Your Question
I was trying to use the unique constraint in the email field of my model but this is not being migrated to the database.
type Account struct {
gorm.Model
ID string `sql:"type:uuid;primary_key;default:uuid_generate_v4()"`
Email string `gorm:"unique;not null" json:"email"` // <- Here
Password string `gorm:"not null" json:"password"`
User User `gorm:"foreignKey:AccountID;references:ID"`
}
When I do automatic migration with AutoMigrate()
everything works, however when I dump the tables with pg_dump
the email field in the table is not unique:
CREATE TABLE public.accounts (
id text NOT NULL,
created_at timestamp with time zone,
updated_at timestamp with time zone,
deleted_at timestamp with time zone,
email text NOT NULL,
password text NOT NULL
);
The document you expected this should be explained
https://gorm.io/docs/constraints.html https://gorm.io/docs/models.html#Fields-Tags
Expected answer
CREATE TABLE public.accounts (
id text NOT NULL,
created_at timestamp with time zone,
updated_at timestamp with time zone,
deleted_at timestamp with time zone,
email text UNIQUE NOT NULL, -- <- unique
password text NOT NULL
);
Comment From: piheta
Got the same problem, this does not catch it:
if errors.Is(result.Error, gorm.ErrDuplicatedKey) {
return weberrors.NewError(409, "employee with this id alread exists")
}
{
"error": "ERROR: duplicate key value violates unique constraint \"employees_pkey\" (SQLSTATE 23505)"
}
Im using psql for the db.
Comment From: gg1229505432
Sample:
type IndexTest struct {
FieldA string gorm:"unique;index"
// unique and index
FieldB string gorm:"unique"
// unique
FieldC string `gorm:"index:,unique"` // uniqueIndex
FieldD string `gorm:"uniqueIndex;index"` // uniqueIndex and index
FieldE1 string `gorm:"uniqueIndex:uniq_field_e1_e2"` // mul uniqueIndex
FieldE2 string `gorm:"uniqueIndex:uniq_field_e1_e2"`
FieldF1 string `gorm:"uniqueIndex:uniq_field_f1_f2;index"` // mul uniqueIndex and index
FieldF2 string `gorm:"uniqueIndex:uniq_field_f1_f2;"`
FieldG string `gorm:"unique;uniqueIndex"` // unique and uniqueIndex
FieldH1 string `gorm:"unique;uniqueIndex:uniq_field_h1_h2"` // unique and mul uniqueIndex
FieldH2 string `gorm:"uniqueIndex:uniq_field_h1_h2"` // unique and mul uniqueIndex
}
path: schema/index_test.go
Comment From: dkrieger
still broken
Comment From: kiennt1-hblab
Have you used this yet? gorm.Config{TranslateError: true}
Comment From: dimas-cyriaco
I'm having the same problem. errors.Is(result.Error, gorm.ErrDuplicatedKey)
does not work.
Comment From: 1514599514
PgSQL still has this issue