Pg: 'Unique' for multiple columns?

Created on 24 Dec 2017  路  3Comments  路  Source: go-pg/pg

I didn't find any way to make "unique" constraint for multiple columns in a table at once. I wanted something like this:

type Plays struct {
    Id               uint16 `sql:",pk,unique"`
    CreatedAt        time.Time `sql:"default:(now() at time zone 'utc')"`
    GameId           uint16 `pg:",fk:Game"`
    Game             *Game
    PlayerId         uint16 `pg:",fk:Player"`
    Player           *Player
    Score          uint64
} `pg:",unique:(game_id,player_id)"`

Is it possible or it's work in progress yet? I can maybe try and help.

Most helpful comment

Done, the syntax is

type Language struct {
    Name string `sql:"unique:idx_name_code"`
    Code string `sql:"unique:idx_name_code"`
}

But keep in mind that index name is ignored and Postgres will generate index name for you.

All 3 comments

It is not possible yet. And I don't think Go allows syntax you suggested.

I don't see a nice/simple way to support multi-column constraints. It could be

type Play struct {
    tableName struct{} `pg:",unique:column1,column2"`
}

But it is not very nice (unique tag on tableName? weird) and it does not support multiple unique indexes.

For now I prefer to not support this and just recommend to use good old SQL:

_, err := db.Model(&Play{}).Exec(`
    CREATE UNIQUE INDEX plays_game_id_player_id_unq
    ON ?TableName(game_id, player_id)
`)

How about syntax which uses in gorm?

type Language struct {
    Name string `pg:"unique_index:idx_name_code"`
    Code string `pg:"unique_index:idx_name_code"`
}

Done, the syntax is

type Language struct {
    Name string `sql:"unique:idx_name_code"`
    Code string `sql:"unique:idx_name_code"`
}

But keep in mind that index name is ignored and Postgres will generate index name for you.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Alireza-Ta picture Alireza-Ta  路  3Comments

pahanini picture pahanini  路  4Comments

mamal72 picture mamal72  路  3Comments

l0gicgate picture l0gicgate  路  5Comments

eicca picture eicca  路  3Comments