Search code examples
sqlgogo-gorm

How do I create unique constraint for multiple columns?


I have following structure and would like to create unique index on (UserId and Contact). Is this possible in gorm?

type Contact struct {
    gorm.Model
    UserId    uint   `gorm:"index;not null"`
    Contact string `gorm:"type:text;not null"`
}

I would like to create table something like

CREATE TABLE contact (...column definitions ...) 
    CONSTRAINT constraint1
    UNIQUE (user_id, contact) 

Solution

  • The doc on models specifies the following for index and uniqueIndex:

    Tag Name Description
    [...] [...]
    index create index with options, use same name for multiple fields creates composite indexes, refer Indexes for details
    uniqueIndex same as index, but create uniqued index
    [...] [...]

    This means that two fields with the same uniqueIndex name will create a composite unique index.

    The full struct definition to use a composite index named compositeindex using your example becomes:

    type Contact struct {
        gorm.Model
        UserId    uint   `gorm:"uniqueIndex:compositeindex;index;not null"`
        Contact   string `gorm:"uniqueIndex:compositeindex;type:text;not null"`
    }