Skip to content

Commit 542d69a

Browse files
committed
fix(objectql)!: a select refuses a plain object or an array as its value, and as a multi-value element (#29244)
A single-value select or radio with no options returned before looking at the value, so an object or an array reached the driver as sent; a declared select admitted ['a'] through String(['a']). The arm now refuses both shapes with invalid_type ahead of option membership, and the multi-value option branch refuses an element that is an object or an array. The two #5922 pins that rested on the admission are restated as refusals that assert the shape sentence, not the operator sentence. Claude-Session: https://claude.ai/code/session_01ADHkmPFEXGDQbc7fNcM24e Co-authored-by: Claude <noreply@anthropic.com>
1 parent 04e0c2c commit 542d69a

5 files changed

Lines changed: 393 additions & 17 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql)!: a select refuses a plain object or an array as its value, and as an element of a multi-value select's array
6+
7+
Clause-②: no (narrowing)
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No metadata key, value or type moves, and no export or type changes: the record validator now refuses a write value whose shape is not the spec's stored shape for an option field (one option code, or an array of them). The narrowed face is a runtime answer to a data write, not anything an author wrote, so there is nothing for objectstack migrate meta to rewrite and no tombstone. Rows already stored are not rewritten or re-judged by this change, so no stored-row migration is prescribed either. -->
11+
12+
**BREAKING** for a data write that sends an object or an array where a select expects an option value. FROM: `{ stage: { a: 1 } }` or `{ stage: ["x"] }` on a single-value `select` / `radio` with no `options` answered `201` / `200` and stored the object or the array as sent (SQLite as its JSON text); so did `{ stage: ["a"] }` on a select whose options include `a`, and `{ labels: [{ a: 1 }] }` or `{ labels: [["a"]] }` on a `multiple: true` select, `multiselect`, `checkboxes` or `tags` field. TO: each is refused `400 VALIDATION_FAILED` with the field's `invalid_type` ("expected one option value, received an object", or "expected an array of option values, received an element that is an array"), on create, update by id, update by filter and the `validate()` dry run, and nothing is stored. The fix for a caller that hits it: send the option code itself (`{ stage: "x" }`), or an array of codes on a multi-value field (`{ labels: ["a"] }`); a value that really is structured data belongs in a `json` field.
13+
14+
One refusal changes its code: an object on a select whose declared `options` do not include it used to answer `invalid_option` and now answers `invalid_type`, because its shape is wrong before its membership is. Unchanged: strings and numbers on a single-value select, arrays of scalars on a multi-value one, option membership, a lone scalar wrapped on a multi-value field, `null`, and a filter-operator object (still refused with its own sentence). Rows already stored with an object or array value are not rewritten.

‎packages/objectql/src/validation/operator-object-write-value.test.ts‎

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -132,20 +132,28 @@ describe('#5922 — what the rule deliberately leaves alone', () => {
132132
expect(errs[0].message).toMatch(/array/i);
133133
});
134134

