先核來源與已訂規則
本例目標數量 2 須正數且非 NULL。V2 試所附替代值;BEGIN 前先標 V2,之後 −1 更新失敗也不會撤回該標記。更正兩者放同一交易,錯就一起回復。
| 紀錄 | 輸入 JSON |
|---|---|
| 原例輸入 | {"nextQuantity":-1} |
比較兩條實際路徑
更正失敗後真正數量 2、記錄 V1;錯拆開狀態卻是數量 2、記錄 V2,誤表搬移已完成。
| 路徑 | 輸出 JSON |
|---|---|
| 錯誤路徑 | {"error":{"code":275},"version":"V2","records":[{"quantity":2}]} |
| 更正路徑 | {"error":{"code":275},"version":"V1","records":[{"quantity":2}]} |
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 ledger(version TEXT);INSERT INTO ledger VALUES('V1');CREATE TABLE target(quantity INTEGER NOT NULL CHECK(quantity>0));INSERT INTO target VALUES(2);");
if(!corrected)db.exec("UPDATE ledger SET version='V2';");db.exec('BEGIN;');
const error=failed(()=>{db.prepare('UPDATE target SET quantity=?').run(i.nextQuantity);if(corrected)db.exec("UPDATE ledger SET version='V2';");db.exec('COMMIT;');});
if(error)db.exec('ROLLBACK;');return {error,version:db.prepare('SELECT version FROM ledger').get().version,records:rows(db,'SELECT * FROM target')};
}finally{db.close();}
};
const cases=[{"label":"misleading base","input":{"nextQuantity":-1},"expected":{"error":{"code":275},"version":"V2","records":[{"quantity":2}]},"corrected":false},{"label":"corrected base","input":{"nextQuantity":-1},"expected":{"error":{"code":275},"version":"V1","records":[{"quantity":2}]},"corrected":true},{"label":"successful data and ledger commit","input":{"nextQuantity":4},"expected":{"error":null,"version":"V2","records":[{"quantity":4}]},"corrected":true},{"label":"required target value missing","input":{"nextQuantity":null},"expected":{"error":{"code":1299},"version":"V1","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);
}
下次載入前核邊界
有效替代 4 可連 V2 提交;替代 null 錯 1299,仍保 V1/2。
| 情況 | 輸入 JSON | 預期輸出 JSON |
|---|---|---|
| 資料及版本同時提交 | {"nextQuantity":4} | {"error":null,"version":"V2","records":[{"quantity":4}]} |
| 所需替代值欠缺 | {"nextQuantity":null} | {"error":{"code":1299},"version":"V1","records":[{"quantity":2}]} |
−1 失敗後,哪個版本標記才符合實況?
查看參考答案
V1,V2 資料結果沒有提交。成功搬移交易前,V1 與數量 2 一起保留。