|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#24715] A `/data` write's NOT NULL refusal names the field by its LABEL, in |
| 5 | + * the caller's locale, and a field declared `storage: { notNull: true }` is not |
| 6 | + * told to declare `required`. |
| 7 | + * |
| 8 | + * `unit_price` (label "Sales Price") is ADR-0113's engine-populated column: |
| 9 | + * `storage: { notNull: true }`, no `required`. The record validator judges |
| 10 | + * `required` only, so a write with no value for it reaches the driver and the |
| 11 | + * DATABASE refuses it. Measured on `origin/main` `7e7e605de` through these same |
| 12 | + * two doors, before the change: |
| 13 | + * |
| 14 | + * PATCH /api/v1/data/OBJECT/ID { "unit_price": null } |
| 15 | + * POST /api/v1/data/OBJECT { …, no unit_price } |
| 16 | + * 400 { "error": "unit_price is required", "code": "VALIDATION_FAILED", |
| 17 | + * "fields": [{ "field": "unit_price", "code": "required", |
| 18 | + * "message": "unit_price is required" }], |
| 19 | + * "hint": "The database column for 'unit_price' requires a value: |
| 20 | + * provide it, or declare the field `required` in the |
| 21 | + * object metadata. If the object declares neither … run |
| 22 | + * 'os migrate' …", "object": "OBJECT" } |
| 23 | + * |
| 24 | + * Read through the public doors, over a REAL `ObjectQL` + |
| 25 | + * `ObjectStackProtocolImplementation` + SQLite `:memory:`, with the stored |
| 26 | + * metadata family registered so the protocol's by-name object read answers |
| 27 | + * (the door reads the field's label and `storage` there). |
| 28 | + * |
| 29 | + * The controls: a field the metadata declares with neither `required` nor |
| 30 | + * `storage.notNull` on a NOT NULL column (drift) keeps the drift hint; a column |
| 31 | + * the metadata does not declare at all keeps the column's sentence. Pinned by |
| 32 | + * kind: the sentence is the catalog's `required` sentence for the label (asked |
| 33 | + * of `renderValidationMessage`, the record validator's own renderer), and the |
| 34 | + * hint is judged by what it prescribes. |
| 35 | + */ |
| 36 | + |
| 37 | +import { describe, it, expect, afterEach } from 'vitest'; |
| 38 | +import { ObjectQL } from '@objectstack/objectql'; |
| 39 | +import { SqlDriver } from '@objectstack/driver-sql'; |
| 40 | +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; |
| 41 | +import { |
| 42 | + SysMetadataAuditObject, |
| 43 | + SysMetadataCommitObject, |
| 44 | + SysMetadataHistoryObject, |
| 45 | + SysMetadataObject, |
| 46 | +} from '@objectstack/metadata-core'; |
| 47 | +import { renderValidationMessage } from '@objectstack/spec/system'; |
| 48 | +import { RestServer } from './rest-server'; |
| 49 | + |
| 50 | +const OBJECT = 'line_item_24715'; |
| 51 | + |
| 52 | +/** The metadata as the DDL saw it: every column the table is built with. */ |
| 53 | +const AS_SYNCED = { |
| 54 | + name: OBJECT, label: 'Line item', systemFields: false, |
| 55 | + fields: { |
| 56 | + id: { name: 'id', type: 'text' as const, primaryKey: true }, |
| 57 | + name: { name: 'name', type: 'text' as const, label: 'Name' }, |
| 58 | + // ADR-0113's engine-populated column: NOT NULL on purpose, not `required`. |
| 59 | + unit_price: { name: 'unit_price', type: 'number' as const, label: 'Sales Price', storage: { notNull: true } }, |
| 60 | + // The validator's own `required`, for the parity case. |
| 61 | + list_price: { name: 'list_price', type: 'number' as const, label: 'List Price', required: true }, |
| 62 | + drift_col: { name: 'drift_col', type: 'text' as const, label: 'Drift Column', storage: { notNull: true } }, |
| 63 | + gone_col: { name: 'gone_col', type: 'text' as const, label: 'Gone Column', storage: { notNull: true } }, |
| 64 | + }, |
| 65 | +}; |
| 66 | + |
| 67 | +/** |
| 68 | + * The metadata the doors read afterwards: `drift_col` declares neither |
| 69 | + * `required` nor `storage.notNull` over a column that is still NOT NULL (drift), |
| 70 | + * and `gone_col` is not declared at all. |
| 71 | + */ |
| 72 | +const SERVED = (() => { |
| 73 | + const { gone_col: _gone, drift_col, ...fields } = AS_SYNCED.fields; |
| 74 | + const { storage: _storage, ...undeclared } = drift_col; |
| 75 | + return { ...AS_SYNCED, fields: { ...fields, drift_col: undeclared } }; |
| 76 | +})(); |
| 77 | + |
| 78 | +const ZH_LABELS: Record<string, string> = { |
| 79 | + [`objects.${OBJECT}.fields.unit_price.label`]: '销售价格', |
| 80 | + [`objects.${OBJECT}.fields.list_price.label`]: '标价', |
| 81 | +}; |
| 82 | +/** An `II18nService` holding a `zh-CN` bundle: `t` echoes the key on a miss. */ |
| 83 | +const I18N = { |
| 84 | + t: (key: string, locale: string) => (locale === 'zh-CN' && ZH_LABELS[key]) || key, |
| 85 | + getLocales: () => ['en', 'zh-CN'], |
| 86 | +}; |
| 87 | + |
| 88 | +function createMockServer() { |
| 89 | + const noop = () => {}; |
| 90 | + return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; |
| 91 | +} |
| 92 | + |
| 93 | +function makeRes() { |
| 94 | + const res: any = { |
| 95 | + write: () => true, end: () => {}, |
| 96 | + header: () => res, |
| 97 | + status: (code: number) => { res._status = code; return res; }, |
| 98 | + json: (body: any) => { res._json = body; return res; }, |
| 99 | + }; |
| 100 | + return res; |
| 101 | +} |
| 102 | + |
| 103 | +const liveEngines: ObjectQL[] = []; |
| 104 | +afterEach(async () => { |
| 105 | + while (liveEngines.length) { |
| 106 | + try { await liveEngines.pop()?.destroy(); } catch { /* noop */ } |
| 107 | + } |
| 108 | +}); |
| 109 | + |
| 110 | +async function boot(opts: { locale?: string; i18n?: boolean } = {}) { |
| 111 | + const engine = new ObjectQL(); |
| 112 | + liveEngines.push(engine); |
| 113 | + engine.registerDriver(new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), true); |
| 114 | + await engine.init(); |
| 115 | + if (opts.i18n) engine.setI18nService(I18N); |
| 116 | + engine.registry.registerObject(AS_SYNCED as any); |
| 117 | + await engine.syncSchemas(); |
| 118 | + await engine.insert(OBJECT, { id: 'e1', name: 'existing', unit_price: 5, list_price: 7, drift_col: 'd', gone_col: 'g' } as any); |
| 119 | + engine.registry.registerObject(SERVED as any); |
| 120 | + // The protocol's object read consults the stored-metadata family; registered |
| 121 | + // after the DDL, as a boot does, so its unprovisioned table reads as empty. |
| 122 | + for (const o of [SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) { |
| 123 | + if (!engine.registry.getObject(o.name)) engine.registry.registerObject(o as any); |
| 124 | + } |
| 125 | + |
| 126 | + const protocol = new ObjectStackProtocolImplementation(engine as any); |
| 127 | + const rest = new RestServer( |
| 128 | + createMockServer() as any, protocol as any, { api: { requireAuth: false } } as any, |
| 129 | + undefined, undefined, undefined, undefined, undefined, |
| 130 | + undefined, undefined, undefined, undefined, undefined, |
| 131 | + // i18nServiceProvider — the 14th constructor argument. |
| 132 | + async () => (opts.i18n ? I18N : undefined) as any, |
| 133 | + ); |
| 134 | + (rest as any).resolveExecCtx = async () => ({ userId: 'test-user', ...(opts.locale ? { locale: opts.locale } : {}) }); |
| 135 | + rest.registerRoutes(); |
| 136 | + const call = async (method: string, path: string, body: unknown, params: Record<string, string> = { object: OBJECT }) => { |
| 137 | + const route = rest.getRoutes().find((r: any) => r.method === method && r.path === path); |
| 138 | + expect(route, `${method} ${path}`).toBeDefined(); |
| 139 | + const res = makeRes(); |
| 140 | + await route!.handler({ params, body, query: {}, headers: {} } as any, res); |
| 141 | + return { status: res._status ?? 200, body: res._json }; |
| 142 | + }; |
| 143 | + const patch = (data: Record<string, unknown>) => |
| 144 | + call('PATCH', '/api/v1/data/:object/:id', data, { object: OBJECT, id: 'e1' }); |
| 145 | + const create = (data: Record<string, unknown>) => call('POST', '/api/v1/data/:object', data); |
| 146 | + const stored = async () => (await engine.find(OBJECT, { where: { id: 'e1' } }) as any[])[0]; |
| 147 | + return { engine, patch, create, stored }; |
| 148 | +} |
| 149 | + |
| 150 | +/** The catalog's `required` sentence for `label`, in `locale` — what the record validator renders. */ |
| 151 | +const requiredSentence = (label: string, field: string, locale?: string) => |
| 152 | + renderValidationMessage({ messageKey: 'required', label, field, params: {} }, { locale }); |
| 153 | + |
| 154 | +/** The envelope the classification answers, with the field's sentence `message`. */ |
| 155 | +function expectRefusal(door: { status: number; body: any }, field: string, message: string) { |
| 156 | + expect(door.status, JSON.stringify(door.body)).toBe(400); |
| 157 | + expect(door.body).toMatchObject({ |
| 158 | + code: 'VALIDATION_FAILED', |
| 159 | + error: message, |
| 160 | + fields: [{ field, code: 'required', message }], |
| 161 | + object: OBJECT, |
| 162 | + }); |
| 163 | + // No key is added or dropped, on the body or on the field. |
| 164 | + expect(Object.keys(door.body).sort()).toEqual(['code', 'error', 'fields', 'hint', 'object']); |
| 165 | + expect(Object.keys(door.body.fields[0]).sort()).toEqual(['code', 'field', 'message']); |
| 166 | +} |
| 167 | + |
| 168 | +/** The declared column's hint: the value, or the default / hook that supplies it — never `required`, never drift. */ |
| 169 | +function expectDeclaredNotNullHint(hint: unknown, field: string) { |
| 170 | + const text = String(hint); |
| 171 | + expect(text).toContain(`'${field}'`); |
| 172 | + expect(text).toContain('`storage: { notNull: true }`'); |
| 173 | + expect(text).toMatch(/requires a value/); |
| 174 | + expect(text).not.toContain('`required`'); |
| 175 | + expect(text).not.toMatch(/drift|os migrate/); |
| 176 | +} |
| 177 | + |
| 178 | +describe('[#24715] a declared `storage.notNull` field\'s refusal names its label', () => { |
| 179 | + it('the fixture is the ADR-0113 posture: the validator lets the write through and the database refuses it', async () => { |
| 180 | + const { engine } = await boot(); |
| 181 | + expect(AS_SYNCED.fields.unit_price).toMatchObject({ label: 'Sales Price', storage: { notNull: true } }); |
| 182 | + expect('required' in AS_SYNCED.fields.unit_price).toBe(false); |
| 183 | + await expect(engine.update(OBJECT, { unit_price: null } as any, { where: { id: 'e1' } } as any)).rejects.toThrow(/not null/i); |
| 184 | + }); |
| 185 | + |
| 186 | + it('PATCH writing null: the label in `error` and `fields[0].message`, the declared column\'s hint', async () => { |
| 187 | + const { patch, stored } = await boot(); |
| 188 | + const door = await patch({ unit_price: null }); |
| 189 | + expectRefusal(door, 'unit_price', requiredSentence('Sales Price', 'unit_price')); |
| 190 | + expect(door.body.error).not.toContain('unit_price'); |
| 191 | + expectDeclaredNotNullHint(door.body.hint, 'unit_price'); |
| 192 | + expect((await stored()).unit_price).toBe(5); |
| 193 | + }); |
| 194 | + |
| 195 | + it('POST with no value: the same answer', async () => { |
| 196 | + const { create, engine } = await boot(); |
| 197 | + const door = await create({ id: 'n1', name: 'new', list_price: 1, drift_col: 'd' }); |
| 198 | + expectRefusal(door, 'unit_price', requiredSentence('Sales Price', 'unit_price')); |
| 199 | + expectDeclaredNotNullHint(door.body.hint, 'unit_price'); |
| 200 | + expect(await engine.find(OBJECT, { where: { id: 'n1' } })).toHaveLength(0); |
| 201 | + }); |
| 202 | +}); |
| 203 | + |
| 204 | +describe('[#24715] localized the way the record validator localizes its own `required`', () => { |
| 205 | + it('zh-CN: the translated label in the catalog\'s zh-CN sentence — the validator\'s template, word for word', async () => { |
| 206 | + const { patch, create } = await boot({ locale: 'zh-CN', i18n: true }); |
| 207 | + |
| 208 | + const door = await patch({ unit_price: null }); |
| 209 | + expectRefusal(door, 'unit_price', requiredSentence('销售价格', 'unit_price', 'zh-CN')); |
| 210 | + expectDeclaredNotNullHint(door.body.hint, 'unit_price'); |
| 211 | + |
| 212 | + // The validator, on the same request shape, for the field it refuses itself. |
| 213 | + const own = await create({ id: 'n1', name: 'new', unit_price: 1, drift_col: 'd' }); |
| 214 | + expect(own.status, JSON.stringify(own.body)).toBe(400); |
| 215 | + const validatorMessage = own.body.fields.find((f: any) => f.field === 'list_price')?.message; |
| 216 | + expect(validatorMessage).toBe(requiredSentence('标价', 'list_price', 'zh-CN')); |
| 217 | + expect(door.body.error.replace('销售价格', 'LABEL')).toBe(validatorMessage.replace('标价', 'LABEL')); |
| 218 | + }); |
| 219 | + |
| 220 | + it('a bare `zh` reaches the zh-CN bundle, as the validator\'s locale negotiation does', async () => { |
| 221 | + const { patch } = await boot({ locale: 'zh', i18n: true }); |
| 222 | + const door = await patch({ unit_price: null }); |
| 223 | + expectRefusal(door, 'unit_price', requiredSentence('销售价格', 'unit_price', 'zh-CN')); |
| 224 | + }); |
| 225 | +}); |
| 226 | + |
| 227 | +describe('[#24715] the controls: what the field map cannot name keeps today\'s answer', () => { |
| 228 | + it('drift — declared with neither `required` nor `storage.notNull` over a NOT NULL column: the label, and the drift hint', async () => { |
| 229 | + const { patch } = await boot(); |
| 230 | + const door = await patch({ drift_col: null }); |
| 231 | + expectRefusal(door, 'drift_col', requiredSentence('Drift Column', 'drift_col')); |
| 232 | + expect(String(door.body.hint)).toMatch(/drifted from metadata/); |
| 233 | + expect(String(door.body.hint)).toMatch(/os migrate/); |
| 234 | + }); |
| 235 | + |
| 236 | + it('a column the metadata does not declare: the column\'s sentence and the drift hint', async () => { |
| 237 | + const { create } = await boot(); |
| 238 | + const door = await create({ id: 'n1', name: 'new', unit_price: 1, list_price: 1, drift_col: 'd' }); |
| 239 | + expectRefusal(door, 'gone_col', 'gone_col is required'); |
| 240 | + expect(String(door.body.hint)).toMatch(/os migrate/); |
| 241 | + }); |
| 242 | +}); |
0 commit comments