先核來源與已訂規則
本例數量須有值並為正整數,兩路都要 NOT NULL。STRICT INTEGER 核可無損轉存的類型,但 −2 本來就是整數。正數範圍要另外 CHECK(quantity>0),不能期望 STRICT 自行加此規則。
| 紀錄 | 輸入 JSON |
|---|---|
| 原例輸入 | {"quantity":-2} |
比較兩條實際路徑
更正後 −2 違 CHECK275;不能轉整數的 wrong 違類型 3091。拒收記錄便可分辨缺哪項要求。
| 路徑 | 輸出 JSON |
|---|---|
| 錯誤路徑 | {"error":null,"records":[{"quantity":-2}]} |
| 更正路徑 | {"error":{"code":275},"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 NOT NULL'+(corrected?' CHECK(quantity>0)':'')+') STRICT;');
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":-2},"expected":{"error":null,"records":[{"quantity":-2}]},"corrected":false},{"label":"corrected base","input":{"quantity":-2},"expected":{"error":{"code":275},"records":[]},"corrected":true},{"label":"nonconvertible text rejected by type","input":{"quantity":"wrong"},"expected":{"error":{"code":3091},"records":[]},"corrected":true},{"label":"positive whole value","input":{"quantity":2},"expected":{"error":null,"records":[{"quantity":2}]},"corrected":true},{"label":"missing required whole count","input":{"quantity":null},"expected":{"error":{"code":1299},"records":[]},"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 同時符合類型及範圍。數量 NULL 欠值則違 NOT NULL1299,不建行。
| 情況 | 輸入 JSON | 預期輸出 JSON |
|---|---|---|
| 文字無法轉為所需類型 | {"quantity":"wrong"} | {"error":{"code":3091},"records":[]} |
| 正整數數量 | {"quantity":2} | {"error":null,"records":[{"quantity":2}]} |
| 必填整數數量欠缺 | {"quantity":null} | {"error":{"code":1299},"records":[]} |
能存成整數,負二在此就合資格嗎?
查看參考答案
不是,類型雖對,仍違本例正數要求。更正目標不會存負二行。