跳至內容
Astera Technology

BLOB 當文字轉一圈,搬移後為何多了字節?

二進位欄用位元組搬移,空 BLOB 與 NULL 也要分開保留。

下載完整個案資料及參考答案 ↓

先核來源與已訂規則

本例二進位欄是 [0,255,65],沒有約定作 UTF-8 文字。先轉文字再編回,無效字節 255 被替代,反而增字節。更正用原 Buffer 綁 SQLite,再查真正 BLOB 類型、長度及內容。

已填假設輸入
紀錄輸入 JSON
原例輸入{"bytes":[0,255,65]}
下載可編輯 CSV ↓

比較兩條實際路徑

錯字節成 [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]}
下載可編輯 CSV ↓
本地 Node.js 程序:22.23.3 或 24.14.1
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}
下載可編輯 CSV ↓

可讀文字看似相符,足夠核二進位完整嗎?

查看參考答案

不足,要比真正位元組及儲存類型。此更正搬移保住原本三個字節。

相關資源