先核來源與已訂規則
本例二進位欄是 [0,255,65],沒有約定作 UTF-8 文字。先轉文字再編回,無效字節 255 被替代,反而增字節。更正用原 Buffer 綁 SQLite,再查真正 BLOB 類型、長度及內容。
| 紀錄 | 輸入 JSON |
|---|---|
| 原例輸入 | {"bytes":[0,255,65]} |
比較兩條實際路徑
錯字節成 [0,239,191,189,65]、長五;更正仍 [0,255,65]、長三,儲存類型 blob。
| 路徑 | 輸出 JSON |
|---|---|
| 錯誤路徑 | {"storage":"blob","length":5,"bytes":[0,239,191,189,65]} |
| 更正路徑 | {"storage":"blob","length":3,"bytes":[0,255,65]} |
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(content BLOB);');let content=i.bytes===null?null:Buffer.from(i.bytes);
if(!corrected&&content!==null)content=Buffer.from(content.toString('utf8'),'utf8');db.prepare('INSERT INTO target VALUES(?)').run(content);
const r=db.prepare('SELECT typeof(content) AS storage,length(content) AS length,content FROM target').get();
return {storage:r.storage,length:r.length,bytes:r.content===null?null:[...r.content]};
}finally{db.close();}
};
const cases=[{"label":"misleading base","input":{"bytes":[0,255,65]},"expected":{"storage":"blob","length":5,"bytes":[0,239,191,189,65]},"corrected":false},{"label":"corrected base","input":{"bytes":[0,255,65]},"expected":{"storage":"blob","length":3,"bytes":[0,255,65]},"corrected":true},{"label":"empty BLOB retains storage kind","input":{"bytes":[]},"expected":{"storage":"blob","length":0,"bytes":[]},"corrected":true},{"label":"explicit SQL NULL is separate","input":{"bytes":null},"expected":{"storage":"null","length":null,"bytes":null},"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);
}
下次載入前核邊界
空 BLOB 是 blob、長零、[];明確 null 則是 null、長 null、內容 null。
| 情況 | 輸入 JSON | 預期輸出 JSON |
|---|---|---|
| 空 BLOB 仍保其類型 | {"bytes":[]} | {"storage":"blob","length":0,"bytes":[]} |
| 明確 SQL 空值 | {"bytes":null} | {"storage":"null","length":null,"bytes":null} |
可讀文字看似相符,足夠核二進位完整嗎?
查看參考答案
不足,要比真正位元組及儲存類型。此更正搬移保住原本三個字節。