Your Question

How Can I add a unique constraint that ignores existing violations?

type Page struct {
    ShortID   string `json:"shortId" gorm:"uniqueIndex"`
    SourceURL string `json:"sourceURL" gorm:"uniqueIndex"`
}

I'm getting this error everytime i migrate an existing column that violates this new constraint short_id or source_url:

2023/03/31 01:21:06 /Users/_/go/pkg/mod/gorm.io/gorm@v1.24.1-0.20221019064659-5dd2bb482755/callbacks.go:134 ERROR: could not create unique index "idx_pages_source_url" (SQLSTATE 23505) [3.737ms] [rows:0] CREATE UNIQUE INDEX IF NOT EXISTS "idx_pages_source_url" ON "pages" ("source_url") {"level":"error","error":"migration 1680203869: ERROR: could not create unique index \"idx_pages_source_url\" (SQLSTATE 23505)","time":"2023-03-31T01:21:06+01:00","message":"Failed to migrate database - changes were not applied"} {"level":"fatal","error":"migrating database: migration 1680203869: ERROR: could not create unique index \"idx_pages_source_url\" (SQLSTATE 23505)","time":"2023-03-31T01:21:06+01:00","message":"Failed to migrate"}

The document you expected this should be explained

Expected answer