跳至內容
Astera Technology

來源有面積,為何寫入計算欄卻失敗?

寫入已訂基礎尺寸,再回讀資料庫計算面積。

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

先核來源與已訂規則

本例目標把 area 定為 width×height 的儲存計算欄,所附尺寸是必填小整數。來源 99 留在輸入可對照,但不是獲准直接寫入的面積替代值。

已填假設輸入
紀錄輸入 JSON
原例輸入{"width":2,"height":3,"sourceArea":99}
下載可編輯 CSV ↓

比較兩條實際路徑

當普通欄插入 area 會失敗。只寫基礎值才得 2×3=6。width 欠缺仍違 NOT NULL,省略計算欄不等於免其輸入。

錯誤與更正路徑的輸出
路徑輸出 JSON
錯誤路徑{"error":{"code":1},"records":[]}
更正路徑{"error":null,"records":[{"width":2,"height":3,"area":6}]}
下載可編輯 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(width INTEGER NOT NULL,height INTEGER NOT NULL,area INTEGER GENERATED ALWAYS AS(width*height) STORED);');
      const error=failed(()=>corrected?db.prepare('INSERT INTO target(width,height) VALUES(?,?)').run(i.width,i.height):db.prepare('INSERT INTO target(width,height,area) VALUES(?,?,?)').run(i.width,i.height,i.sourceArea));
      return {error,records:rows(db,'SELECT * FROM target')};
    }finally{db.close();}
  };
const cases=[{"label":"misleading base","input":{"width":2,"height":3,"sourceArea":99},"expected":{"error":{"code":1},"records":[]},"corrected":false},{"label":"corrected base","input":{"width":2,"height":3,"sourceArea":99},"expected":{"error":null,"records":[{"width":2,"height":3,"area":6}]},"corrected":true},{"label":"changed base dimensions","input":{"width":4,"height":3,"sourceArea":99},"expected":{"error":null,"records":[{"width":4,"height":3,"area":12}]},"corrected":true},{"label":"missing required base","input":{"width":null,"height":3,"sourceArea":99},"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);
}
下載可執行例子 ↓

下次載入前核邊界

width 改 4 便算 12;欠 width 則沒有目標行。

可編輯邊界紀錄及預期輸出
情況輸入 JSON預期輸出 JSON
基礎寬度有變{"width":4,"height":3,"sourceArea":99}{"error":null,"records":[{"width":4,"height":3,"area":12}]}
必填尺寸欠缺{"width":null,"height":3,"sourceArea":99}{"error":{"code":1299},"records":[]}
下載可編輯 CSV ↓

來源面積 99 應否寫過計算值 6?

查看參考答案

不應,此結構由資料庫計算。寫 width2、height3,回讀 area6;要容許替代值,須另訂結構。

相關資源