Your Question
I have a model
type Numbering struct {
gorm.Model
Year int `gorm:"check:year>0;" json:"year"`
... other fieds
}
func Migrate (tx * gorm.DB) error {
if err := tx.AutoMigrate(&Numbering{}); err != nil {return err }
return nil
if is the first time migration then migration goes well, but if you modify structs and want to run migration again , instead of altering model and drop existing constraint/index if existing and create a new one, it modify database table by adding new constraint/index with same name. As the result I got db error
go:64 mssql: Could not create constraint or index. See previous errors.
[191.354ms] [rows:0] ALTER TABLE "Numbering" ADD CONSTRAINT "chk_Numbering_Period" CHECK (period>0)
mssql: Could not create constraint or index. See previous errors.
gorm AuotMigrate per each model to drop existing constraints and create a new constraints but it adding as if it does not exists
The document you expected this should be explained
Expected answer
There is a possibility to alter AutoMigrate to check for constraint/index before re-creating them
Comment From: rngallen
After following I have discovered the query used to check constraint by gorm
SELECT count(*) FROM sys.foreign_keys as F inner join sys.tables as T on F.parent_object_id=T.object_id inner join INFORMATION_SCHEMA.TABLES as I on I.TABLE_NAME = T.name WHERE F.name = 'chk_numbering_year' AND I.TABLE_NAME = 'numberings' AND I.TABLE_SCHEMA like '%' AND I.TABLE_CATALOG = 'EVOERMS';
returns null as sys.foregin_keys
as no value as it was supposed to be
SELECT count(*) FROM sys.check_constraints as F inner join sys.tables as T
on F.parent_object_id=T.object_id inner
join INFORMATION_SCHEMA.TABLES as I on I.TABLE_NAME = T.name WHERE F.name = 'chk_numbering_year'
AND I.TABLE_NAME = 'numberings' AND I.TABLE_SCHEMA like '%' AND I.TABLE_CATALOG = 'EVOERMS';