import {test} from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import vm from 'node:vm'; import {PGlite} from '@electric-sql/pglite'; const source=fs.readFileSync(new URL('../deploy-admin-functions.mjs',import.meta.url),'utf8'); const gateway=source.match(/const appGatewayCode = String.raw`([\s\S]*?)\n`;/)[1]; const before=fs.readFileSync(new URL('./fixtures/library-loading-before.js',import.meta.url),'utf8'); const plain=v=>JSON.parse(JSON.stringify(v)); async function fixture(t){ const db=new PGlite();t.after(()=>db.close()); await db.exec(`CREATE TABLE "Node"(company text,"nodeId" numeric,"parentId" numeric,"nodeName" text,"orderId" numeric); CREATE TABLE "CourseBinding"(company text,id numeric,"objectId" text,yhid text,kcid text,"enrollmentStatus" text,syjd text); CREATE TABLE "CommonModel"(company text,"modelId" numeric,"itemId" numeric,"nodeId" numeric,"generalId" numeric,status numeric); CREATE TABLE "PracticeRecord"(company text,yhid numeric,scid numeric,xxcs text); INSERT INTO "CourseBinding" VALUES('7pIbDBJmKx',1,'binding','42','100','active','{}'),('7pIbDBJmKx',2,'assigned','42','200','active','{"110":"110@Unit 1","120":"120@Unit 2"}'); INSERT INTO "CommonModel" VALUES('7pIbDBJmKx',58,1,0,999,99),('7pIbDBJmKx',58,2,0,998,99); INSERT INTO "Node" VALUES('7pIbDBJmKx',110,100,'Unit 1',1),('7pIbDBJmKx',120,100,'Unit 2',2),('7pIbDBJmKx',130,100,'Empty',3),('other',140,100,'Foreign',0); INSERT INTO "CommonModel" SELECT '7pIbDBJmKx',52,i,CASE WHEN i<11 THEN 110 ELSE 120 END,i,99 FROM generate_series(1,20)i; INSERT INTO "CommonModel" SELECT '7pIbDBJmKx',CASE WHEN i%2=0 THEN 52 ELSE 56 END,i,999,i,99 FROM generate_series(1000,15000)i; INSERT INTO "CommonModel" VALUES('other',52,1,110,1,99); INSERT INTO "PracticeRecord" VALUES('7pIbDBJmKx',42,1,'1'),('7pIbDBJmKx',42,1,'2'),('7pIbDBJmKx',42,2,'0'),('7pIbDBJmKx',42,3,'bad'),('7pIbDBJmKx',42,11,'1.5'),('7pIbDBJmKx',99,2,'1'),('other',42,2,'1'); CREATE INDEX cm_node ON "CommonModel"(company,"modelId","nodeId");CREATE INDEX cm_general ON "CommonModel"(company,"modelId","generalId");CREATE INDEX pr_user ON "PracticeRecord"(company,(yhid::text),(scid::text));ANALYZE;`); function harness(code){const calls=[];const c=vm.createContext({Psql:{one:async(sql,args)=>{calls.push({sql,args});return(await db.query(sql,args)).rows[0];},query:async(sql,args)=>{calls.push({sql,args});return(await db.query(sql,args)).rows;}}});vm.runInContext(gateway,c);if(code)vm.runInContext(code,c);c.authorizeRequestedUser=async(_,uid)=>{if(uid!==42)throw Error('denied');return uid;};return{calls,read:input=>c.nodeUnitPage({pid:100,userId:42,psize:2,...input},{})};} return{db,before:harness(before),after:harness()}; } test('unit optimization preserves every row, progress, count, page and assigned-unit fallback',async t=>{ const h=await fixture(t); for(const input of [{},{cpage:2},{cpage:3},{bindingId:'assigned',pid:200},{bindingId:'assigned',pid:200,psize:1,cpage:2}])assert.deepEqual(plain(await h.after.read(input)),plain(await h.before.read(input))); const r=await h.after.read({});assert.deepEqual(plain(r.rows.map(x=>[x.total,x.yx_word,x.process])),[[10,1,10],[10,1,10]]); await assert.rejects(h.after.read({userId:99}),/denied/); await assert.rejects(h.after.read({bindingId:'missing'}),/尚未分配/); await h.db.exec(`UPDATE "CourseBinding" SET "enrollmentStatus"='recycled' WHERE "objectId"='binding'`); await assert.rejects(h.after.read({}),/尚未分配/); }); test('unit progress scans only selected vocabulary using all existing model/node index keys',async t=>{ const h=await fixture(t);await h.after.read({});let discarded=0;const nodes=[]; for(const q of h.after.calls){const result=await h.db.query('EXPLAIN (ANALYZE,FORMAT JSON) '+q.sql,q.args);const walk=p=>{discarded+=Number(p['Rows Removed by Filter']||0)*Number(p['Actual Loops']||1);nodes.push(p);for(const c of p.Plans||[])walk(c);};walk(result.rows[0]['QUERY PLAN'][0].Plan);} assert.ok(discarded<1000,`discarded ${discarded} irrelevant rows while reading only two units`); assert.ok(nodes.some(p=>(p['Index Cond']||'').includes('modelId')&&(p['Index Cond']||'').includes('nodeId')),'must retain numeric model + node lookup'); }); test('numeric scale guards keep historical model/node/word text matching exactly unchanged',async t=>{ const h=await fixture(t); await h.db.exec(`INSERT INTO "CommonModel" VALUES('7pIbDBJmKx',52.0,501,110,501,99),('7pIbDBJmKx',52,502,110.0,502,99),('7pIbDBJmKx',52,503,110,503.0,99);INSERT INTO "PracticeRecord" VALUES('7pIbDBJmKx',42,503,'1');`); for(const input of [{},{bindingId:'assigned',pid:200}])assert.deepEqual(plain(await h.after.read(input)),plain(await h.before.read(input))); const rows=(await h.after.read({})).rows;assert.equal(rows[0].total,11);assert.equal(rows[0].yx_word,1); });