Skip to content

Commit 1cb3f6a

Browse files
committed
test(objectql, runtime, driver-mongodb): pin the write answer to the next read per path and driver; changeset (#29538)
Claude-Session: https://claude.ai/code/session_01ADHkmQjPiXgNoSaEpqeGvY Co-authored-by: Claude <noreply@anthropic.com>
1 parent e47a9f8 commit 1cb3f6a

4 files changed

Lines changed: 567 additions & 0 deletions

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql): a write answers every stored declared column the driver did not echo as `null`, so the insert and update answer is the record the next read returns, on every driver (#29538)
6+
7+
Clause-②: no — nothing a request may send is refused or newly admitted, and nothing a write stores changes; measured on base and head through the engine and the protocol doors on SQLite, driver-memory and driver-mongodb (fake `Db`), every write was accepted on both. An insert or by-id update answer gains a `null` key for a stored declared column the driver did not echo, and on driver-mongodb and driver-memory a `formula` over such a column in that answer now evaluates against that `null`, as the next read and driver-sql already did.
8+
Metadata-protocol: none
9+
10+
- **Before.** After #29408, `find` and `findOne` answer an unwritten declared column `null` on every driver, but the write answer still came straight from the driver. driver-sql echoed `null` (its table has the column); driver-mongodb and driver-memory echoed only the keys the write stored. So a create on mongo or memory answered `{ title: 'x' }` and the very next `GET` of the same row answered `{ title: 'x', note: null }`, and a formula reading `note` answered `null` (a fault) in the create response and its value on the `GET`.
11+
- **Now.** The engine answers the insert result (single, batch, and each `insertMany` outcome) and the by-id update readback on every stored declared column, `null` where the driver echoed no key, before the formulas and the `afterInsert` / `afterUpdate` hooks. Every door on those two verbs answers alike: `POST /data/:object`, `PATCH /data/:object/:id`, `createManyData`, `updateManyData`, and `batchData` create / update / both upsert arms.
12+
- **Unchanged.** What a write stores. A predicate update still answers its affected-row count. A column field-level security refuses the writer stays absent (the security mask still deletes it), and so do a name outside the declared set, an injected column a federated (`external`) object has no storage for, and a `created_at` / `updated_at` a federated object neither declares nor has injected — the read's own exclusions.
13+
- **Who sees it.** A client of an object served by driver-mongodb or driver-memory that diffs a create or update response against its own state, or renders it: a field the save never mentioned now arrives in that response as `null`, as it does on the next read, instead of appearing only on the next read. In-process readers of the write result see the same: an `afterInsert` / `afterUpdate` hook, a `data.record.created` / `data.record.updated` event payload and the webhooks that deliver it. A reader that told a missing key from `null` (`'x' in row`, `has(record.x)`) now reads what driver-sql already answered; test emptiness with `record.x != null`. A `formula` over an unwritten field in a write response on those two drivers changes value: it used to answer `null` with a fault, and now answers what the next read answers (`record.qty != null ? record.qty * 2 : -1` was `null`, now `-1`).
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#29538] driver-mongodb through the engine: a write answers the record the
5+
* next read answers — a declared column the write never touched is `null` in
6+
* the insert and update answer, as on the following `findOne` (#29408).
7+
*
8+
* This driver stores no key for a field given no value (`withoutUndefinedOwnKeys`
9+
* at the insert doors), its `create` / `bulkCreate` echo the document they
10+
* inserted, and its `update` re-reads the document. So the row each write
11+
* hands the engine is sparse. Measured on `origin/main` before the fix with
12+
* this same harness: every write answer below carried no `note` / `qty` key
13+
* and answered the formula `doubled` as `null` (a fault on the missing
14+
* `qty`), while the next `findOne` answered `note: null`, `qty: null` and
15+
* `doubled: -1`.
16+
*
17+
* Runs without a server, on the fake `Db` of
18+
* `mongodb-declared-column-null-on-read.test.ts`, with the write calls the
19+
* engine's insert and by-id update doors reach. The fake keeps each document
20+
* as inserted and answers a projection as a real mongod does — the named keys
21+
* the document HAS. The real-server suites are gated on `mongodb-memory-server`
22+
* (#5517).
23+
*/
24+
25+
import { describe, it, expect, beforeEach } from 'vitest';
26+
import { ObjectQL } from '@objectstack/objectql';
27+
import { MongoDBDriver } from './mongodb-driver.js';
28+
29+
type Doc = Record<string, unknown>;
30+
31+
/** A fake `Db`: one collection, stored documents kept as inserted. */
32+
function fakeDb() {
33+
const docs: Doc[] = [];
34+
const project = (doc: Doc, projection: Record<string, number> | undefined): Doc => {
35+
const keep = Object.keys(projection ?? {}).filter((k) => projection![k] === 1);
36+
const out: Doc = {};
37+
for (const [k, v] of Object.entries(doc)) {
38+
if (k === '_id' && projection?._id === 0) continue;
39+
if (keep.length > 0 && !keep.includes(k)) continue;
40+
out[k] = v;
41+
}
42+
return out;
43+
};
44+
// Equality on plain keys only — the writes and reads below address a row
45+
// by `id` alone. A combinator or any other operator is REFUSED, never read
46+
// as a field name.
47+
const matches = (doc: Doc, filter: Doc | undefined): boolean =>
48+
Object.entries(filter ?? {}).every(([k, v]) => {
49+
if (k.startsWith('$')) throw new Error(`fake Db: filter operator ${k} is not implemented`);
50+
if (v !== null && typeof v === 'object') {
51+
const ops = Object.keys(v as Doc);
52+
if (ops.length !== 1 || ops[0] !== '$eq') throw new Error(`fake Db: operator ${ops.join(',')} is not implemented`);
53+
return doc[k] === (v as Doc).$eq;
54+
}
55+
return doc[k] === v;
56+
});
57+
const collection = {
58+
insertOne: async (doc: Doc) => { docs.push({ _id: `oid_${docs.length}`, ...doc }); return {}; },
59+
insertMany: async (many: Doc[]) => { for (const doc of many) docs.push({ _id: `oid_${docs.length}`, ...doc }); return {}; },
60+
updateOne: async (filter: Doc, update: { $set?: Doc }) => {
61+
const updateOps = Object.keys(update);
62+
if (updateOps.length !== 1 || updateOps[0] !== '$set') throw new Error(`fake Db: update ${updateOps.join(',')} is not implemented`);
63+
const d = docs.find((x) => matches(x, filter));
64+
if (d) Object.assign(d, update.$set);
65+
return { matchedCount: d ? 1 : 0 };
66+
},
67+
findOne: async (filter: Doc, options: { projection?: Record<string, number> }) => {
68+
const d = docs.find((x) => matches(x, filter));
69+
return d ? project(d, options?.projection) : null;
70+
},
71+
find: (filter: Doc, options: { projection?: Record<string, number> }) => ({
72+
toArray: async () => docs.filter((x) => matches(x, filter)).map((d) => project(d, options?.projection)),
73+
}),
74+
};
75+
return { db: { collection: () => collection }, docs };
76+
}
77+
78+
const OBJECT = 'nk_mongo_write_item';
79+
80+
const own = (row: unknown, key: string): boolean =>
81+
row != null && typeof row === 'object' && Object.prototype.hasOwnProperty.call(row, key);
82+
83+
describe('[#29538] driver-mongodb: a write answers the record the next read answers', () => {
84+
let engine: ObjectQL;
85+
let docs: Doc[];
86+
87+
beforeEach(async () => {
88+
const driver = new MongoDBDriver({ url: 'mongodb://127.0.0.1:1/unused' });
89+
const fake = fakeDb();
90+
docs = fake.docs;
91+
(driver as any).db = fake.db;
92+
(driver as any).connect = async () => {};
93+
(driver as any).disconnect = async () => {};
94+
engine = new ObjectQL();
95+
engine.registerDriver(driver as never, true);
96+
await engine.init();
97+
engine.registry.registerObject({
98+
name: OBJECT,
99+
label: 'Item',
100+
fields: {
101+
name: { type: 'text' },
102+
note: { type: 'text' },
103+
qty: { type: 'number' },
104+
doubled: { type: 'formula', expression: { dialect: 'cel', source: 'record.qty != null ? record.qty * 2 : -1' } },
105+
},
106+
} as never);
107+
});
108+
109+
const expectAnswerIsNextRead = async (answer: Doc) => {
110+
expect(answer).toStrictEqual(await engine.findOne(OBJECT, { where: { id: answer.id } }));
111+
expect(own(answer, 'note')).toBe(true);
112+
expect(answer.note).toBeNull();
113+
expect(own(answer, 'qty')).toBe(true);
114+
expect(answer.qty).toBeNull();
115+
// FORMULA CONTROL: evaluated against the `null`, as the read evaluates it.
116+
expect(answer.doubled).toBe(-1);
117+
};
118+
119+
it('insert: the answer deep-equals the next findOne', async () => {
120+
const answer = await engine.insert(OBJECT, { name: 'Ada' }) as Doc;
121+
expect(own(docs[0], 'note')).toBe(false);
122+
await expectAnswerIsNextRead(answer);
123+
});
124+
125+
it('batch insert (bulkCreate): every answered row deep-equals its next findOne', async () => {
126+
const answers = await engine.insert(OBJECT, [{ name: 'Ada' }, { name: 'Bo' }]) as Doc[];
127+
expect(answers).toHaveLength(2);
128+
for (const answer of answers) await expectAnswerIsNextRead(answer);
129+
});
130+
131+
it('update by id: the answer deep-equals the next findOne', async () => {
132+
const created = await engine.insert(OBJECT, { name: 'Ada' }) as Doc;
133+
const answer = await engine.update(OBJECT, { id: created.id, name: 'Ada L.' }) as Doc;
134+
expect(answer.name).toBe('Ada L.');
135+
await expectAnswerIsNextRead(answer);
136+
// The stored document still carries no key for the column: only the
137+
// answer is shaped, never what the write stores.
138+
expect(own(docs[0], 'note')).toBe(false);
139+
});
140+
});
Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
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

Comments
 (0)