diff --git a/.changeset/34672-summary-readonly-on-update.md b/.changeset/34672-summary-readonly-on-update.md new file mode 100644 index 00000000000..c33d0f79e0b --- /dev/null +++ b/.changeset/34672-summary-readonly-on-update.md @@ -0,0 +1,16 @@ +--- +'@objectstack/objectql': patch +--- + +fix(objectql)!: a roll-up `summary` field is read-only on update whether or not it declares `readonly: true` + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING** for a caller that updates a `summary` field. A `PATCH /api/v1/data/:object/:id`, an import with `writeMode: 'update'`, a predicate (`multi: true`) update and the `update`-mode preview (`validate`) now drop a value sent for a roll-up summary field, as they already did for one declared `readonly: true`. The rest of the write is stored, and `droppedFields` / `onFieldsDropped` name the field with reason `readonly`. Under `strictReadonlyWrites` the whole update is refused with `ERR_READONLY_FIELD_REJECTED` and nothing is written. Before this change the typed value was stored and read downstream (defaults, rules, reports) until the next child write recomputed the roll-up. An import with `writeMode: 'upsert'` drops the value on the rows it updates and keeps it on the rows it creates. Undoing a non-historical import that was committed before this release restores the rows' `before` snapshot through an ordinary update, so a summary value that import overwrote is not put back; it stays until the next child write recomputes it. + +To fix a refused or dropped write: leave the summary field out of the update payload. Server code that must set the column (a migration, a repair job) passes `{ context: { isSystem: true } }`, which the roll-up recompute itself uses and which this lock exempts, as it exempts every read-only column. + +Not changed: a create keeps a value sent for a summary field as its starting value, so seed data and a historical import may still carry a pre-computed total; the next child write replaces it with the computed one. A historical import (`treatAsHistorical: true`, which writes with `preserveAudit`) keeps a summary value it sends on update too, as it keeps any other read-only value it sends, and so does the undo of such an import. The roll-up recompute, the backfill and the enable refresh write as before. A summary field that already declares `readonly: true` answers exactly as before. diff --git a/content/docs/data-modeling/fields.mdx b/content/docs/data-modeling/fields.mdx index a583b8ad41a..6a01d5f0505 100644 --- a/content/docs/data-modeling/fields.mdx +++ b/content/docs/data-modeling/fields.mdx @@ -396,6 +396,23 @@ are inserted, updated, or deleted. `relationshipField` is optional when the chil has only one `lookup`/`master_detail` field pointing back to the parent; set it when multiple relationships target the same parent object. +On update a summary field is read-only whether or not it declares `readonly: true`. +A value that a `PATCH`, an import with `writeMode: 'update'` or a bulk update +sends for it is dropped, the rest of the write is stored, and the response's +`droppedFields` names the field with reason `readonly`. Under +`strictReadonlyWrites` the whole update is refused. Server code that runs with +`isSystem: true` can still write the column, as it can any read-only column. +On create, a value you send is kept as the field's starting value (seed data or +a historical import may carry a pre-computed total); the next child write +replaces it with the computed one. +An import with `writeMode: 'upsert'` therefore drops the value on the rows it +updates and keeps it on the rows it creates. A historical import +(`treatAsHistorical: true`, which writes with `preserveAudit`) keeps a summary +value on update as well, as it keeps any other read-only value it sends. Undoing +an ordinary import restores the rows through an ordinary update, so a summary +value that an import committed before this rule overwrote is not put back by +the undo; it stays until the next child write recomputes it. + Because the roll-up is engine-derived state rather than a user write, the recompute runs under a system context: a user who may create a child does not also need edit access on the parent, and the aggregate is computed over the diff --git a/packages/objectql/src/engine-blank-typed-value-door.test.ts b/packages/objectql/src/engine-blank-typed-value-door.test.ts index b6ec649644d..c8b4474bba7 100644 --- a/packages/objectql/src/engine-blank-typed-value-door.test.ts +++ b/packages/objectql/src/engine-blank-typed-value-door.test.ts @@ -178,14 +178,22 @@ describe('engine write doors: a blank on a non-string-typed column reaches the d }); it('update by id and update by predicate', async () => { + // [#34672] A `summary` column is read-only on update: a caller's value + // for it, a blank included, is dropped before the driver, so the update + // sends no `f_summary` at all. Every other typed column still lands null. + const updateTyped = TYPED.filter((t) => t !== 'summary'); + const expectUpdateTypedNull = (data: Record) => { + for (const t of updateTyped) expect(data[f(t)], t).toBeNull(); + expect(data).not.toHaveProperty(f('summary')); + }; await engine.insert('blank_door', { id: 'u1', ...VALID }); await engine.update('blank_door', { id: 'u1', ...blankTyped(''), ...STR_BLANK }); const byId = last('update'); - expectTypedNull(byId); + expectUpdateTypedNull(byId); expect([byId.c_text, byId.c_lookup, byId.c_select]).toEqual(['', null, null]); await engine.update('blank_door', blankTyped(''), { where: { id: { $in: ['u1'] } }, multi: true } as any); - expectTypedNull(last('updateMany')); + expectUpdateTypedNull(last('updateMany')); }); it('a valid value on every typed column — falsy ones included — is unchanged', async () => { diff --git a/packages/objectql/src/engine-summary-update-lock.test.ts b/packages/objectql/src/engine-summary-update-lock.test.ts new file mode 100644 index 00000000000..94a75104c25 --- /dev/null +++ b/packages/objectql/src/engine-summary-update-lock.test.ts @@ -0,0 +1,270 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34672] A roll-up `summary` field is read-only on UPDATE whether or not the + * author declared `readonly: true`. + * + * The engine computes a roll-up from its child rows and writes it through + * `update()` under an `isSystem` context. Before this card the update's static + * `readonly` strip read only the declared flag, so a person's `PATCH`, an + * import with `writeMode: 'update'` or a predicate update stored the typed + * value, and it was read downstream until the next child write recomputed it. + * Now the update's schema view (`updateStaticReadonlySubject`) reads every + * `summary` field as `readonly: true`. So the write is taken and reported as + * `readonly`, and refused under `strictReadonlyWrites`, exactly as for a + * roll-up the author did declare read-only (the control below). + * + * Kept as before, each pinned here: + * - the roll-up recompute's own write (`isSystem`), and any other `isSystem` + * write of the column; + * - a caller's initial value on INSERT (seed data, a historical import), the + * boundary the `summary` note on `RUNTIME_OWNED_FIELD_TYPES` draws. + * + * The import door, end to end over HTTP and SQLite: + * `packages/rest/src/import-summary-update-lock-34672.test.ts`. + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import type { DroppedFieldsEvent } from '@objectstack/spec/data'; +import { ObjectQL } from './engine.js'; +import { summaryFieldsLockedOnUpdate } from './engine-top-level.js'; +import { READONLY_FIELD_REJECTED_CODE } from './readonly-strict-errors.js'; + +function makeDriver() { + const stores = new Map>(); + const storeFor = (o: string) => { + let s = stores.get(o); + if (!s) { s = new Map(); stores.set(o, s); } + return s; + }; + // Flat equality, `$and` and a field's `$in`: the shapes the roll-up + // aggregate and the predicate update below send. Any other operator throws. + const matches = (row: any, where: any): boolean => { + if (!where || typeof where !== 'object') return true; + return Object.entries(where).every(([k, v]) => { + if (k === '$and') return (v as any[]).every((sub) => matches(row, sub)); + if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`); + if (v && typeof v === 'object' && !Array.isArray(v)) { + const ops = Object.keys(v); + if (ops.length === 1 && ops[0] === '$in' && Array.isArray((v as any).$in)) return (v as any).$in.includes(row?.[k]); + throw new Error(`fake driver: unsupported condition on ${k}: ${JSON.stringify(v)}`); + } + return row?.[k] === v; + }); + }; + let n = 0; + const driver: any = { + name: 'memory', version: '0.0.0', supports: {}, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, + async find(object: string, ast: any) { + const rows = Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where)); + const page = typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; + return page.map((r) => ({ ...r })); + }, + async findOne(object: string, ast: any) { + for (const r of storeFor(object).values()) if (matches(r, ast?.where)) return { ...r }; + return null; + }, + async create(object: string, data: Record) { + n += 1; + const id = (data.id as string) ?? `r_${n}`; + const row = { ...data, id }; + storeFor(object).set(id, row); + return { ...row }; + }, + async update(object: string, id: string, data: Record) { + const s = storeFor(object); + const row = { ...s.get(id), ...data, id }; + s.set(id, row); + return { ...row }; + }, + async updateMany(object: string, ast: any, data: Record) { + const s = storeFor(object); + let count = 0; + for (const row of [...s.values()]) { + if (!matches(row, ast?.where)) continue; + s.set(row.id, { ...row, ...data, id: row.id }); + count += 1; + } + return count; + }, + async delete(object: string, id: string) { return storeFor(object).delete(id); }, + async count() { return 0; }, + async bulkCreate(object: string, rows: Record[]) { + return Promise.all(rows.map((r) => this.create(object, r, undefined))); + }, + async bulkUpdate() { return []; }, async bulkDelete() {}, + async beginTransaction() { return { __trx: true, commit: async () => {}, rollback: async () => {} }; }, + async commit() {}, async rollback() {}, + }; + return { driver, storeFor }; +} + +const silentLogger: any = (() => { + const l: any = { debug() {}, info() {}, error() {}, trace() {}, fatal() {}, warn() {}, child() { return l; } }; + return l; +})(); + +/** A signed-in person: not the system principal. */ +const PERSON = { userId: 'u_rep' } as any; + +async function rejection(p: Promise): Promise { + try { + await p; + } catch (err) { + return err; + } + throw new Error('expected the write to be refused, but it resolved'); +} + +const ACCOUNT = { + name: 'acct', + fields: { + name: { type: 'text' }, + note: { type: 'text' }, + // The card's shape: a roll-up with no `readonly`. + order_total: { type: 'summary', summaryOperations: { object: 'ord', field: 'amount', function: 'sum' } }, + // The control: the same roll-up, declared read-only by its author. + order_total_ro: { type: 'summary', readonly: true, summaryOperations: { object: 'ord', field: 'amount', function: 'sum' } }, + }, +}; + +const ORDER = { + name: 'ord', + fields: { + amount: { type: 'number' }, + acct: { type: 'master_detail', reference: 'acct' }, + }, +}; + +const ROLL_UP: DroppedFieldsEvent = { object: 'acct', fields: ['order_total'], reason: 'readonly' }; + +describe('[#34672] a roll-up summary without readonly: true is read-only on update', () => { + let engine: ObjectQL; + let storeFor: ReturnType['storeFor']; + + beforeEach(async () => { + engine = new ObjectQL({ logger: silentLogger }); + const d = makeDriver(); + storeFor = d.storeFor; + engine.registerDriver(d.driver, true); + await engine.init(); + engine.registry.registerObject(ACCOUNT as any); + engine.registry.registerObject(ORDER as any); + const a = await engine.insert('acct', { id: 'a1', name: 'A' }, { context: PERSON } as any); + const b = await engine.insert('acct', { id: 'a2', name: 'B' }, { context: PERSON } as any); + await engine.insert('ord', { acct: a.id, amount: 10 }, { context: PERSON } as any); + await engine.insert('ord', { acct: a.id, amount: 32 }, { context: PERSON } as any); + await engine.insert('ord', { acct: b.id, amount: 5 }, { context: PERSON } as any); + }); + + const acct = (id: string) => storeFor('acct').get(id); + + it('the seeded roll-ups are the engine\'s (the baseline every case reads)', () => { + expect(acct('a1')).toMatchObject({ order_total: 42, order_total_ro: 42 }); + expect(acct('a2')).toMatchObject({ order_total: 5, order_total_ro: 5 }); + }); + + it('a by-id update (REST PATCH): the roll-up value is dropped and reported as readonly, the rest is written', async () => { + const events: DroppedFieldsEvent[] = []; + await engine.update( + 'acct', + { id: 'a1', note: 'typed', order_total: 90 }, + { context: PERSON, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) } as any, + ); + expect(events).toEqual([ROLL_UP]); + expect(acct('a1')).toMatchObject({ note: 'typed', order_total: 42 }); + }); + + it('a predicate update (multi): the roll-up value is dropped from every matched row and reported once', async () => { + const events: DroppedFieldsEvent[] = []; + await engine.update( + 'acct', + { note: 'bulk', order_total: 2 }, + { where: { id: { $in: ['a1', 'a2'] } }, multi: true, context: PERSON, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) } as any, + ); + expect(events).toEqual([ROLL_UP]); + expect(acct('a1')).toMatchObject({ note: 'bulk', order_total: 42 }); + expect(acct('a2')).toMatchObject({ note: 'bulk', order_total: 5 }); + }); + + it('under strictReadonlyWrites the update is refused and writes nothing, on both branches', async () => { + const byId = await rejection(engine.update( + 'acct', { id: 'a1', note: 'typed', order_total: 90 }, + { context: PERSON, strictReadonlyWrites: true } as any, + )); + expect(byId.code).toBe(READONLY_FIELD_REJECTED_CODE); + expect(byId.fields).toEqual(['order_total']); + expect(byId.drops).toEqual([ROLL_UP]); + expect(byId.operation).toBe('update'); + + const multi = await rejection(engine.update( + 'acct', { note: 'bulk', order_total: 2 }, + { where: { id: { $in: ['a1', 'a2'] } }, multi: true, context: PERSON, strictReadonlyWrites: true } as any, + )); + expect(multi.code).toBe(READONLY_FIELD_REJECTED_CODE); + expect(multi.fields).toEqual(['order_total']); + + expect(acct('a1')).toMatchObject({ order_total: 42 }); + expect(acct('a2')).toMatchObject({ order_total: 5 }); + expect([acct('a1').note, acct('a2').note]).toEqual([undefined, undefined]); + }); + + it('the update-mode preview (validate) reports the same drop the write makes', async () => { + const events: DroppedFieldsEvent[] = []; + const preview = await engine.validate( + 'acct', { id: 'a1', note: 'typed', order_total: 90 }, + { mode: 'update', context: PERSON, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) }, + ); + expect(events).toEqual([ROLL_UP]); + expect(preview.results[0]).toMatchObject({ valid: true, droppedFields: [ROLL_UP] }); + }); + + it('the roll-up still recomputes after a refused write: the next child write lands the engine\'s value', async () => { + await engine.update('acct', { id: 'a1', order_total: 90 }, { context: PERSON } as any); + await engine.insert('ord', { acct: 'a1', amount: 8 }, { context: PERSON } as any); + expect(acct('a1')).toMatchObject({ order_total: 50, order_total_ro: 50 }); + }); + + it('an isSystem write of the column is kept, as for a declared readonly column (the recompute\'s exemption)', async () => { + const events: DroppedFieldsEvent[] = []; + await engine.update( + 'acct', { id: 'a1', order_total: 7 }, + { context: { isSystem: true }, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) } as any, + ); + expect(events).toEqual([]); + expect(acct('a1')).toMatchObject({ order_total: 7 }); + }); + + it('CONTROL: a roll-up declared readonly: true answers the same, and one payload naming both reports both once', async () => { + const events: DroppedFieldsEvent[] = []; + await engine.update( + 'acct', { id: 'a1', order_total: 1, order_total_ro: 1 }, + { context: PERSON, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) } as any, + ); + expect(events).toEqual([{ object: 'acct', fields: ['order_total', 'order_total_ro'], reason: 'readonly' }]); + expect(acct('a1')).toMatchObject({ order_total: 42, order_total_ro: 42 }); + }); + + it('INSERT is not narrowed: a caller\'s initial value is kept (seed data, a historical import)', async () => { + const events: DroppedFieldsEvent[] = []; + await engine.insert( + 'acct', { id: 'a3', name: 'C', order_total: 7 }, + { context: PERSON, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) } as any, + ); + expect(events).toEqual([]); + expect(acct('a3')).toMatchObject({ order_total: 7 }); + }); +}); + +describe('[#34672] summaryFieldsLockedOnUpdate', () => { + it('names each summary field not declared readonly, and nothing else', () => { + expect(summaryFieldsLockedOnUpdate(ACCOUNT)).toEqual(['order_total']); + expect(summaryFieldsLockedOnUpdate(ORDER)).toEqual([]); + }); + + it('answers empty for a schema with no field map', () => { + expect(summaryFieldsLockedOnUpdate(undefined)).toEqual([]); + expect(summaryFieldsLockedOnUpdate({ fields: [] })).toEqual([]); + }); +}); diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index dac2d18b839..88c139c57a8 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -2240,7 +2240,11 @@ export function undeclaredWriteFieldErrors( * ⛔ Keyed on `type === 'formula'` literally — the test the read path's * projection and `driver-sql`'s `fieldHasColumn` use. `summary` is NOT here: a * roll-up HAS a column, and a caller-supplied value is persisted (measured on - * #20805, SQLite and memory) — a separate question, not this door's. + * #20805, SQLite and memory) — a separate question, not this door's. [#34672] + * Its answer is the update's static-`readonly` strip + * ({@link summaryFieldsLockedOnUpdate}), which exempts the `isSystem` write + * the roll-up recompute makes; this door, which runs in every context, would + * take that write too. * * Pure: the caller's objects are never mutated. A row keeps its reference when * nothing was taken, else it is a shallow copy without the keys. @@ -2455,15 +2459,58 @@ export function insertStaticReadonlySubject( * reads the wall's flag once and hands that one value to all of them, so the * hook view and the stored row cannot disagree about the column. [#25062] The * `update`-mode preview's strip reads it too. + * + * [#34672] ...and with every roll-up `summary` field read as `readonly: true` + * ({@link summaryFieldsLockedOnUpdate}): the engine owns that value on + * update, so a person's or an import's write to it is taken and reported as + * `readonly`, exactly as if the author had declared the flag. The roll-up's + * own write is `isSystem` and skips these passes. Because the lock lives in + * this one view, every pass named above takes the same keys. */ export function updateStaticReadonlySubject(schema: unknown, wallJudgesOrganization: boolean): unknown { - if (!staticReadonlySparesOrganization(schema, wallJudgesOrganization)) return schema; + const sparesOrganization = staticReadonlySparesOrganization(schema, wallJudgesOrganization); + const rollUps = summaryFieldsLockedOnUpdate(schema); + if (!sparesOrganization && rollUps.length === 0) return schema; const { name, fields } = schema as { name?: string; fields: Record }; const kept = { ...fields }; - delete kept[SystemFieldName.ORGANIZATION_ID]; + if (sparesOrganization) delete kept[SystemFieldName.ORGANIZATION_ID]; + for (const field of rollUps) kept[field] = { ...(kept[field] as Record), readonly: true }; return { name, fields: kept }; } +/** + * [#34672] The roll-up `summary` fields an UPDATE judges read-only although + * the author did not declare `readonly: true`. The engine computes a roll-up + * from its child rows and writes it through `update()` under an `isSystem` + * context (`recomputeSummaries`, the backfill, the enable refresh), which the + * static strip exempts. So the only writes this lock takes are a caller's: + * a REST `PATCH`, an import with `writeMode: 'update'`, a predicate update. + * Before it, such a write was stored and read downstream until the next + * child write recomputed the roll-up. + * + * ⛔ UPDATE only. An insert keeps a caller's initial value: seed data and a + * historical import may carry a pre-computed total, and + * `initializeSummaryFields` seeds only the roll-ups the caller left out. See + * the `summary` note on `RUNTIME_OWNED_FIELD_TYPES` in + * `validation/rule-validator.ts`, which keeps the type out of the + * insert-side runtime-owned strip for that reason. + * + * Keyed on `type === 'summary'` literally, like the roll-up readers + * (`getSummaryDescriptors`, `summary-enable-refresh.ts`). A field already + * declared `readonly: true` is left as it is. + */ +export function summaryFieldsLockedOnUpdate(schema: unknown): string[] { + const fields = (schema as { fields?: unknown } | null | undefined)?.fields; + if (!fields || typeof fields !== 'object' || Array.isArray(fields)) return []; + const locked: string[] = []; + for (const [name, def] of Object.entries(fields as Record)) { + if (!def || typeof def !== 'object') continue; + const d = def as { type?: unknown; readonly?: unknown }; + if (d.type === 'summary' && d.readonly !== true) locked.push(name); + } + return locked; +} + /** * [#22306] The insert side of the #16344 invariant — a hook is never handed a * value that will not be stored. Takes out of ONE caller row every value the diff --git a/packages/rest/src/import-summary-update-lock-34672.test.ts b/packages/rest/src/import-summary-update-lock-34672.test.ts new file mode 100644 index 00000000000..5f247695c07 --- /dev/null +++ b/packages/rest/src/import-summary-update-lock-34672.test.ts @@ -0,0 +1,157 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34672] A roll-up `summary` field without `readonly: true`, through the + * public doors: `PATCH /api/v1/data/:object/:id` and + * `POST /api/v1/data/:object/import` with `writeMode: 'update'` (dry run and + * commit), over a REAL {@link ObjectQL} + {@link ObjectStackProtocolImplementation} + * + SQLite `:memory:`, as a signed-in person. + * + * Measured on `main` before this card: both doors answered `200` / `ok`, said + * nothing about the column, and stored the typed value (`90`, `2`) while the + * child rows summed to `42`. Now the engine reads every `summary` field as + * read-only on update, so both doors report the column as `readonly`, as they + * do for the roll-up the author declared read-only (the control), and the + * stored value stays the engine's. + * + * The engine's own pins (predicate update, `strictReadonlyWrites`, the + * recompute, `isSystem`, the insert boundary): + * `packages/objectql/src/engine-summary-update-lock.test.ts`. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { SysImportJob } from '@objectstack/platform-objects/audit'; +import { RestServer } from './rest-server'; +import { installDefaultOrganization } from './default-organization.testkit.js'; + +const PARENT = 'acct_rollup_34672'; +const CHILD = 'ord_rollup_34672'; + +const ACCOUNT = { + name: PARENT, label: 'Account 34672', systemFields: false, + fields: { + id: { name: 'id', type: 'text' as const, primaryKey: true }, + name: { name: 'name', type: 'text' as const }, + order_total: { + name: 'order_total', type: 'summary' as const, + summaryOperations: { object: CHILD, field: 'amount', function: 'sum' as const }, + }, + order_total_ro: { + name: 'order_total_ro', type: 'summary' as const, readonly: true, + summaryOperations: { object: CHILD, field: 'amount', function: 'sum' as const }, + }, + }, +}; + +const ORDER = { + name: CHILD, label: 'Order 34672', systemFields: false, + fields: { + id: { name: 'id', type: 'text' as const, primaryKey: true }, + amount: { name: 'amount', type: 'number' as const }, + acct: { name: 'acct', type: 'master_detail' as const, reference: PARENT }, + }, +}; + +const ROLL_UP = { object: PARENT, fields: ['order_total'], reason: 'readonly' }; +const ROLL_UP_RO = { object: PARENT, fields: ['order_total_ro'], reason: 'readonly' }; + +function createMockServer() { + const noop = () => {}; + return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; +} + +function makeRes() { + const res: any = { + write: () => true, end: () => {}, + header: () => res, + status: (code: number) => { res._status = code; return res; }, + json: (body: any) => { res._json = body; return res; }, + }; + return res; +} + +const liveEngines: ObjectQL[] = []; +afterEach(async () => { + while (liveEngines.length) { + try { await liveEngines.pop()?.destroy(); } catch { /* noop */ } + } +}); + +async function boot() { + const engine = new ObjectQL(); + liveEngines.push(engine); + engine.registerDriver(new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), true); + await engine.init(); + engine.registry.registerObject(ACCOUNT as any); + engine.registry.registerObject(ORDER as any); + engine.registry.registerObject(SysImportJob as any); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + + const protocol = new ObjectStackProtocolImplementation(engine as any); + const rest = new RestServer(createMockServer() as any, protocol as any, { api: { requireAuth: false } } as any); + (rest as any).resolveExecCtx = async () => ({ userId: 'test-user' }); + rest.registerRoutes(); + const call = async (method: string, path: string, body: unknown, params: Record): Promise<{ status: number; body: any }> => { + const route = rest.getRoutes().find((r: any) => r.method === method && r.path === path); + expect(route, `${method} ${path}`).toBeDefined(); + const res = makeRes(); + await route!.handler({ params, body, query: {}, headers: {} } as any, res); + return { status: res._status ?? 200, body: res._json }; + }; + + // The account and its two orders, written through the create door as the + // same person: the roll-ups are the engine's, 10 + 32. + for (const [object, row] of [ + [PARENT, { id: 'a1', name: 'A' }], + [CHILD, { id: 'o1', acct: 'a1', amount: 10 }], + [CHILD, { id: 'o2', acct: 'a1', amount: 32 }], + ] as const) { + const created = await call('POST', '/api/v1/data/:object', row, { object }); + expect(created.status, JSON.stringify(created.body)).toBe(201); + } + const stored = async () => engine.findOne(PARENT, { where: { id: 'a1' } }); + expect(await stored()).toMatchObject({ order_total: 42, order_total_ro: 42 }); + + const importUpdate = (rows: Array>, dryRun: boolean) => + call('POST', '/api/v1/data/:object/import', { + format: 'json', rows, dryRun, writeMode: 'update', matchFields: ['id'], + }, { object: PARENT }); + return { call, importUpdate, stored }; +} + +describe('[#34672] a roll-up summary without readonly: true, through the public doors', () => { + it('PATCH: the roll-up value is dropped and reported as readonly; the rest of the patch is written', async () => { + const b = await boot(); + const patch = await b.call('PATCH', '/api/v1/data/:object/:id', { name: 'A2', order_total: 90 }, { object: PARENT, id: 'a1' }); + expect(patch.status, JSON.stringify(patch.body)).toBe(200); + expect(patch.body.droppedFields).toEqual([ROLL_UP]); + expect(await b.stored()).toMatchObject({ name: 'A2', order_total: 42 }); + }); + + it('import writeMode update: the dry run and the commit both report the drop, and the commit stores the engine\'s value', async () => { + const b = await boot(); + const dry = await b.importUpdate([{ id: 'a1', name: 'A3', order_total: 2 }], true); + expect(dry.body, JSON.stringify(dry.body)).toMatchObject({ ok: 1, errors: 0, updated: 1 }); + expect(dry.body.results[0]).toEqual({ row: 1, ok: true, action: 'updated', id: 'a1', droppedFields: [ROLL_UP] }); + + const commit = await b.importUpdate([{ id: 'a1', name: 'A3', order_total: 2 }], false); + expect(commit.body, JSON.stringify(commit.body)).toMatchObject({ ok: 1, errors: 0, updated: 1 }); + expect(commit.body.results[0]).toEqual({ row: 1, ok: true, action: 'updated', id: 'a1', droppedFields: [ROLL_UP] }); + expect(await b.stored()).toMatchObject({ name: 'A3', order_total: 42 }); + }); + + it('CONTROL: the roll-up the author declared readonly: true answers the same on both doors', async () => { + const b = await boot(); + const patch = await b.call('PATCH', '/api/v1/data/:object/:id', { order_total_ro: 90 }, { object: PARENT, id: 'a1' }); + expect(patch.status, JSON.stringify(patch.body)).toBe(200); + expect(patch.body.droppedFields).toEqual([ROLL_UP_RO]); + + const commit = await b.importUpdate([{ id: 'a1', order_total_ro: 2 }], false); + expect(commit.body.results[0]).toEqual({ row: 1, ok: true, action: 'updated', id: 'a1', droppedFields: [ROLL_UP_RO] }); + expect(await b.stored()).toMatchObject({ order_total: 42, order_total_ro: 42 }); + }); +}); diff --git a/packages/rest/src/rest-data-blank-typed-value.test.ts b/packages/rest/src/rest-data-blank-typed-value.test.ts index 0e53ef945a3..4c38ea2d3e7 100644 --- a/packages/rest/src/rest-data-blank-typed-value.test.ts +++ b/packages/rest/src/rest-data-blank-typed-value.test.ts @@ -147,6 +147,19 @@ function expectTypedNull(row: Record | undefined | null, where: for (const t of TYPED) expect(row![f(t)], `${where} · ${t}`).toBeNull(); } +/** + * [#34672] The UPDATE doors' answer: a `summary` column is read-only on update, + * so a caller's blank for it is dropped and the stored roll-up (the seeded + * `f_summary: 7`) stays; every other typed column stores null. + */ +function expectUpdatedTypedNull(row: Record | undefined | null, where: string) { + expect(row, where).toBeTruthy(); + for (const t of TYPED) { + if (t === 'summary') expect(row![f(t)], `${where} · ${t} (read-only on update)`).toBe(VALID.f_summary); + else expect(row![f(t)], `${where} · ${t}`).toBeNull(); + } +} + describe('REST write doors on SQLite: a cleared typed column stores null (#20308)', () => { let ctx: Awaited>; beforeEach(async () => { ctx = await boot(); }); @@ -169,7 +182,7 @@ describe('REST write doors on SQLite: a cleared typed column stores null (#20308 await seed('u1'); const res = await ctx.call('PATCH', '/api/v1/data/:object/:id', { object: 'blank_rest', id: 'u1' }, blankTyped()); expect(res.status).toBe(200); - expectTypedNull(await ctx.stored('blank_rest', 'u1'), 'stored'); + expectUpdatedTypedNull(await ctx.stored('blank_rest', 'u1'), 'stored'); }); it('batch create and update, createMany and updateMany', async () => { @@ -183,7 +196,7 @@ describe('REST write doors on SQLite: a cleared typed column stores null (#20308 const bu = await ctx.call('POST', '/api/v1/data/:object/batch', { object: 'blank_rest' }, { operation: 'update', records: [{ id: 'b2', data: blankTyped() }] }); expect(bu.body.results.map((r: any) => r.success)).toEqual([true]); - expectTypedNull(await ctx.stored('blank_rest', 'b2'), 'batch update'); + expectUpdatedTypedNull(await ctx.stored('blank_rest', 'b2'), 'batch update'); const cm = await ctx.call('POST', '/api/v1/data/:object/createMany', { object: 'blank_rest' }, [{ id: 'm1', ...blankTyped() }]); expect(cm.status).toBe(201); @@ -193,7 +206,7 @@ describe('REST write doors on SQLite: a cleared typed column stores null (#20308 const um = await ctx.call('POST', '/api/v1/data/:object/updateMany', { object: 'blank_rest' }, { records: [{ id: 'm2', data: blankTyped() }] }); expect(um.body.results.map((r: any) => r.success)).toEqual([true]); - expectTypedNull(await ctx.stored('blank_rest', 'm2'), 'updateMany'); + expectUpdatedTypedNull(await ctx.stored('blank_rest', 'm2'), 'updateMany'); }); it('a valid value on every typed column is stored and read back unchanged', async () => {