|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#29538] A write answers the record the next read of the row answers: every |
| 5 | + * stored declared column the driver did not echo is `null`, as on driver-sql. |
| 6 | + * |
| 7 | + * The write-side twin of #29408 (`selected-declared-columns-answered.test.ts`, |
| 8 | + * the read half). The driver here stores only the keys a write carried and |
| 9 | + * echoes exactly the stored row, the driver-mongodb / driver-memory shape. |
| 10 | + * Measured on `origin/main` before the fix, through the engine and the |
| 11 | + * protocol doors: on that shape every write answer below left out each |
| 12 | + * unwritten declared column (`note`, `qty` and the registry-injected system |
| 13 | + * columns) while the next `findOne` answered them `null`, and the formula |
| 14 | + * `doubled` read `null` in the write answer (a fault on the missing `qty`) |
| 15 | + * but `-1` on the read. driver-sql answered both the same. |
| 16 | + * |
| 17 | + * driver-mongodb is pinned in its own package |
| 18 | + * (`mongodb-declared-column-null-on-write.test.ts`) and driver-sql with the |
| 19 | + * security plugin composed in `@objectstack/runtime` |
| 20 | + * (`declared-column-null-on-write.test.ts`), where a field-level-refused |
| 21 | + * column is pinned absent; this file is the driver-memory shape's pin. |
| 22 | + */ |
| 23 | + |
| 24 | +import { describe, it, expect, beforeEach } from 'vitest'; |
| 25 | +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; |
| 26 | + |
| 27 | +import { ObjectQL } from './engine.js'; |
| 28 | + |
| 29 | +type Row = Record<string, unknown>; |
| 30 | + |
| 31 | +interface DriverAst { |
| 32 | + where?: Record<string, unknown>; |
| 33 | + fields?: string[]; |
| 34 | + limit?: number; |
| 35 | +} |
| 36 | + |
| 37 | +function makeSparseDriver(name: string) { |
| 38 | + const tables = new Map<string, Map<string, Row>>(); |
| 39 | + const tableFor = (o: string): Map<string, Row> => { |
| 40 | + let t = tables.get(o); |
| 41 | + if (!t) { t = new Map<string, Row>(); tables.set(o, t); } |
| 42 | + return t; |
| 43 | + }; |
| 44 | + // Equality on plain keys only. A combinator or any other operator is |
| 45 | + // REFUSED, never read as a field name. |
| 46 | + const matches = (row: Row, where: Record<string, unknown> | undefined): boolean => { |
| 47 | + if (!where) return true; |
| 48 | + for (const [k, v] of Object.entries(where)) { |
| 49 | + if (k.startsWith('$')) throw new Error(`sparse driver: filter operator ${k} is not implemented`); |
| 50 | + if (v !== null && typeof v === 'object') throw new Error(`sparse driver: operator on ${k} is not implemented`); |
| 51 | + if ((row[k] ?? null) !== (v ?? null)) return false; |
| 52 | + } |
| 53 | + return true; |
| 54 | + }; |
| 55 | + const run = (object: string, ast: DriverAst | undefined): Row[] => { |
| 56 | + let out = Array.from(tableFor(object).values()).filter((r) => matches(r, ast?.where)); |
| 57 | + if (typeof ast?.limit === 'number') out = out.slice(0, ast.limit); |
| 58 | + const fields = Array.isArray(ast?.fields) && ast.fields.length > 0 ? ast.fields : undefined; |
| 59 | + return out.map((r) => (fields |
| 60 | + ? Object.fromEntries(Object.entries(r).filter(([k]) => k === 'id' || fields.includes(k))) |
| 61 | + : { ...r })); |
| 62 | + }; |
| 63 | + let seq = 0; |
| 64 | + // A key given `undefined` is not stored, as driver-mongodb's insert doors |
| 65 | + // drop it; the echo is the stored row and nothing else. |
| 66 | + const stored = (data: Row): Row => Object.fromEntries(Object.entries(data).filter(([, v]) => v !== undefined)); |
| 67 | + const driver = { |
| 68 | + name, version: '0.0.0', supports: {}, |
| 69 | + async connect(): Promise<void> {}, |
| 70 | + async disconnect(): Promise<void> {}, |
| 71 | + async checkHealth(): Promise<boolean> { return true; }, |
| 72 | + async execute(): Promise<null> { return null; }, |
| 73 | + async find(object: string, ast?: DriverAst): Promise<Row[]> { return run(object, ast); }, |
| 74 | + async findOne(object: string, ast?: DriverAst): Promise<Row | null> { return run(object, ast)[0] ?? null; }, |
| 75 | + async create(object: string, data: Row): Promise<Row> { |
| 76 | + seq += 1; |
| 77 | + const row: Row = { ...stored(data), id: (data.id as string | undefined) ?? `new_${seq}` }; |
| 78 | + tableFor(object).set(String(row.id), row); |
| 79 | + return { ...row }; |
| 80 | + }, |
| 81 | + async update(object: string, id: string, data: Row): Promise<Row | null> { |
| 82 | + const prior = tableFor(object).get(id); |
| 83 | + if (!prior) return null; |
| 84 | + const next: Row = { ...prior, ...stored(data), id }; |
| 85 | + tableFor(object).set(id, next); |
| 86 | + return { ...next }; |
| 87 | + }, |
| 88 | + async updateMany(object: string, ast: DriverAst, data: Row): Promise<number> { |
| 89 | + const hits = Array.from(tableFor(object).values()).filter((r) => matches(r, ast?.where)); |
| 90 | + for (const r of hits) tableFor(object).set(String(r.id), { ...r, ...stored(data) }); |
| 91 | + return hits.length; |
| 92 | + }, |
| 93 | + async delete(object: string, id: string): Promise<boolean> { return tableFor(object).delete(id); }, |
| 94 | + async count(object: string, ast?: DriverAst): Promise<number> { return run(object, ast).length; }, |
| 95 | + registerExternalObject() {}, |
| 96 | + async syncSchema() {}, |
| 97 | + }; |
| 98 | + return { |
| 99 | + driver, |
| 100 | + stored: (object: string, id: string) => tableFor(object).get(id), |
| 101 | + }; |
| 102 | +} |
| 103 | + |
| 104 | +const ITEM = 'nk_write_item'; |
| 105 | +const PACKAGE_ID = 'com.example.nk_write'; |
| 106 | + |
| 107 | +/** `note` and `qty` are never written; `doubled` reads the unwritten `qty`. */ |
| 108 | +const ITEM_FIELDS = { |
| 109 | + title: { type: 'text' }, |
| 110 | + note: { type: 'text' }, |
| 111 | + qty: { type: 'number' }, |
| 112 | + doubled: { type: 'formula', expression: { dialect: 'cel', source: 'record.qty != null ? record.qty * 2 : -1' } }, |
| 113 | +}; |
| 114 | + |
| 115 | +async function boot() { |
| 116 | + const engine = new ObjectQL(); |
| 117 | + const local = makeSparseDriver('memory'); |
| 118 | + engine.registerDriver(local.driver as never, true); |
| 119 | + await engine.init(); |
| 120 | + engine.registry.registerObject({ name: ITEM, label: 'Item', fields: ITEM_FIELDS } as never, PACKAGE_ID); |
| 121 | + return { engine, local, protocol: new ObjectStackProtocolImplementation(engine as never) }; |
| 122 | +} |
| 123 | + |
| 124 | +const own = (row: unknown, key: string): boolean => |
| 125 | + row != null && typeof row === 'object' && Object.prototype.hasOwnProperty.call(row, key); |
| 126 | + |
| 127 | +type Booted = Awaited<ReturnType<typeof boot>>; |
| 128 | +type Answer = Row | null | undefined; |
| 129 | + |
| 130 | +/** One write door: performs the write and hands back the record body it answered. */ |
| 131 | +type WritePath = [string, (h: Booted, existingId: string) => Promise<Answer>]; |
| 132 | + |
| 133 | +const WRITE_PATHS: WritePath[] = [ |
| 134 | + ['engine.insert', async (h) => await h.engine.insert(ITEM, { title: 'a' }) as Row], |
| 135 | + ['engine.insert (batch)', async (h) => ((await h.engine.insert(ITEM, [{ title: 'b1' }, { title: 'b2' }])) as Row[])[1]], |
| 136 | + ['engine.insertMany (partial outcomes)', async (h) => ((await h.engine.insertMany(ITEM, [{ title: 'c' }])) as Array<{ record?: Row }>)[0]!.record], |
| 137 | + ['engine.update by id', async (h, id) => await h.engine.update(ITEM, { id, title: 'u' }) as Row], |
| 138 | + ['createData (POST /data/:object)', async (h) => ((await h.protocol.createData({ object: ITEM, data: { title: 'd' } })) as { record: Row }).record], |
| 139 | + ['updateData (PATCH /data/:object/:id)', async (h, id) => ((await h.protocol.updateData({ object: ITEM, id, data: { title: 'p' } })) as { record: Row }).record], |
| 140 | + ['createManyData', async (h) => ((await h.protocol.createManyData({ object: ITEM, records: [{ title: 'm' }] })) as { records: Row[] }).records[0]], |
| 141 | + ['updateManyData', async (h, id) => ((await h.protocol.updateManyData({ object: ITEM, records: [{ id, data: { title: 'n' } }] } as never)) as { results: Array<{ data: Row }> }).results[0]!.data], |
| 142 | + ['batch create', async (h) => ((await h.protocol.batchData({ object: ITEM, request: { operation: 'create', records: [{ data: { title: 'bc' } }] } as never })) as { results: Array<{ data: Row }> }).results[0]!.data], |
| 143 | + ['batch update', async (h, id) => ((await h.protocol.batchData({ object: ITEM, request: { operation: 'update', records: [{ id, data: { title: 'bu' } }] } as never })) as { results: Array<{ data: Row }> }).results[0]!.data], |
| 144 | + ['batch upsert, update arm', async (h, id) => ((await h.protocol.batchData({ object: ITEM, request: { operation: 'upsert', records: [{ id, data: { title: 'xu' } }] } as never })) as { results: Array<{ data: Row }> }).results[0]!.data], |
| 145 | + ['batch upsert, create arm', async (h) => ((await h.protocol.batchData({ object: ITEM, request: { operation: 'upsert', records: [{ id: 'nk_up_new', data: { title: 'xc' } }] } as never })) as { results: Array<{ data: Row }> }).results[0]!.data], |
| 146 | +]; |
| 147 | + |
| 148 | +describe('[#29538] a write answers the record the next read answers', () => { |
| 149 | + let h: Booted; |
| 150 | + let existingId: string; |
| 151 | + beforeEach(async () => { |
| 152 | + h = await boot(); |
| 153 | + existingId = String(((await h.engine.insert(ITEM, { title: 'seed' })) as Row).id); |
| 154 | + }); |
| 155 | + |
| 156 | + it('the fixture is real: the stored row carries no key for the unwritten columns', () => { |
| 157 | + const stored = h.local.stored(ITEM, existingId)!; |
| 158 | + expect(own(stored, 'note')).toBe(false); |
| 159 | + expect(own(stored, 'qty')).toBe(false); |
| 160 | + }); |
| 161 | + |
| 162 | + it.each(WRITE_PATHS)('%s: the write answer deep-equals the next findOne', async (_label, write) => { |
| 163 | + const answer = await write(h, existingId); |
| 164 | + expect(answer).toBeTruthy(); |
| 165 | + const next = await h.engine.findOne(ITEM, { where: { id: answer!.id } }); |
| 166 | + expect(answer).toStrictEqual(next); |
| 167 | + // The unwritten stored columns are present as `null`, not missing keys. |
| 168 | + expect(own(answer, 'note')).toBe(true); |
| 169 | + expect(answer!.note).toBeNull(); |
| 170 | + expect(own(answer, 'qty')).toBe(true); |
| 171 | + expect(answer!.qty).toBeNull(); |
| 172 | + }); |
| 173 | + |
| 174 | + it.each(WRITE_PATHS)('%s: FORMULA CONTROL — the formula over the unwritten column evaluates against null, as the read does', async (_label, write) => { |
| 175 | + const answer = await write(h, existingId); |
| 176 | + expect(answer!.doubled).toBe(-1); |
| 177 | + }); |
| 178 | + |
| 179 | + it('a stored value and a stored null are answered as stored', async () => { |
| 180 | + const answer = await h.engine.update(ITEM, { id: existingId, note: 'kept', qty: null }) as Row; |
| 181 | + expect(answer).toMatchObject({ note: 'kept', qty: null, doubled: -1 }); |
| 182 | + expect(answer).toStrictEqual(await h.engine.findOne(ITEM, { where: { id: existingId } })); |
| 183 | + }); |
| 184 | + |
| 185 | + it('the driver\'s stored row is never mutated by the answer', async () => { |
| 186 | + await h.engine.update(ITEM, { id: existingId, title: 'again' }); |
| 187 | + expect(own(h.local.stored(ITEM, existingId), 'note')).toBe(false); |
| 188 | + }); |
| 189 | + |
| 190 | + it('a predicate update still answers its affected-row count, not a record body', async () => { |
| 191 | + const count = await h.engine.update(ITEM, { title: 'many' }, { where: { title: 'seed' }, multi: true } as never); |
| 192 | + expect(count).toBe(1); |
| 193 | + }); |
| 194 | +}); |
0 commit comments