先核來源與已訂規則
本例目標要求數量有值且大於零。只用 CHECK(quantity>0),NULL 會得未知而非零,所以未被拒。更正須同時有 NOT NULL 及正數 CHECK。
| 紀錄 | 輸入 JSON |
|---|---|
| 原例輸入 | {"quantity":null} |
比較兩條實際路徑
欠值實際以 NOT NULL 代碼 1299 失敗,目標沒有行。零則是 CHECK 代碼 275,兩個原因不同。
| 路徑 | 輸出 JSON |
|---|---|
| 錯誤路徑 | {"error":null,"records":[{"quantity":null}]} |
| 更正路徑 | {"error":{"code":1299},"records":[]} |
import {DatabaseSync} from 'node:sqlite';
import {TextDecoder} from 'node:util';
import {inflateSync} from 'node:zlib';
import {posix} from 'node:path';
import {createHash} from 'node:crypto';
const rows=(db,sql)=>db.prepare(sql).all().map(r=>({...r}));
const failed=(action)=>{try{action();return null;}catch(e){return {code:e.errcode??e.code??e.name};}};
import assert from 'node:assert/strict';
const run=function run(i,corrected=true){
const db=new DatabaseSync(':memory:');try{db.exec('CREATE TABLE target(quantity INTEGER '+(corrected?'NOT NULL ':'')+'CHECK(quantity>0));');
const error=failed(()=>db.prepare('INSERT INTO target VALUES(?)').run(i.quantity));
return {error,records:rows(db,'SELECT * FROM target')};
}finally{db.close();}
};
const cases=[{"label":"misleading base","input":{"quantity":null},"expected":{"error":null,"records":[{"quantity":null}]},"corrected":false},{"label":"corrected base","input":{"quantity":null},"expected":{"error":{"code":1299},"records":[]},"corrected":true},{"label":"zero violates positive check","input":{"quantity":0},"expected":{"error":{"code":275},"records":[]},"corrected":true},{"label":"positive quantity accepted","input":{"quantity":2},"expected":{"error":null,"records":[{"quantity":2}]},"corrected":true}];
for(const test of cases){
const actual=run(test.input,test.corrected);
assert.deepEqual(actual,test.expected,test.label);
console.log(test.label,actual);
}
下次載入前核邊界
零拒收,正數 2 存入。要求有值並沒有放寬正數範圍。
| 情況 | 輸入 JSON | 預期輸出 JSON |
|---|---|---|
| 零違反數值範圍 | {"quantity":0} | {"error":{"code":275},"records":[]} |
| 正數二可收 | {"quantity":2} | {"error":null,"records":[{"quantity":2}]} |
此必填欄只用 CHECK(quantity>0) 足夠嗎?
查看參考答案
不足夠,要加 NOT NULL。欠值會失敗且不建行,2 才收。