Skip to content

Commit ee3ea87

Browse files
committed
fix(objectql,types,rest): a database NOT NULL refusal on a declared field is the validator's ValidationError at every door
The engine's write doors translate a driver NOT NULL refusal on a field the object declares into the record validator's own ValidationError, built by buildFieldError with the validator's message context, so the dispatcher /data twin, the actions door and RestServer answer 400 VALIDATION_FAILED by label. @objectstack/types exports the dialect reader notNullViolationSite and retires the relabel helpers; @objectstack/rest retires its door-side relabel. Claude-Session: https://claude.ai/code/session_01E1oXN1ZJ8NnZKKhzWeCZ6q Co-authored-by: Claude <noreply@anthropic.com>
1 parent 0c37228 commit ee3ea87

14 files changed

Lines changed: 904 additions & 556 deletions

‎packages/objectql/src/engine-insert-duplicate-record.test.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,8 @@
3030
* via the per-row fallback loop, `insertMany`'s partial mode, and the
3131
* last-chance create the autonumber resync issues when the field vanished
3232
* mid-flight; and
33-
* - **nothing else moves**: a NOT NULL violation, a deadlock, a missing table
33+
* - **nothing else moves**: a NOT NULL violation on a column no field declares
34+
* ([#24768]: on a declared field it is the validator's `ValidationError`), a deadlock, a missing table
3435
* and an unreachable store leave the door as the very object the driver
3536
* threw — asserted on IDENTITY, not on a message match, so a future
3637
* "helpful" re-wrap cannot pass this file.
@@ -125,8 +126,14 @@ const memoryDuplicate = () =>
125126

126127
/* -------- the negative side: failures that must NOT change shape --------- */
127128

129+
/**
130+
* [#24768] On a column NO field of `doc` declares: a NOT NULL refusal on a
131+
* declared field is the engine's `ValidationError` now
132+
* (`engine-not-null-refusal.test.ts`), and this one is what still leaves as the
133+
* driver threw it.
134+
*/
128135
const notNullViolation = () =>
129-
Object.assign(new Error('NOT NULL constraint failed: doc.title'), {
136+
Object.assign(new Error('NOT NULL constraint failed: doc.legacy_col'), {
130137
code: 'SQLITE_CONSTRAINT_NOTNULL',
131138
});
132139

@@ -408,7 +415,7 @@ describe('engine.insert — a driver unique violation is a DUPLICATE_RECORD enve
408415

409416
describe('nothing that is not a unique violation changes shape', () => {
410417
const controls: Array<[string, () => unknown]> = [
411-
['a NOT NULL violation', notNullViolation],
418+
['a NOT NULL violation on an undeclared column', notNullViolation],
412419
['a missing table', missingTable],
413420
['a deadlock', deadlock],
414421
['an unreachable store', unreachableStore],
Lines changed: 309 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,309 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#24768] A driver's NOT NULL refusal on a field the object declares leaves the
5+
* write doors as the record validator's own `ValidationError`, named by the
6+
* field's label in the caller's locale — on every driver exit and every dialect.
7+
*
8+
* `unit_price` (label "Sales Price") is ADR-0113's engine-populated column:
9+
* `storage: { notNull: true }`, no `required`. The validator judges `required`
10+
* only, so a write with no value for it reaches the driver, and the DATABASE
11+
* refuses it. Before this change the door let the driver's error out, and each
12+
* HTTP door classified it from the text its own way: the runtime dispatcher's
13+
* `/data` answered `500 INTERNAL_ERROR`, the actions door `400 VALIDATION_ERROR`
14+
* with the driver's text, `RestServer` `400` with the column key relabelled by a
15+
* second object read. The doors, on a real driver, are pinned in
16+
* `packages/runtime/src/dispatcher-not-null-refusal-24768.test.ts` and
17+
* `packages/rest/src/data-not-null-field-label-24715.test.ts`.
18+
*
19+
* Refusals assert `code` and the field envelope, never `toThrow()` alone. The
20+
* sentence is asked of `renderValidationMessage`, the validator's renderer, and
21+
* compared with the validator's own refusal on the same request where the
22+
* locale is what is under test.
23+
*
24+
* The driver fixtures are the shapes `notNullViolationSite`'s codes table
25+
* records per client.
26+
*/
27+
28+
import { describe, it, expect, beforeEach, vi } from 'vitest';
29+
import { redactPropagatedDriverFault } from '@objectstack/types';
30+
import { renderValidationMessage } from '@objectstack/spec/system';
31+
import { ObjectQL } from './engine';
32+
import { ValidationError, VALIDATION_FAILED_CODE } from './validation/record-validator';
33+
import { DuplicateRecordError } from './duplicate-record-error';
34+
import { NotNullRefusalError } from './not-null-refusal-error';
35+
import { SchemaRegistry } from './registry';
36+
import type { IDataDriver } from '@objectstack/spec/contracts';
37+
38+
vi.mock('./registry', async () => {
39+
const { createRegistryModuleMock } = await import('./registry-module-mock.js');
40+
return createRegistryModuleMock();
41+
});
42+
43+
/** The double's `getObject`, typed (see `engine-insert-duplicate-record.test.ts`). */
44+
const registryDouble = SchemaRegistry as unknown as { getObject: ReturnType<typeof vi.fn> };
45+
46+
type Row = Record<string, unknown>;
47+
48+
const OBJECT = 'line_item';
49+
50+
const SCHEMA = {
51+
name: OBJECT,
52+
label: 'Line item',
53+
fields: {
54+
name: { type: 'text', label: 'Name' },
55+
// ADR-0113's engine-populated column: NOT NULL on purpose, not `required`.
56+
unit_price: { type: 'number', label: 'Sales Price', storage: { notNull: true } },
57+
// The validator's own `required`, for the parity cases.
58+
list_price: { type: 'number', label: 'List Price', required: true },
59+
},
60+
};
61+
62+
/* --------------------------------------------------------------------------
63+
* Driver fixtures — the dialect shapes, each naming `line_item.unit_price`.
64+
* ----------------------------------------------------------------------- */
65+
66+
const sqlite = (table = OBJECT, column = 'unit_price') => () =>
67+
Object.assign(
68+
new Error(`insert into [statement and bound values redacted] - NOT NULL constraint failed: ${table}.${column}`),
69+
{ code: 'SQLITE_CONSTRAINT_NOTNULL' },
70+
);
71+
const libsql = () =>
72+
Object.assign(new Error(`SQLITE_CONSTRAINT: NOT NULL constraint failed: ${OBJECT}.unit_price`), {
73+
code: 'SQLITE_CONSTRAINT', extendedCode: 'SQLITE_CONSTRAINT_NOTNULL', rawCode: 1299,
74+
});
75+
const postgres = () =>
76+
Object.assign(new Error(`null value in column "unit_price" of relation "${OBJECT}" violates not-null constraint`), {
77+
code: '23502', column: 'unit_price', table: OBJECT,
78+
});
79+
const mysql = () =>
80+
Object.assign(new Error("Column 'unit_price' cannot be null"), { code: 'ER_BAD_NULL_ERROR', errno: 1048 });
81+
const sqljs = () => new Error(`NOT NULL constraint failed: ${OBJECT}.unit_price`);
82+
83+
/* --------------------------------------------------------------------------
84+
* Rig
85+
* ----------------------------------------------------------------------- */
86+
87+
const STORED: Row[] = [
88+
{ id: 'r1', name: 'a', unit_price: 5, list_price: 7 },
89+
{ id: 'r2', name: 'b', unit_price: 6, list_price: 8 },
90+
];
91+
92+
interface DriverOpts {
93+
/** What every write method rejects with. */
94+
refuse: () => unknown;
95+
/** Omit `bulkCreate` so a batch takes the engine's per-row fallback loop. */
96+
noBulkCreate?: boolean;
97+
}
98+
99+
function makeDriver(opts: DriverOpts) {
100+
const driver: any = {
101+
name: 'fake',
102+
version: '0.0.0',
103+
supports: {},
104+
connect: vi.fn().mockResolvedValue(undefined),
105+
disconnect: vi.fn().mockResolvedValue(undefined),
106+
checkHealth: vi.fn().mockResolvedValue(true),
107+
execute: vi.fn(),
108+
find: vi.fn(async () => []),
109+
// The by-id update reads the prior row before it writes (#7867's not-found gate).
110+
findOne: vi.fn(async (_obj: string, ast: { where?: { id?: unknown } }) =>
111+
STORED.find((row) => row.id === ast?.where?.id) ?? null,
112+
),
113+
create: vi.fn(async () => { throw opts.refuse(); }),
114+
update: vi.fn(async () => { throw opts.refuse(); }),
115+
updateMany: vi.fn(async () => { throw opts.refuse(); }),
116+
delete: vi.fn(),
117+
count: vi.fn(),
118+
};
119+
if (!opts.noBulkCreate) driver.bulkCreate = vi.fn(async () => { throw opts.refuse(); });
120+
return driver as IDataDriver & { create: any; bulkCreate?: any; update: any; updateMany: any };
121+
}
122+
123+
/** A logger that records the doors' `… operation failed` lines (`warn`, `meta.error = { message, stack }`). */
124+
function recordingLogger() {
125+
const lines: Array<{ msg: string; err: any }> = [];
126+
const logger = {
127+
info: vi.fn(), debug: vi.fn(), trace: vi.fn(), error: vi.fn(),
128+
warn: vi.fn((msg: string, meta?: { error?: unknown }) => { lines.push({ msg, err: meta?.error }); }),
129+
};
130+
return { logger, lines };
131+
}
132+
133+
async function makeRig(opts: DriverOpts, schema: unknown = SCHEMA) {
134+
registryDouble.getObject.mockReturnValue(schema);
135+
const driver = makeDriver(opts);
136+
const { logger, lines } = recordingLogger();
137+
const engine = new ObjectQL({ logger } as any);
138+
engine.registerDriver(driver, true);
139+
await engine.init();
140+
return { engine, driver, lines };
141+
}
142+
143+
/** The rejection, as the value the caller actually receives. */
144+
async function refusalOf(run: () => Promise<unknown>): Promise<any> {
145+
return run().then(
146+
() => { throw new Error('expected the write to be refused'); },
147+
(e) => e as any,
148+
);
149+
}
150+
151+
/** The catalog sentence the validator renders for `messageKey`. */
152+
const sentence = (messageKey: 'required' | 'required_cleared', label: string, field = 'unit_price', locale?: string) =>
153+
renderValidationMessage({ messageKey, label, field, params: {} }, { locale });
154+
155+
/** The validator's envelope, for the one field. */
156+
function expectRefusalFor(failure: any, messageKey: 'required' | 'required_cleared', label = 'Sales Price') {
157+
expect(failure).toBeInstanceOf(ValidationError);
158+
expect(failure.code).toBe(VALIDATION_FAILED_CODE);
159+
expect(failure.name).toBe('ValidationError');
160+
const message = sentence(messageKey, label);
161+
expect(failure.fields).toEqual([{ field: 'unit_price', code: 'required', message, label }]);
162+
expect(failure.message).toBe(message);
163+
}
164+
165+
const insertOne = (engine: ObjectQL, opts?: unknown) =>
166+
engine.insert(OBJECT, { name: 'n', list_price: 1 }, opts as any);
167+
const insertBatch = (engine: ObjectQL) =>
168+
engine.insert(OBJECT, [{ name: 'n', list_price: 1 }, { name: 'm', list_price: 2 }]);
169+
const updateById = (engine: ObjectQL, opts?: unknown) =>
170+
engine.update(OBJECT, { id: 'r2', unit_price: null }, opts as any);
171+
const updateByPredicate = (engine: ObjectQL) =>
172+
engine.update(OBJECT, { unit_price: null }, { where: { name: 'b' }, multi: true } as any);
173+
174+
beforeEach(() => {
175+
vi.clearAllMocks();
176+
});
177+
178+
describe('[#24768] every driver exit answers with the validator\'s `ValidationError`', () => {
179+
it('insert, one row: the label, the `required` sentence, the driver\'s error on `cause`', async () => {
180+
const raw = sqlite()();
181+
const { engine } = await makeRig({ refuse: () => raw });
182+
183+
const failure = await refusalOf(() => insertOne(engine));
184+
185+
expectRefusalFor(failure, 'required');
186+
expect(failure).toBeInstanceOf(NotNullRefusalError);
187+
expect(failure.cause).toBeInstanceOf(Error);
188+
expect(failure.cause.code).toBe('SQLITE_CONSTRAINT_NOTNULL');
189+
expect(failure.cause.message).toBe((redactPropagatedDriverFault(raw) as Error).message);
190+
// The driver's text does not become the message a door ships.
191+
expect(failure.message).not.toMatch(/constraint failed|unit_price/);
192+
});
193+
194+
it('insert, a batch through `bulkCreate`', async () => {
195+
const { engine, driver } = await makeRig({ refuse: sqlite() });
196+
expectRefusalFor(await refusalOf(() => insertBatch(engine)), 'required');
197+
expect(driver.bulkCreate).toHaveBeenCalledTimes(1);
198+
});
199+
200+
it('insert, a batch through the per-row fallback loop', async () => {
201+
const { engine, driver } = await makeRig({ refuse: sqlite(), noBulkCreate: true });
202+
expectRefusalFor(await refusalOf(() => insertBatch(engine)), 'required');
203+
expect(driver.create).toHaveBeenCalled();
204+
});
205+
206+
it('update by id: the sentence the validator gives a clear-out (`required_cleared`)', async () => {
207+
const { engine, driver } = await makeRig({ refuse: sqlite() });
208+
expectRefusalFor(await refusalOf(() => updateById(engine)), 'required_cleared');
209+
expect(driver.update).toHaveBeenCalledTimes(1);
210+
});
211+
212+
it('update by predicate: the same', async () => {
213+
const { engine, driver } = await makeRig({ refuse: sqlite() });
214+
expectRefusalFor(await refusalOf(() => updateByPredicate(engine)), 'required_cleared');
215+
expect(driver.updateMany).toHaveBeenCalledTimes(1);
216+
});
217+
218+
it('the door\'s log line carries the DATABASE\'s diagnosis, not the envelope\'s sentence', async () => {
219+
const { engine, lines } = await makeRig({ refuse: sqlite() });
220+
await refusalOf(() => insertOne(engine));
221+
await refusalOf(() => updateById(engine));
222+
223+
const insertLine = lines.find((l) => l.msg === 'Insert operation failed');
224+
const updateLine = lines.find((l) => l.msg === 'Update operation failed');
225+
expect(String(insertLine?.err?.message)).toMatch(/NOT NULL constraint failed: line_item\.unit_price/);
226+
expect(String(updateLine?.err?.message)).toMatch(/NOT NULL constraint failed: line_item\.unit_price/);
227+
});
228+
});
229+
230+
describe('[#24768] every dialect', () => {
231+
it.each([
232+
['better-sqlite3', sqlite()],
233+
['libsql', libsql],
234+
['node-postgres', postgres],
235+
['mysql2', mysql],
236+
['sql.js (text only)', sqljs],
237+
])('%s', async (_driver, refuse) => {
238+
const { engine } = await makeRig({ refuse });
239+
expectRefusalFor(await refusalOf(() => insertOne(engine)), 'required');
240+
});
241+
});
242+
243+
describe('[#24768] localized the way the validator localizes its own `required`', () => {
244+
const ZH: Record<string, string> = {
245+
[`objects.${OBJECT}.fields.unit_price.label`]: '销售价格',
246+
[`objects.${OBJECT}.fields.list_price.label`]: '标价',
247+
};
248+
const i18n = {
249+
t: (key: string, locale: string) => (locale === 'zh-CN' && ZH[key]) || key,
250+
getLocales: () => ['en', 'zh-CN'],
251+
};
252+
253+
it.each([['zh-CN'], ['zh']])('%s: the translated label in the zh-CN sentence, word for word the validator\'s', async (locale) => {
254+
const { engine } = await makeRig({ refuse: sqlite() });
255+
engine.setI18nService(i18n);
256+
const context = { locale };
257+
258+
const refusal = await refusalOf(() => insertOne(engine, { context }));
259+
const expected = sentence('required', '销售价格', 'unit_price', 'zh-CN');
260+
expect(refusal.fields).toEqual([{ field: 'unit_price', code: 'required', message: expected, label: '销售价格' }]);
261+
262+
// The validator, on the same request shape, for the field it refuses itself.
263+
const own = await refusalOf(() => engine.insert(OBJECT, { name: 'n', unit_price: 1 }, { context } as any));
264+
const ownMessage = own.fields.find((f: any) => f.field === 'list_price')?.message;
265+
expect(ownMessage).toBe(sentence('required', '标价', 'list_price', 'zh-CN'));
266+
expect(refusal.fields[0].message.replace('销售价格', 'LABEL')).toBe(ownMessage.replace('标价', 'LABEL'));
267+
});
268+
});
269+
270+
describe('[#24768] the controls: what the field map cannot name leaves as the driver threw it', () => {
271+
it('a column no field declares (drift): the driver\'s error, as it leaves the engine', async () => {
272+
const raw = sqlite(OBJECT, 'legacy_col')();
273+
const { engine } = await makeRig({ refuse: () => raw });
274+
const failure = await refusalOf(() => insertOne(engine));
275+
expect(failure).not.toBeInstanceOf(ValidationError);
276+
expect(failure.code).toBe('SQLITE_CONSTRAINT_NOTNULL');
277+
});
278+
279+
it('a refusal the driver attributes to ANOTHER table: that object\'s door names it, not this one', async () => {
280+
const { engine } = await makeRig({ refuse: sqlite('other_object', 'unit_price') });
281+
const failure = await refusalOf(() => insertOne(engine));
282+
expect(failure).not.toBeInstanceOf(ValidationError);
283+
expect(failure.code).toBe('SQLITE_CONSTRAINT_NOTNULL');
284+
});
285+
286+
it('a NOT NULL code whose column the driver did not name: the driver\'s error', async () => {
287+
const { engine } = await makeRig({ refuse: () => Object.assign(new Error('insert failed'), { code: '23502' }) });
288+
const failure = await refusalOf(() => insertOne(engine));
289+
expect(failure).not.toBeInstanceOf(ValidationError);
290+
expect(failure.code).toBe('23502');
291+
});
292+
293+
it('a unique violation is still the duplicate envelope, never this one', async () => {
294+
const { engine } = await makeRig({
295+
refuse: () => Object.assign(new Error(`UNIQUE constraint failed: ${OBJECT}.name`), { code: 'SQLITE_CONSTRAINT_UNIQUE' }),
296+
});
297+
const failure = await refusalOf(() => insertOne(engine));
298+
expect(failure).toBeInstanceOf(DuplicateRecordError);
299+
expect(failure).not.toBeInstanceOf(ValidationError);
300+
});
301+
302+
it('`required` is still the validator\'s, before any driver runs — no pre-write check reads `storage.notNull`', async () => {
303+
const { engine, driver } = await makeRig({ refuse: sqlite() });
304+
const failure = await refusalOf(() => engine.insert(OBJECT, { name: 'n' }));
305+
// `list_price` is refused by the validator; `unit_price` is not judged before the driver.
306+
expect(failure.fields.map((f: any) => f.field)).toEqual(['list_price']);
307+
expect(driver.create).not.toHaveBeenCalled();
308+
});
309+
});

‎packages/objectql/src/engine-update-duplicate-record.test.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@
3232
* violation into the envelope — the by-id `driver.update` call and the
3333
* predicate `driver.updateMany` call — and the scoped-repository facade a
3434
* hook reaches as `ctx.api.object(name)` inherits it; and
35-
* - **nothing else moves**: a NOT NULL violation, a deadlock, a missing table
35+
* - **nothing else moves**: a NOT NULL violation on a column no field declares
36+
* ([#24768]: on a declared field it is the validator's `ValidationError`), a deadlock, a missing table
3637
* and an unreachable store leave BOTH exits as the very object the driver
3738
* threw — asserted on IDENTITY, not on a message match, one pin per class
3839
* per exit (triage ruling, 2026-09-02).
@@ -140,8 +141,14 @@ const memoryDuplicate = () =>
140141

141142
/* -------- the negative side: failures that must NOT change shape --------- */
142143

144+
/**
145+
* [#24768] On a column NO field of `doc` declares: a NOT NULL refusal on a
146+
* declared field is the engine's `ValidationError` now
147+
* (`engine-not-null-refusal.test.ts`), and this one is what still leaves as the
148+
* driver threw it.
149+
*/
143150
const notNullViolation = () =>
144-
Object.assign(new Error('NOT NULL constraint failed: doc.title'), {
151+
Object.assign(new Error('NOT NULL constraint failed: doc.legacy_col'), {
145152
code: 'SQLITE_CONSTRAINT_NOTNULL',
146153
});
147154

@@ -484,7 +491,7 @@ describe('engine.update — a driver unique violation is a DUPLICATE_RECORD enve
484491

485492
describe('nothing that is not a unique violation changes shape', () => {
486493
const controls: Array<[string, () => unknown]> = [
487-
['a NOT NULL violation', notNullViolation],
494+
['a NOT NULL violation on an undeclared column', notNullViolation],
488495
['a missing table', missingTable],
489496
['a deadlock', deadlock],
490497
['an unreachable store', unreachableStore],

0 commit comments

Comments
 (0)