135-
it('admits an UNDECLARED $-spelling — not a filter any backend executes', () => {
136-
// The rule is derived from the spec's operator vocabulary, not from the
137-
// `$` sigil. `{ $inn: … }` is out of scope by construction; judging every
138-
// plain object on a scalar field is #5922's option A, which this is not.
139-
//
140-
// [#29133] Pinned on a free-form `select`, not on `text`: the text family
141-
// now refuses every plain object by its own shape rule (see
142-
// `record-validator.text-shape.test.ts`), which would make this pin pass
143-
// for a reason other than the one it states.
144-
expect(() => validateRecord(schema, { stage_free: { $inn: ['a'] } }, 'update')).not.toThrow();
135+
// The rule is derived from the spec's operator vocabulary, not from the `$`
136+
// sigil: `{ $inn: … }` is out of its scope by construction, and judging every
137+
// plain object on a scalar field is #5922's option A, which this is not.
138+
//
139+
// [#29244] Restated as refusals. Every scalar-valued type now refuses a plain
140+
// object by its own SHAPE rule (the text family since #29133, the
141+
// single-value select since #29244), so no scalar field is left that admits
142+
// one, and moving the pins to `json` would pin nothing: that column skips
143+
// this rule entirely. What the pins still prove is that THIS rule did not
144+
// claim the object. The shape sentence answers, never the operator sentence.
145+
it('an UNDECLARED $-spelling is not named as a filter operator (the shape rule refuses it)', () => {
146+
const errs = errorsOf({ stage_free: { $inn: ['a'] } });
147+
expect(errs.map((e) => [e.field, e.code])).toEqual([['stage_free', 'invalid_type']]);
148+
expect(errs[0].constraint).toMatchObject({ detail: 'expected one option value, received an object' });
149+
expect(errs[0].message).not.toContain('filter operator');
145150
});
146151

147-
it('admits a plain non-operator object (same reason)', () => {
148-
expect(() => validateRecord(schema, { stage_free: { a: 1 } }, 'update')).not.toThrow();
152+
it('a plain non-operator object is not named as a filter operator (same reason)', () => {
153+
const errs = errorsOf({ stage_free: { a: 1 } });
154+
expect(errs.map((e) => [e.field, e.code])).toEqual([['stage_free', 'invalid_type']]);
155+
expect(errs[0].constraint).toMatchObject({ detail: 'expected one option value, received an object' });
156+
expect(errs[0].message).not.toContain('filter operator');
149157
});
150158
});
151159

Lines changed: 202 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,202 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#29244] A select's value is an option code: one for a single-value
5+
* `select` / `radio`, an array of them for a multi-value one. A plain object or
6+
* an array is refused as the single value, and as an element of the array.
7+
*
8+
* Measured on `origin/main` @ `04e0c2c0` before the change, with a recording
9+
* driver behind the real engine, on insert, update by id and update by
10+
* predicate alike:
11+
*
12+
* field value before after
13+
* select, no options { a: 1 } ADMIT, driver got { a: 1 } invalid_type
14+
* select, no options (and radio) ['x'] ADMIT, driver got ['x'] invalid_type
15+
* select, options a/b ['a'] ADMIT, driver got ['a'] invalid_type
16+
* select, options a/b { a: 1 } invalid_option invalid_type
17+
* select multiple, no options [{ a: 1 }] ADMIT invalid_type
18+
* select multiple, no options [['x']] ADMIT invalid_type
19+
* select multiple, options a/b [['a']] ADMIT, driver got [['a']] invalid_type
20+
* multiselect / tags / checkboxes, free [{ a: 1 }] ADMIT invalid_type
21+
*
22+
* A string, a number, an array of scalars on a multi-value field, and option
23+
* membership are unchanged.
24+
*/
25+
26+
import { describe, it, expect } from 'vitest';
27+
import { validateRecord, validateRecordInScope, ValidationError } from './record-validator.js';
28+
import { ObjectQL } from '../engine.js';
29+
30+
const schema = {
31+
fields: {
32+
free: { type: 'select', label: 'Free' },
33+
free_radio: { type: 'radio', label: 'Free radio' },
34+
decl: { type: 'select', label: 'Stage', options: [{ value: 'a' }, { value: 'b' }] },
35+
free_multi: { type: 'select', label: 'Free multi', multiple: true },
36+
decl_multi: { type: 'select', label: 'Stages', multiple: true, options: [{ value: 'a' }, { value: 'b' }] },
37+
ms: { type: 'multiselect', label: 'MS' },
38+
tags: { type: 'tags', label: 'Tags' },
39+
boxes: { type: 'checkboxes', label: 'Boxes' },
40+
},
41+
};
42+
43+
function errorsOf(data: Record<string, unknown>, mode: 'insert' | 'update' = 'insert') {
44+
try {
45+
validateRecord(schema, data, mode);
46+
} catch (e) {
47+
if (e instanceof ValidationError) return e.fields;
48+
throw e;
49+
}
50+
return [];
51+
}
52+
53+
describe('#29244 — a single-value select refuses a plain object or an array', () => {
54+
for (const field of ['free', 'free_radio', 'decl'] as const) {
55+
for (const [shape, value, received] of [
56+
['object', { a: 1 }, 'an object'],
57+
['empty object', {}, 'an object'],
58+
['array', ['a'], 'an array'],
59+
['empty array', [], 'an array'],
60+
] as const) {
61+
for (const mode of ['insert', 'update'] as const) {
62+
it(`${field}: refuses ${shape} on ${mode} as invalid_type`, () => {
63+
const errs = errorsOf({ [field]: value }, mode);
64+
expect(errs.map((e) => [e.field, e.code])).toEqual([[field, 'invalid_type']]);
65+
expect(errs[0].constraint).toMatchObject({
66+
type: schema.fields[field].type,
67+
detail: `expected one option value, received ${received}`,
68+
});
69+
});
70+
}
71+
}
72+
}
73+
74+
it('says the field, the type and the received shape in the message', () => {
75+
const errs = errorsOf({ free: { a: 1 } });
76+
expect(errs[0].message).toContain('Free');
77+
expect(errs[0].message).toContain('select');
78+
expect(errs[0].message).toContain('expected one option value, received an object');
79+
});
80+
81+
it('refuses the shape on a readonly select too (a shape arm, reached under the readonly scope)', () => {
82+
const ro = { fields: { kind: { type: 'select', label: 'Kind', readonly: true } } };
83+
let err: unknown = null;
84+
try {
85+
validateRecordInScope(ro, { kind: ['x'] }, 'insert', 'include');
86+
} catch (e) {
87+
err = e;
88+
}
89+
expect(err).toBeInstanceOf(ValidationError);
90+
expect((err as ValidationError).fields.map((f) => [f.field, f.code])).toEqual([['kind', 'invalid_type']]);
91+
});
92+
93+
it('a filter-operator object keeps its own, earlier sentence', () => {
94+
const errs = errorsOf({ free: { $in: ['a'] } }, 'update');
95+
expect(errs).toHaveLength(1);
96+
expect(errs[0].message).toContain('$in is a filter operator, not a value');
97+
});
98+
});
99+
100+
describe('#29244 — a multi-value option field refuses an element that is a plain object or an array', () => {
101+
for (const field of ['free_multi', 'decl_multi', 'ms', 'tags', 'boxes'] as const) {
102+
for (const [shape, value, received] of [
103+
['object element', ['a', { a: 1 }], 'an object'],
104+
['array element', [['a']], 'an array'],
105+
] as const) {
106+
it(`${field}: refuses an ${shape} as invalid_type`, () => {
107+
const errs = errorsOf({ [field]: value });
108+
expect(errs.map((e) => [e.field, e.code])).toEqual([[field, 'invalid_type']]);
109+
expect(errs[0].constraint).toMatchObject({
110+
detail: `expected an array of option values, received an element that is ${received}`,
111+
});
112+
});
113+
}
114+
}
115+
});
116+
117+
describe('#29244 — what the rule leaves alone', () => {
118+
it('a scalar on a single-value select is judged as before', () => {
119+
expect(errorsOf({ free: 'anything', free_radio: 'x', decl: 'a' })).toEqual([]);
120+
expect(errorsOf({ free: 3 })).toEqual([]);
121+
expect(errorsOf({ decl: 'z' }).map((e) => e.code)).toEqual(['invalid_option']);
122+
});
123+
124+
it('an array of scalars on a multi-value field is judged as before', () => {
125+
expect(errorsOf({ free_multi: ['x', 'y'], decl_multi: ['a', 'b'], ms: ['x'], tags: ['t'], boxes: [] })).toEqual([]);
126+
expect(errorsOf({ decl_multi: ['z'] }).map((e) => e.code)).toEqual(['invalid_option']);
127+
});
128+
129+
it('a lone scalar on a multi-value select is still wrapped, and a lone object still answers invalid_type_array', () => {
130+
expect(errorsOf({ free_multi: 'x' })).toEqual([]);
131+
const errs = errorsOf({ free_multi: { a: 1 } });
132+
expect(errs.map((e) => e.code)).toEqual(['invalid_type']);
133+
expect(errs[0].message).toMatch(/array/i);
134+
expect(errs[0].message).not.toContain('option values');
135+
});
136+
137+
it('null and undefined are unchanged', () => {
138+
expect(errorsOf({ free: null, free_multi: null }, 'update')).toEqual([]);
139+
expect(errorsOf({ free: undefined }, 'insert')).toEqual([]);
140+
});
141+
});
142+
143+
/**
144+
* The end-to-end half: the engine's create, update-by-id and update-by-predicate
145+
* doors reach the rule, answer the VALIDATION_FAILED envelope, and the driver
146+
* is never written.
147+
*/
148+
describe('#29244 — write path end to end: no object or array reaches the driver', () => {
149+
async function boot() {
150+
const engine = new ObjectQL();
151+
const writes: unknown[] = [];
152+
const rows = new Map<string, Record<string, unknown>>([['rec_1', { id: 'rec_1', stage: 'orig' }]]);
153+
engine.registerDriver({
154+
name: 'recording', version: '0.0.0', supports: {},
155+
async connect() {}, async disconnect() {}, async checkHealth() { return true; },
156+
async execute() { return null; },
157+
async find() { return Array.from(rows.values()); },
158+
async findOne(_o: string, ast: any) { return rows.get(ast?.where?.id) ?? null; },
159+
async create(_o: string, data: Record<string, unknown>) { writes.push(data); return { ...data, id: 'x' }; },
160+
async update(_o: string, id: string, data: Record<string, unknown>) { writes.push(data); return { ...data, id }; },
161+
async updateMany(_o: unknown, _a: unknown, data: unknown) { writes.push(data); return 0; },
162+
async delete() { return true; }, async count() { return rows.size; },
163+
async bulkCreate() { return []; }, async bulkUpdate() { return []; }, async bulkDelete() {},
164+
async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; },
165+
async commit() {}, async rollback() {},
166+
} as any, true);
167+
await engine.init();
168+
engine.registry.registerObject({
169+
name: 'shape_deal', label: 'Deal',
170+
fields: {
171+
id: { name: 'id', label: 'ID', type: 'text', primaryKey: true },
172+
stage: { name: 'stage', label: 'Stage', type: 'select' },
173+
labels: { name: 'labels', label: 'Labels', type: 'select', multiple: true },
174+
},
175+
} as any);
176+
return { engine, writes, rows };
177+
}
178+
179+
it('refuses on insert, update and multi-update, and the driver sees no write', async () => {
180+
const { engine, writes, rows } = await boot();
181+
for (const [field, run] of [
182+
['stage', () => engine.insert('shape_deal', { stage: { a: 1 } } as any)],
183+
['stage', () => engine.update('shape_deal', { stage: ['x'] } as any, { where: { id: 'rec_1' } } as any)],
184+
['stage', () => engine.update('shape_deal', { stage: { a: 1 } } as any, { multi: true } as any)],
185+
['labels', () => engine.insert('shape_deal', { labels: [{ a: 1 }] } as any)],
186+
['labels', () => engine.update('shape_deal', { labels: [['x']] } as any, { where: { id: 'rec_1' } } as any)],
187+
] as const) {
188+
const err = await run().then(() => null, (e: unknown) => e as ValidationError);
189+
expect(err).toBeInstanceOf(ValidationError);
190+
expect(err!.code).toBe('VALIDATION_FAILED');
191+
expect(err!.fields.map((f) => [f.field, f.code])).toEqual([[field, 'invalid_type']]);
192+
}
193+
expect(writes).toEqual([]);
194+
expect(rows.get('rec_1')).toEqual({ id: 'rec_1', stage: 'orig' });
195+
});
196+
197+
it('a scalar and an array of scalars on the same path still land', async () => {
198+
const { engine, writes } = await boot();
199+
await engine.update('shape_deal', { stage: 'won', labels: ['x', 'y'] } as any, { where: { id: 'rec_1' } } as any);
200+
expect(writes).toEqual([expect.objectContaining({ stage: 'won', labels: ['x', 'y'] })]);
201+
});
202+
});

‎packages/objectql/src/validation/record-validator.ts‎

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,9 @@
5454
* - format email / url / phone (lightweight RFC-aware regex)
5555
* - select / multiselect: value must appear in `options`, or be one the write
5656
* names for the field in `keptOptionValues` (an import's kept
57-
* cell, #22183)
57+
* cell, #22183); a single value that is a plain object or an
58+
* array, or an array element that is one, is `invalid_type`
59+
* whether or not `options` are declared (#29244)
5860
* - boolean / toggle: must coerce to boolean
5961
* - date / datetime: must be ISO-parsable, naming a year from 0001 to 9999
6062
* for a `date` and from 1000 to 9999 for a `datetime` (#20280);
@@ -682,8 +684,8 @@ export function normalizeMultiValueFields(
682684
* the declared type at all", with the same wire code and the same sentence a
683685
* non-readonly field gets: a `date` / `datetime` / `time` the platform reads,
684686
* a number for a number-typed field, a boolean, an array for a multi-value
685-
* field, no plain object or array on a string-typed field, no filter-operator
686-
* object, and the ADR-0104 reference / media / structured-JSON shape under
687+
* field, no plain object or array on a string-typed field or as a select's
688+
* value or option element, no filter-operator object, and the ADR-0104 reference / media / structured-JSON shape under
687689
* the object's own posture (warn-first until the deployment's evidence says
688690
* otherwise). It is never REQUIRED.
689691
*
@@ -1687,8 +1689,26 @@ function validateOne(
16871689
// question from two authorities that happen to agree today, which is the
16881690
// drift the one-definition ruling (#17469) closes.
16891691
if ((t === 'select' || t === 'radio') && !isMultiValueField(def)) {
1690-
// Option membership is the whole arm, and it is a constraint: ⛔ never on
1691-
// a readonly value (the open-vocabulary ruling, see ReadonlyValueScope).
1692+
// [#29244] A single-value select stores ONE option code (the spec's
1693+
// `valueSchemaFor`: a declared code, or a string when no `options` are
1694+
// declared). A plain object or an array is refused as a shape, never
1695+
// judged by its string reading: with no `options` the arm returned before
1696+
// looking at the value, so `{ a: 1 }` and `['x']` reached the driver as
1697+
// sent; with `options`, `['a']` passed membership as `String(['a'])` and
1698+
// the driver stored the array. Neither the list nor the filter door (which
1699+
// refuses an object or array comparand on this field) can read either.
1700+
// Same posture and sentence as the string arm's #29133 rule. A SHAPE test,
1701+
// so it runs ahead of `shapeOnly` and of option membership; a filter
1702+
// operator object was already refused above, with its own sentence.
1703+
if (isPlainObjectValue(value) || Array.isArray(value)) {
1704+
return fail(
1705+
'invalid_type',
1706+
{ type: t, detail: `expected one option value, received ${Array.isArray(value) ? 'an array' : 'an object'}` },
1707+
'invalid_value_shape',
1708+
);
1709+
}
1710+
// Option membership is the rest of the arm, and it is a constraint: ⛔ never
1711+
// on a readonly value (the open-vocabulary ruling, see ReadonlyValueScope).
16921712
if (shapeOnly) return null;
16931713
const allowed = optionValues(def.options);
16941714
if (picklist !== undefined && allowed.length === 0) return picklistUnresolved();
@@ -1728,6 +1748,20 @@ function validateOne(
17281748
// including a system write. Whether a referenced id EXISTS is still
17291749
// `assertReferencesResolve`'s question, with its own `isSystem` latitude.
17301750
if (!isValueShapeJudgedType(t)) {
1751+
// [#29244] Each element is one option code, as for a single value. An
1752+
// element that is a plain object or an array is refused as a shape: with
1753+
// no `options` this branch admitted any array, and with `options` a
1754+
// nested `['a']` passed membership as `String(['a'])`. A shape test, so
1755+
// ahead of `shapeOnly`; an array of scalars is judged as before.
1756+
const nested = value.find((v) => isPlainObjectValue(v) || Array.isArray(v));
1757+
if (nested !== undefined) {
1758+
const received = Array.isArray(nested) ? 'an array' : 'an object';
1759+
return fail(
1760+
'invalid_type',
1761+
{ type: t, detail: `expected an array of option values, received an element that is ${received}` },
1762+
'invalid_value_shape',
1763+
);
1764+
}
17311765
if (shapeOnly) return null;
17321766
const allowed = optionValues(def.options);
17331767
if (allowed.length === 0) {

0 commit comments

Comments
 (0)