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.
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.
Most helpful comment
Done, the syntax is
But keep in mind that index name is ignored and Postgres will generate index name for you.