{"record":{"id":"b9318ebd51663d24","repo":"go-gorm/gorm","slug":"violates-check-constraint","errorCode":null,"errorMessage":"violates check constraint","messagePattern":"violates check constraint","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"errors.go","lineNumber":53,"sourceCode":"\tErrInvalidField = errors.New(\"invalid field\")\n\t// ErrEmptySlice empty slice found\n\tErrEmptySlice = errors.New(\"empty slice found\")\n\t// ErrDryRunModeUnsupported dry run mode unsupported\n\tErrDryRunModeUnsupported = errors.New(\"dry run mode unsupported\")\n\t// ErrInvalidDB invalid db\n\tErrInvalidDB = errors.New(\"invalid db\")\n\t// ErrInvalidValue invalid value\n\tErrInvalidValue = errors.New(\"invalid value, should be pointer to struct or slice\")\n\t// ErrInvalidValueOfLength invalid values do not match length\n\tErrInvalidValueOfLength = errors.New(\"invalid association values, length doesn't match\")\n\t// ErrPreloadNotAllowed preload is not allowed when count is used\n\tErrPreloadNotAllowed = errors.New(\"preload is not allowed when count is used\")\n\t// ErrDuplicatedKey occurs when there is a unique key constraint violation\n\tErrDuplicatedKey = errors.New(\"duplicated key not allowed\")\n\t// ErrForeignKeyViolated occurs when there is a foreign key constraint violation\n\tErrForeignKeyViolated = errors.New(\"violates foreign key constraint\")\n\t// ErrCheckConstraintViolated occurs when there is a check constraint violation\n\tErrCheckConstraintViolated = errors.New(\"violates check constraint\")\n)\n","sourceCodeStart":35,"sourceCodeEnd":55,"githubUrl":"https://github.com/go-gorm/gorm/blob/1d6ce99528060be18a42be09aca8d39efcb47f28/errors.go#L35-L55","documentation":"ErrCheckConstraintViolated is GORM's translated sentinel error for a database CHECK constraint violation. When gorm.Open is configured with TranslateEnabled: true, a driver error like PostgreSQL's '23514 violates check constraint' is rewritten to this error so callers can match it with errors.Is. It means the INSERT or UPDATE you ran produced column values that fail a CHECK constraint defined on the table (e.g. CHECK (price >= 0)).","triggerScenarios":"Inserting or updating a row whose column value breaks a CHECK constraint - either one declared via the gorm tag `gorm:\"check:price>0\"` (created by AutoMigrate) or one already defined in the DB - while the connection has error translation enabled (gorm.Open(dia, &gorm.Config{TranslateEnabled: true})).","commonSituations":"Adding a `check:` gorm tag to an existing model and then writing legacy/edge data (negative amounts, empty strings on CHECK (name <> '')); backfilling historical rows that predate the constraint; test fixtures generated with zero values that violate non-zero checks; MySQL 8 / PostgreSQL / SQLite behaving differently on constraint enforcement so the bug appears only in one environment.","solutions":["Fix the data being written so it satisfies the constraint (usually a validation gap in the application layer).","Inspect the constraint in the DB (\\d table or SHOW CREATE TABLE) to confirm which CHECK fires and on which column.","If the business rule changed, drop or alter the constraint via a migration before writing the new data.","If pre-existing rows violate it, run a data-cleanup UPDATE before re-enabling/enforcing the constraint."],"exampleFix":"// before\ndb.Create(&Order{Price: -5}) // violates CHECK (price >= 0)\n\n// after\nif order.Price < 0 {\n    return errors.New(\"price must be non-negative\")\n}\ndb.Create(&order)","handlingStrategy":"try-catch","validationCode":"func validPrice(p int) bool { return p >= 0 }\n// before write:\nif !validPrice(order.Price) { return ErrValidation }","typeGuard":"func isCheckViolation(err error) bool { return errors.Is(err, gorm.ErrCheckConstraintViolated) }","tryCatchPattern":"err := db.Create(&order).Error\nif err != nil {\n    if errors.Is(err, gorm.ErrCheckConstraintViolated) {\n        // map to 422 validation error, log the offending record\n    }\n    return err // real DB failure\n}","preventionTips":["Enable TranslateEnabled: true so constraint errors are matchable sentinels instead of driver strings.","Mirror CHECK constraints with app-side validation so users get field-level errors, not DB rejections.","After adding a check tag, run a data audit query for existing violating rows before deploying."],"tags":["gorm","database","constraint","integrity","postgresql","mysql"],"backgroundTag":null,"analyzedSha":"1d6ce99528060be18a42be09aca8d39efcb47f28","analyzedAt":"2026-08-15T13:01:23.433Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}