SQLite CHECK 为什么放过 NULL?用 12 个测试拆开空值、范围与类型约束
给库存数量写下 CHECK(qty >= 0),很容易以为已经保证“数量存在,而且是非负整数”。实际只完成了一部分。NULL 不是零,也不是负数;普通表的 INTEGER 声明也不等于只收整数。把空值、范围和类型拆开验证,才能避免看似严谨的建表语句留下漏洞。
配图为独立模型生成的概念示意图,不是真实数据库界面。
一、CHECK 拒绝的是假,不是未知
SQL 比较可得到真、假或未知。对本例来说,0 >= 0 和 8 >= 0 的结果为 1,-1 >= 0 为 0,而 NULL >= 0 为 NULL。SQLite 检查 CHECK 表达式时,会按数值方式判断结果:零构成违反约束,NULL 或非零则不构成违反。因此“没有证明不合格”和“已经证明合格”不是同一回事,CHECK 采用的是前者这条边界。规则见 SQLite CHECK 官方说明。
如果字段必须填写,就明确加上 NOT NULL,再用 CHECK(qty >= 0) 限制范围。两条约束各司其职,不能把非负检查当成空值检查。下面同时保留四种表定义,让差异直接体现在测试中,而不是只看建表语句猜结果。
在库存场景中,尚未盘点与确认库存为零是两种状态。若允许前者,保留 NULL 可以表达未知;若流程要求先填写数量,就拒绝 NULL,而不是为了通过校验把它替换为零。这个选择属于业务含义,不能由数据库比较运算代替决定。
二、用十二个测试固定真实行为
保存以下完整代码为 check_constraints.py,执行 python check_constraints.py,再执行 python -O check_constraints.py。示例只使用 Python 标准库,每个测试单独创建内存数据库并自动关闭,不连接外部服务、不读取业务库、不创建数据库文件。运行前会输出 Python 与实际链接的 SQLite 版本;STRICT 要求 SQLite 至少为 3.37.0,旧版本会明确退出,不会偷偷跳过关键测试。
import sqlite3
import sys
import unittest
class CheckConstraintTests(unittest.TestCase):
def setUp(self):
self.db = sqlite3.connect(':memory:')
self.addCleanup(self.db.close)
self.db.execute(
'CREATE TABLE loose(qty INTEGER CHECK(qty >= 0))'
)
self.db.execute(
'CREATE TABLE required('
'qty INTEGER NOT NULL CHECK(qty >= 0))'
)
self.db.execute(
'CREATE TABLE strict_nullable('
'qty INTEGER CHECK(qty >= 0)) STRICT'
)
self.db.execute(
'CREATE TABLE strict_required('
'qty INTEGER NOT NULL CHECK(qty >= 0)) STRICT'
)
def test_predicate_has_three_results(self):
row = self.db.execute(
'SELECT NULL >= 0, 0 >= 0, 8 >= 0, -1 >= 0'
).fetchone()
self.assertEqual(row, (None, 1, 1, 0))
def test_check_accepts_null(self):
self.db.execute('INSERT INTO loose VALUES (?)', (None,))
self.assertEqual(
self.db.execute('SELECT qty FROM loose').fetchone(),
(None,),
)
def test_check_accepts_zero(self):
self.db.execute('INSERT INTO loose VALUES (?)', (0,))
self.assertEqual(
self.db.execute('SELECT qty FROM loose').fetchone(), (0,)
)
def test_check_accepts_positive(self):
self.db.execute('INSERT INTO loose VALUES (?)', (8,))
self.assertEqual(
self.db.execute('SELECT qty FROM loose').fetchone(), (8,)
)
def test_check_rejects_negative(self):
with self.assertRaises(sqlite3.IntegrityError):
self.db.execute('INSERT INTO loose VALUES (?)', (-1,))
def test_not_null_rejects_null(self):
with self.assertRaises(sqlite3.IntegrityError):
self.db.execute('INSERT INTO required VALUES (?)', (None,))
def test_update_is_checked(self):
self.db.execute('INSERT INTO loose VALUES (8)')
with self.assertRaises(sqlite3.IntegrityError):
self.db.execute('UPDATE loose SET qty = -1')
self.assertEqual(
self.db.execute('SELECT qty FROM loose').fetchone(), (8,)
)
def test_ordinary_table_accepts_text_and_real(self):
self.db.executemany(
'INSERT INTO loose VALUES (?)', [('oops',), (1.5,)]
)
rows = self.db.execute(
'SELECT qty, typeof(qty), qty >= 0 FROM loose ORDER BY rowid'
).fetchall()
self.assertEqual(rows, [('oops', 'text', 1), (1.5, 'real', 1)])
def test_numeric_text_is_converted(self):
self.db.execute('INSERT INTO loose VALUES (?)', ('3',))
self.db.execute('INSERT INTO strict_required VALUES (?)', ('3',))
for query in (
'SELECT qty, typeof(qty) FROM loose',
'SELECT qty, typeof(qty) FROM strict_required',
):
with self.subTest(query=query):
self.assertEqual(self.db.execute(query).fetchone(), (3, 'integer'))
def test_strict_still_accepts_null_without_not_null(self):
self.db.execute('INSERT INTO strict_nullable VALUES (?)', (None,))
self.assertEqual(
self.db.execute('SELECT qty FROM strict_nullable').fetchone(),
(None,),
)
def test_strict_rejects_unconvertible_values(self):
for value in ('oops', 1.5):
with self.subTest(value=value):
with self.assertRaises(sqlite3.IntegrityError):
self.db.execute(
'INSERT INTO strict_required VALUES (?)', (value,)
)
def test_strict_domain_needs_both_constraints(self):
for value in (None, -1):
with self.subTest(value=value):
with self.assertRaises(sqlite3.IntegrityError):
self.db.execute(
'INSERT INTO strict_required VALUES (?)', (value,)
)
self.db.executemany(
'INSERT INTO strict_required VALUES (?)', [(0,), (8,)]
)
self.assertEqual(
self.db.execute(
'SELECT qty FROM strict_required ORDER BY qty'
).fetchall(),
[(0,), (8,)],
)
if __name__ == '__main__':
print(f'Python {sys.version.split()[0]}; SQLite {sqlite3.sqlite_version}',
flush=True)
if sqlite3.sqlite_version_info < (3, 37, 0):
raise SystemExit('This example requires SQLite 3.37.0 or newer.')
unittest.main(verbosity=2)本次实测环境为 Python 3.12.14、SQLite 3.53.1,普通模式与 -O 模式均为十二项通过。断言使用 unittest 方法而非会被优化删除的 assert 语句。测试不仅检查插入,也验证把已有数量更新为负数会失败;这里没有借此推导更复杂的事务或批处理结论。
三、INTEGER 亲和性不等于整数门禁
普通表会根据类型亲和性尝试转换值,而不是把列声明当作绝对类型限制。本例中字符串 '3' 被存为整数 3;'oops' 保持文本,1.5 保持实数。更值得注意的是,'oops' 仍通过 qty >= 0:在这个比较中,它没有变成数值,而文本存储类排序高于数值存储类,比较结果为真。这不是“任意字符串等于零”,也不能脱离列亲和性把结果套到其他表达式。代码同时核对值、typeof 和比较结果,依据见 类型转换与比较规则。
四、STRICT 也需要业务约束
给表加 STRICT 后,INTEGER 列会拒绝不能无损转换的 'oops' 与 1.5,却仍能接受并转换 '3'。所以严格表约束的是可存储类型,不保证调用方传入的一定是 Python 整数。没有 NOT NULL 的严格表仍允许 NULL,CHECK 的空值语义也没有变化,详见 STRICT Tables。
若业务定义就是“必填、整数、非负”,本例的 strict_required 将这三件事分别交给 NOT NULL、STRICT INTEGER 与 CHECK。若还要求库存上限、特定单位或拒绝数字字符串,需要另加相应规则。验收时也应分组测试空值、边界值、错误类型和更新路径:一条通过的范围断言,不是完整的数据契约。


