Open 0x41337 opened 6 months ago
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.
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
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.
When I do automatic migration with
AutoMigrate()
everything works, however when I dump the tables withpg_dump
the email field in the table is not unique:The document you expected this should be explained
https://gorm.io/docs/constraints.html https://gorm.io/docs/models.html#Fields-Tags
Expected answer