Skip to content

CHECK Constraint Violation

错误信息

                新行 for 关系 violates 检查 constraint
              

快速摘要

你 tried 到 insert or 更新值 那个失败 CHECK constraint — 自定义条件如 `price > 0` or `age >= 18`.

为什么发生

  • Inserting 负 price 当 constraint 需要 price > 0

  • Inserting 无效 age, date 范围, or other out-的-边界值

  • Application logic 做不 验证数据之前发送到 数据库

最小示例

✗ 错误代码
INSERT INTO products (id, name, price) VALUES (1, 'Widget', -9.99);
-- But price has CHECK (price > 0)
✓ 修复代码
INSERT INTO products (id, name, price) VALUES (1, 'Widget', 9.99);

负 price violates CHECK constraint. Using 正 price satisfies 它.

如何诊断

  • 读取错误到 identify 哪个 CHECK constraint 是 violated

  • 检查 constraint 定义: \d table_name in psql

  • 验证值 你是 trying 到 insert 针对 constraint 条件

如何修复

  • Provide 值那个 satisfies CHECK 条件

  • 更新 constraint 如果 business 规则有 更改

  • 验证数据 in 你的 application 之前 inserting

如何预防

  • 验证数据 in 你的 application using 相同规则 as CHECK constraint

  • Use 表单 validation 到 prevent 无效输入

  • Document CHECK constraints and 它们的 business meaning

相关资源

相关术语

相关课程

← 返回语言