|
| 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 | +}); |
0 commit comments