diff --git a/.changeset/34199-record-reference-refused-by-name.md b/.changeset/34199-record-reference-refused-by-name.md new file mode 100644 index 00000000000..1040fe68d16 --- /dev/null +++ b/.changeset/34199-record-reference-refused-by-name.md @@ -0,0 +1,19 @@ +--- +'@objectstack/core': minor +'@objectstack/spec': minor +--- + +fix(core): an unresolved `{ $record }` lookup-filter comparand is refused by name before any driver sees it + +Clause-②: no +Metadata-protocol: semantic + +A `lookupFilters` entry may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }`; only the record picker of the form editing that record can replace it with a value. When one reaches a server unresolved as a field's comparand (the field's own value, or the value of an operator on that field), the engine's token pass (`resolveFilterTokens`) now refuses it with `INVALID_FILTER` / 400, and the message names the field, the `$record` path and its position, for example: + +`A { "$record": "account.cb_market" } comparand on field "cb_market" at filter.cb_market reached the server unresolved, and is refused rather than compared.` + +- Before: the eq shorthand `{ cb_market: { $record: "account.cb_market" } }` reached the driver, which refused it in its own words: driver-memory as an unsupported operator `"$record"`, driver-sql with the operator and field withheld. Both were already `INVALID_FILTER` / 400 (driver-mongodb refuses an unknown operator the same way), so on the built-in drivers no filter that answered rows now refuses: the pass judges only a field's comparand, never a value inside one (see Unchanged). +- Now: that shape is refused by name before any driver is asked, on every engine verb and in the analytics service, whether or not the filter also holds a string placeholder. On the engine's object path the other five operators (`{ valid_from: { $lte: { $record: "…" } } }`) and the eq shorthand on a date, datetime or time column are still refused one door earlier, in that door's own words, as before. The engine lowers a `[field, op, value]` array `where` before the pass, so there the array spelling is judged as its object form; the analytics service hands the pass its `where` unlowered, and the pass leaves a tuple to the doors that judged it before. +- Unchanged: a `{ $record }` deeper inside a comparand is a deep-equality literal (or a nested-relation condition) and passes through as before, in either spelling: the object form `{ attachment: { meta: { $record: "x" } } }`, which driver-memory still compares whole, and the tuple `['attachment', '=', { meta: { $record: "x" } }]`, whose third member is a comparand, never a filter node. Both come back from the pass by reference (pinned as CONTROLs on `resolveFilterTokens`). + +The `value` and `lookupFilters` describes now say what holds on the server: an unresolved `{ $record }` is refused with `INVALID_FILTER`, never read as null, and, in `lookupFilters`, by name on the eq shorthand of a column other than a date, datetime or time column. Their picker sentences (a record form sends the referenced value; every other picker host leaves the entry out) are not changed by this entry. diff --git a/content/docs/references/data/field.mdx b/content/docs/references/data/field.mdx index 88817c90f0d..18f6f0d956b 100644 --- a/content/docs/references/data/field.mdx +++ b/content/docs/references/data/field.mdx @@ -93,7 +93,7 @@ const result = CurrencyConfigSchema.parse(data); | **descriptionField** | `string` | optional | Secondary field shown under the label in the quick-select popover. | | **lookupColumns** | `(string \| { field: string; label?: string; width?: string; type?: string })[]` | optional | Explicit columns for the record-picker table; auto-derived from the referenced object when omitted. | | **lookupPageSize** | `integer` | optional | Rows per page in the record-picker dialog (default 10). | -| **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any; orEmpty?: boolean }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. Each entry compares a column of the CANDIDATE record (`field`, on the referenced object) with `value`. A value may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). In a record form, whatever its layout, the picker sends that value in its place and re-queries whenever a referenced field changes; every other picker host leaves every `{ $record }` entry out: inline edit on a record page, a record page's header or related list, an action's parameter dialog, and a picker with no single record being edited (a bulk action over selected rows). The referenced fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['quote_date']` adds `quote_date = …` to the query over the referenced object). While the value is empty or cannot be read (the hop's row or field does not come back, no object is named for the hop, or the host has no single-row reader), the entry is left out. A `{ $record }` is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A `{ $record }` that reaches a server unresolved is refused, never read as null. The picker narrows the choice only: a rule the save must enforce belongs on the server too. | +| **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any; orEmpty?: boolean }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. Each entry compares a column of the CANDIDATE record (`field`, on the referenced object) with `value`. A value may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). In a record form, whatever its layout, the picker sends that value in its place and re-queries whenever a referenced field changes; every other picker host leaves every `{ $record }` entry out: inline edit on a record page, a record page's header or related list, an action's parameter dialog, and a picker with no single record being edited (a bulk action over selected rows). The referenced fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['quote_date']` adds `quote_date = …` to the query over the referenced object). While the value is empty or cannot be read (the hop's row or field does not come back, no object is named for the hop, or the host has no single-row reader), the entry is left out. A `{ $record }` is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A `{ $record }` that reaches a server unresolved is refused (INVALID_FILTER), never read as null: by name, naming the field and the path, when it arrives as the eq shorthand on a column other than a date, datetime or time column; any other operator, and eq on a date, datetime or time column, is refused earlier, in generic words. The picker narrows the choice only: a rule the save must enforce belongs on the server too. | | **dependsOn** | `(string \| { field: string; param?: string })[]` | optional | Declares that this field's available values depend on the value of other field(s) on the same record — the form gates the field until they are set and re-evaluates as they change. For `lookup`/`master_detail` it scopes the candidate query (string = same local/remote key; `{field,param}` when the remote filter key differs — the `{field,param}` form is lookup-only). For `select`/`multiselect`/`radio` the actual per-option rule lives in each option's `visibleWhen`; list the referenced fields here (string form) so the option list gates and refreshes with the parent. | | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | | **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. | @@ -242,7 +242,7 @@ const result = CurrencyConfigSchema.parse(data); | :--- | :--- | :--- | :--- | | **field** | `string` | ✅ | | | **operator** | `Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>` | ✅ | | -| **value** | `any` | ✅ | The comparand: a literal (an array for `in` / `notIn`), a date placeholder such as `{today}` or a `{ $now: true, addDays }` comparand for a date relative to today, or a `{ $record: "path" }` reference to the record being edited — a field of it, or one lookup hop ("account.cb_market"); a `{ $record }` value pairs only with eq, ne, gt, lt, gte or lte. In a record form, whatever its layout, the picker sends the referenced value in place of the reference; every other picker host leaves the entry out. | +| **value** | `any` | ✅ | The comparand: a literal (an array for `in` / `notIn`), a date placeholder such as `{today}` or a `{ $now: true, addDays }` comparand for a date relative to today, or a `{ $record: "path" }` reference to the record being edited — a field of it, or one lookup hop ("account.cb_market"); a `{ $record }` value pairs only with eq, ne, gt, lt, gte or lte. In a record form, whatever its layout, the picker sends the referenced value in place of the reference; every other picker host leaves the entry out. A `{ $record }` that reaches a server unresolved is refused (INVALID_FILTER), never read as null. | | **orEmpty** | `boolean` | optional | TRUE: the entry also matches a candidate whose column is null — "valid from the quote date, or with no start date". Only with eq, ne, gt, lt, gte or lte. The picker sends the comparison or a null match on the same column. | ### Nested Shape: `Field.lookupAutofill[number]` diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 8b5c26a2024..f81d49afcd7 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -270,7 +270,7 @@ const result = ApiMethod.parse(data); | **descriptionField** | `string` | optional | Secondary field shown under the label in the quick-select popover. | | **lookupColumns** | `(string \| { field: string; label?: string; width?: string; type?: string })[]` | optional | Explicit columns for the record-picker table; auto-derived from the referenced object when omitted. | | **lookupPageSize** | `integer` | optional | Rows per page in the record-picker dialog (default 10). | -| **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any; orEmpty?: boolean }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. Each entry compares a column of the CANDIDATE record (`field`, on the referenced object) with `value`. A value may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). In a record form, whatever its layout, the picker sends that value in its place and re-queries whenever a referenced field changes; every other picker host leaves every `{ $record }` entry out: inline edit on a record page, a record page's header or related list, an action's parameter dialog, and a picker with no single record being edited (a bulk action over selected rows). The referenced fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['quote_date']` adds `quote_date = …` to the query over the referenced object). While the value is empty or cannot be read (the hop's row or field does not come back, no object is named for the hop, or the host has no single-row reader), the entry is left out. A `{ $record }` is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A `{ $record }` that reaches a server unresolved is refused, never read as null. The picker narrows the choice only: a rule the save must enforce belongs on the server too. | +| **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any; orEmpty?: boolean }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. Each entry compares a column of the CANDIDATE record (`field`, on the referenced object) with `value`. A value may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). In a record form, whatever its layout, the picker sends that value in its place and re-queries whenever a referenced field changes; every other picker host leaves every `{ $record }` entry out: inline edit on a record page, a record page's header or related list, an action's parameter dialog, and a picker with no single record being edited (a bulk action over selected rows). The referenced fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['quote_date']` adds `quote_date = …` to the query over the referenced object). While the value is empty or cannot be read (the hop's row or field does not come back, no object is named for the hop, or the host has no single-row reader), the entry is left out. A `{ $record }` is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A `{ $record }` that reaches a server unresolved is refused (INVALID_FILTER), never read as null: by name, naming the field and the path, when it arrives as the eq shorthand on a column other than a date, datetime or time column; any other operator, and eq on a date, datetime or time column, is refused earlier, in generic words. The picker narrows the choice only: a rule the save must enforce belongs on the server too. | | **dependsOn** | `(string \| { field: string; param?: string })[]` | optional | Declares that this field's available values depend on the value of other field(s) on the same record — the form gates the field until they are set and re-evaluates as they change. For `lookup`/`master_detail` it scopes the candidate query (string = same local/remote key; `{field,param}` when the remote filter key differs — the `{field,param}` form is lookup-only). For `select`/`multiselect`/`radio` the actual per-option rule lives in each option's `visibleWhen`; list the referenced fields here (string form) so the option list gates and refreshes with the parent. | | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | | **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. | @@ -647,7 +647,7 @@ const result = ApiMethod.parse(data); | **descriptionField** | `string` | optional | Secondary field shown under the label in the quick-select popover. | | **lookupColumns** | `(string \| { field: string; label?: string; width?: string; type?: string })[]` | optional | Explicit columns for the record-picker table; auto-derived from the referenced object when omitted. | | **lookupPageSize** | `integer` | optional | Rows per page in the record-picker dialog (default 10). | -| **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any; orEmpty?: boolean }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. Each entry compares a column of the CANDIDATE record (`field`, on the referenced object) with `value`. A value may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). In a record form, whatever its layout, the picker sends that value in its place and re-queries whenever a referenced field changes; every other picker host leaves every `{ $record }` entry out: inline edit on a record page, a record page's header or related list, an action's parameter dialog, and a picker with no single record being edited (a bulk action over selected rows). The referenced fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['quote_date']` adds `quote_date = …` to the query over the referenced object). While the value is empty or cannot be read (the hop's row or field does not come back, no object is named for the hop, or the host has no single-row reader), the entry is left out. A `{ $record }` is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A `{ $record }` that reaches a server unresolved is refused, never read as null. The picker narrows the choice only: a rule the save must enforce belongs on the server too. | +| **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any; orEmpty?: boolean }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. Each entry compares a column of the CANDIDATE record (`field`, on the referenced object) with `value`. A value may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). In a record form, whatever its layout, the picker sends that value in its place and re-queries whenever a referenced field changes; every other picker host leaves every `{ $record }` entry out: inline edit on a record page, a record page's header or related list, an action's parameter dialog, and a picker with no single record being edited (a bulk action over selected rows). The referenced fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['quote_date']` adds `quote_date = …` to the query over the referenced object). While the value is empty or cannot be read (the hop's row or field does not come back, no object is named for the hop, or the host has no single-row reader), the entry is left out. A `{ $record }` is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A `{ $record }` that reaches a server unresolved is refused (INVALID_FILTER), never read as null: by name, naming the field and the path, when it arrives as the eq shorthand on a column other than a date, datetime or time column; any other operator, and eq on a date, datetime or time column, is refused earlier, in generic words. The picker narrows the choice only: a rule the save must enforce belongs on the server too. | | **dependsOn** | `(string \| { field: string; param?: string })[]` | optional | Declares that this field's available values depend on the value of other field(s) on the same record — the form gates the field until they are set and re-evaluates as they change. For `lookup`/`master_detail` it scopes the candidate query (string = same local/remote key; `{field,param}` when the remote filter key differs — the `{field,param}` form is lookup-only). For `select`/`multiselect`/`radio` the actual per-option rule lives in each option's `visibleWhen`; list the referenced fields here (string form) so the option list gates and refreshes with the parent. | | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | | **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. | diff --git a/content/docs/references/system/migration.mdx b/content/docs/references/system/migration.mdx index 43c5323cd6f..102c9953f41 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -96,7 +96,7 @@ Add a new field to an existing object | **descriptionField** | `string` | optional | Secondary field shown under the label in the quick-select popover. | | **lookupColumns** | `(string \| { field: string; label?: string; width?: string; type?: string })[]` | optional | Explicit columns for the record-picker table; auto-derived from the referenced object when omitted. | | **lookupPageSize** | `integer` | optional | Rows per page in the record-picker dialog (default 10). | -| **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any; orEmpty?: boolean }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. Each entry compares a column of the CANDIDATE record (`field`, on the referenced object) with `value`. A value may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). In a record form, whatever its layout, the picker sends that value in its place and re-queries whenever a referenced field changes; every other picker host leaves every `{ $record }` entry out: inline edit on a record page, a record page's header or related list, an action's parameter dialog, and a picker with no single record being edited (a bulk action over selected rows). The referenced fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['quote_date']` adds `quote_date = …` to the query over the referenced object). While the value is empty or cannot be read (the hop's row or field does not come back, no object is named for the hop, or the host has no single-row reader), the entry is left out. A `{ $record }` is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A `{ $record }` that reaches a server unresolved is refused, never read as null. The picker narrows the choice only: a rule the save must enforce belongs on the server too. | +| **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any; orEmpty?: boolean }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. Each entry compares a column of the CANDIDATE record (`field`, on the referenced object) with `value`. A value may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). In a record form, whatever its layout, the picker sends that value in its place and re-queries whenever a referenced field changes; every other picker host leaves every `{ $record }` entry out: inline edit on a record page, a record page's header or related list, an action's parameter dialog, and a picker with no single record being edited (a bulk action over selected rows). The referenced fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['quote_date']` adds `quote_date = …` to the query over the referenced object). While the value is empty or cannot be read (the hop's row or field does not come back, no object is named for the hop, or the host has no single-row reader), the entry is left out. A `{ $record }` is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A `{ $record }` that reaches a server unresolved is refused (INVALID_FILTER), never read as null: by name, naming the field and the path, when it arrives as the eq shorthand on a column other than a date, datetime or time column; any other operator, and eq on a date, datetime or time column, is refused earlier, in generic words. The picker narrows the choice only: a rule the save must enforce belongs on the server too. | | **dependsOn** | `(string \| { field: string; param?: string })[]` | optional | Declares that this field's available values depend on the value of other field(s) on the same record — the form gates the field until they are set and re-evaluates as they change. For `lookup`/`master_detail` it scopes the candidate query (string = same local/remote key; `{field,param}` when the remote filter key differs — the `{field,param}` form is lookup-only). For `select`/`multiselect`/`radio` the actual per-option rule lives in each option's `visibleWhen`; list the referenced fields here (string form) so the option list gates and refreshes with the parent. | | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | | **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. | @@ -532,7 +532,7 @@ Add a new field to an existing object | **descriptionField** | `string` | optional | Secondary field shown under the label in the quick-select popover. | | **lookupColumns** | `(string \| { field: string; label?: string; width?: string; type?: string })[]` | optional | Explicit columns for the record-picker table; auto-derived from the referenced object when omitted. | | **lookupPageSize** | `integer` | optional | Rows per page in the record-picker dialog (default 10). | -| **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any; orEmpty?: boolean }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. Each entry compares a column of the CANDIDATE record (`field`, on the referenced object) with `value`. A value may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). In a record form, whatever its layout, the picker sends that value in its place and re-queries whenever a referenced field changes; every other picker host leaves every `{ $record }` entry out: inline edit on a record page, a record page's header or related list, an action's parameter dialog, and a picker with no single record being edited (a bulk action over selected rows). The referenced fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['quote_date']` adds `quote_date = …` to the query over the referenced object). While the value is empty or cannot be read (the hop's row or field does not come back, no object is named for the hop, or the host has no single-row reader), the entry is left out. A `{ $record }` is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A `{ $record }` that reaches a server unresolved is refused, never read as null. The picker narrows the choice only: a rule the save must enforce belongs on the server too. | +| **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any; orEmpty?: boolean }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. Each entry compares a column of the CANDIDATE record (`field`, on the referenced object) with `value`. A value may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). In a record form, whatever its layout, the picker sends that value in its place and re-queries whenever a referenced field changes; every other picker host leaves every `{ $record }` entry out: inline edit on a record page, a record page's header or related list, an action's parameter dialog, and a picker with no single record being edited (a bulk action over selected rows). The referenced fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['quote_date']` adds `quote_date = …` to the query over the referenced object). While the value is empty or cannot be read (the hop's row or field does not come back, no object is named for the hop, or the host has no single-row reader), the entry is left out. A `{ $record }` is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A `{ $record }` that reaches a server unresolved is refused (INVALID_FILTER), never read as null: by name, naming the field and the path, when it arrives as the eq shorthand on a column other than a date, datetime or time column; any other operator, and eq on a date, datetime or time column, is refused earlier, in generic words. The picker narrows the choice only: a rule the save must enforce belongs on the server too. | | **dependsOn** | `(string \| { field: string; param?: string })[]` | optional | Declares that this field's available values depend on the value of other field(s) on the same record — the form gates the field until they are set and re-evaluates as they change. For `lookup`/`master_detail` it scopes the candidate query (string = same local/remote key; `{field,param}` when the remote filter key differs — the `{field,param}` form is lookup-only). For `select`/`multiselect`/`radio` the actual per-option rule lives in each option's `visibleWhen`; list the referenced fields here (string form) so the option list gates and refreshes with the parent. | | **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. | | **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. | diff --git a/packages/core/src/utils/filter-tokens.test.ts b/packages/core/src/utils/filter-tokens.test.ts index 04d07031700..2914bd68120 100644 --- a/packages/core/src/utils/filter-tokens.test.ts +++ b/packages/core/src/utils/filter-tokens.test.ts @@ -259,6 +259,102 @@ describe('resolveFilterTokens — the record-context token refuses by name', () }); }); +describe('[#34199] resolveFilterTokens — an unresolved { $record } comparand refuses by name', () => { + // A FULL context, as for `{record_id}`: nothing a request carries resolves it. + const full = { now: NOW, userId: 'usr_1', orgId: 'org_9', timezone: 'UTC' }; + + function refusal(filter: unknown): { code?: string; status?: number; message: string } { + let err: unknown; + try { + resolveFilterTokens(filter, full); + } catch (e) { + err = e; + } + expect(err, 'expected a refusal').toBeInstanceOf(Error); + return err as { code?: string; status?: number; message: string }; + } + + it.each([ + // The eq shorthand is what a picker that does not resolve it sends (the card's market entry). + ['the eq shorthand', { cb_market: { $record: 'account.cb_market' } }, 'cb_market', 'account.cb_market', 'filter.cb_market'], + ['an operator comparand', { cb_market: { $eq: { $record: 'account.cb_market' } } }, 'cb_market', 'account.cb_market', 'filter.cb_market.$eq'], + ['an ordering comparand', { valid_from: { $lte: { $record: 'quote_date' } } }, 'valid_from', 'quote_date', 'filter.valid_from.$lte'], + ['inside $or beside a literal', { $or: [{ cb_market: 'export' }, { cb_market: { $record: 'account.cb_market' } }] }, 'cb_market', 'account.cb_market', 'filter.$or[1].cb_market'], + ['under $not', { $not: { cb_market: { $ne: { $record: 'account.cb_market' } } } }, 'cb_market', 'account.cb_market', 'filter.$not.cb_market.$ne'], + ['beside a string token it no longer depends on', { $and: [{ owner: '{current_user_id}' }, { cb_market: { $record: 'account.cb_market' } }] }, 'cb_market', 'account.cb_market', 'filter.$and[1].cb_market'], + // A column literally named `value` beside one named `field` is two columns, not a rule entry. + ['on a column named value beside one named field', { field: 'x', value: { $record: 'account.cb_market' } }, 'value', 'account.cb_market', 'filter.value'], + ])('%s: INVALID_FILTER / 400 naming the field, the $record path and the position', (_label, filter, field, path, at) => { + const err = refusal(filter); + expect(err.code).toBe('INVALID_FILTER'); + expect(err.status).toBe(400); + expect(err.message).toContain(`{ "$record": "${path}" }`); + expect(err.message).toContain(`on field "${field}" at ${at} reached the server unresolved`); + }); + + it('walks an or-array from its second member: an object node there is still judged', () => { + const err = refusal(['or', ['stage', '=', 'won'], { cb_market: { $record: 'account.cb_market' } }]); + expect(err.code).toBe('INVALID_FILTER'); + expect(err.status).toBe(400); + expect(err.message).toContain('on field "cb_market" at filter[2].cb_market reached'); + }); + + it('bounds the echoed $record value, which came off the wire', () => { + const err = refusal({ cb_market: { $record: 'x'.repeat(500) } }); + expect(err.code).toBe('INVALID_FILTER'); + expect(err.status).toBe(400); + expect(err.message).not.toContain('x'.repeat(60)); + expect(err.message).toContain('on field "cb_market" at filter.cb_market reached'); + }); + + it('refuses a malformed reference by its key too', () => { + const malformed = refusal({ cb_market: { $record: 'account.cb_market', addDays: 1 } }); + expect(malformed.code).toBe('INVALID_FILTER'); + expect(malformed.status).toBe(400); + expect(malformed.message).toContain('on field "cb_market" at filter.cb_market reached'); + }); + + it.each([ + // A no-`$` object beneath a field is a deep-equality comparand (or a + // nested-relation condition): the `$record` inside it is data to this pass. + ['inside a deep-equality comparand', { attachment: { meta: { $record: 'x' } } }], + ['inside a nested-relation condition', { account: { cb_market: { $record: 'account.cb_market' } } }], + // A list member: the engine's comparand-type door refuses it first, and the + // first string of the list is never read as a field name. + ['as an $in list member', { region: { $in: ['NA', 'EU', { $record: 'account.region' }] } }], + ['at the root, where no field names it', { $record: 'account.cb_market' }], + ['as the third member of a [field, op, value] tuple', ['cb_market', '=', { $record: 'account.cb_market' }]], + // The tuple's value is a comparand: the array spelling of the deep-equality + // CONTROL above is the same literal, and the analytics service hands the + // unlowered array to this pass. + ['inside a deep-equality comparand in the array spelling', ['attachment', '=', { meta: { $record: 'x' } }]], + ['inside a tuple under an and-array', ['and', ['stage', '=', 'won'], ['attachment', '=', { meta: { $record: 'x' } }]]], + ['inside a tuple of a legacy list of tuples', [['stage', '=', 'won'], ['attachment', 'in', [{ meta: { $record: 'x' } }]]]], + ])('control — %s: not a field\'s comparand, so it comes back by reference', (_label, filter) => { + expect(resolveFilterTokens(filter, full)).toBe(filter); + }); + + it('control — a filter with no placeholder still returns by reference, nested objects included', () => { + const plain = { cb_market: 'export', account: { region: 'NA' }, meta: { $eq: 'x' }, $or: [{ score: { $gt: 1 } }] }; + expect(resolveFilterTokens(plain, full)).toBe(plain); + }); + + it('control — string tokens and the $now anchor resolve as before, with `record` only as a value', () => { + expect(resolveFilterTokens({ owner: '{current_user_id}', due: { $lt: '{today}' }, note: '$record', kind: 'record' }, full)).toEqual({ + owner: 'usr_1', due: { $lt: '2026-07-15' }, note: '$record', kind: 'record', + }); + expect(resolveFilterTokens({ due: { $gte: { $now: true, addDays: -1 } } }, full)).toEqual({ + due: { $gte: { $now: NOW.toISOString(), addDays: -1 } }, + }); + }); + + it('control — a deep { $record } beside a string token is resolved around, kept as written', () => { + expect(resolveFilterTokens({ owner: '{current_user_id}', attachment: { meta: { $record: 'x' } } }, full)).toEqual({ + owner: 'usr_1', attachment: { meta: { $record: 'x' } }, + }); + }); +}); + describe('resolveFilterTokens — tree walk', () => { const ctx = { now: NOW, userId: 'usr_1', orgId: 'org_9' }; diff --git a/packages/core/src/utils/filter-tokens.ts b/packages/core/src/utils/filter-tokens.ts index 7211feb2c60..244045f6cd2 100644 --- a/packages/core/src/utils/filter-tokens.ts +++ b/packages/core/src/utils/filter-tokens.ts @@ -111,6 +111,14 @@ * to `null`, `undefined` or the literal: a count written as "about this * record" would otherwise come back as "about nobody", or, with the condition * gone, "about everybody". + * + * # A `{ $record }` comparand refuses here by name + * + * [#34199] The `lookupFilters` comparand `{ $record: 'path' }` reads the record + * a form is editing, which only that form's record picker knows. Where it IS a + * field's comparand it is refused here, `INVALID_FILTER` / 400 naming the field, + * the `$record` path and where it sits; deeper inside a comparand it is data + * and is left alone — see {@link findRecordReferenceComparand}. */ import { @@ -572,6 +580,162 @@ class MalformedNowAnchorError extends Error { } } +/** + * [#34199] `{ $record: 'path' }` — the `lookupFilters` comparand that reads the + * RECORD BEING EDITED (`LookupFilterRecordReferenceSchema`, + * `@objectstack/spec/data`): a field of that record, or one lookup hop from it + * (`account.cb_market`). Only the record picker of the form editing that + * record can resolve it — it sends the referenced value in its place before + * the query leaves the browser — and no server path knows which record a form + * is editing. The KEY decides, not the shape: a malformed reference + * (`{ $record: 1 }`, a key beside `$record`) is no more resolvable. + */ +function isRecordReference(node: unknown): node is Record { + return !!node && typeof node === 'object' && !Array.isArray(node) + && Object.prototype.hasOwnProperty.call(node, '$record'); +} + +/** A plain filter object (not a `Date`, not a branded `ReadableIds` leaf). */ +function isFilterObject(node: unknown): node is Record { + return !!node && typeof node === 'object' && !Array.isArray(node) + && !(node instanceof Date) && !isReadableIds(node); +} + +/** An operator object: a field's value carrying at least one `$` key. */ +function isOperatorObject(node: unknown): node is Record { + return isFilterObject(node) && Object.keys(node).some((k) => k.startsWith('$')); +} + +/** [#34199] A `{ $record }` met where it is a field's comparand. */ +interface RecordReferenceComparand { + readonly reference: Record; + readonly field: string; + readonly at: string; +} + +/** + * [#34199] The first `{ $record }` that IS a field's comparand, walking the + * filter's node grammar (`FilterCondition`): the field's own value (the eq + * shorthand `{ f: { $record } }`, which is what the picker's flat lowering of + * `eq` sends) or the value of an operator on that field (`{ f: { $gt: { + * $record } } }`), under any `$and` / `$or` / `$not` nesting. `at` is spelled + * from the filter's root: `filter.$or[1].cb_market`. + * + * Deliberately NOT judged — each left exactly as it was before this pass + * learned the reference: + * + * - **Inside a no-`$` object beneath a field** (`{ attachment: { meta: { + * $record: 'x' } } }`). That object is a deep-equality comparand or a + * nested-relation condition, and only the field's declaration tells the two + * apart, which this field-agnostic resolver never reads. As a deep-equality + * comparand the `$record` key is part of a literal a driver may compare + * whole (driver-memory does), so refusing it here would refuse a filter that + * answers today. + * - **A member of an operator's list** (`$in: ['NA', { $record }]`) and + * anything deeper inside an operator's value: the comparand-type door + * refuses a plain-object list member on the engine's path first. + * - **A `$` key in a node position that is not `$and` / `$or` / `$not`** + * (`{ $record: 'x' }` at the root): it is not a field's comparand, and the + * drivers already refuse an undeclared node key. + * - **A legacy `[field, op, value]` tuple** (an array whose first member is a + * string other than `and` / `or`, the split `parseFilterAST` lowers by): + * it is a comparison, not a list of nodes, and its third member is a + * comparand — `['attachment', '=', { meta: { $record: 'x' } }]` is the same + * deep-equality literal as the object spelling above, and comes back by + * reference like it. An `['and' | 'or', …]` array is walked from its second + * member, and any other array as a list of nodes. + * + * Allocation-free and shallow (it never enters a comparand), so it costs a + * read whose filter holds no reference one walk of its node keys. + */ +function findRecordReferenceComparand(node: unknown, at = 'filter'): RecordReferenceComparand | undefined { + if (Array.isArray(node)) { + let start = 0; + if (typeof node[0] === 'string') { + const head = node[0].toLowerCase(); + // A `[field, op, value]` tuple: a comparison whose value is a comparand — not judged. + if (head !== 'and' && head !== 'or') return undefined; + start = 1; + } + for (let i = start; i < node.length; i++) { + const hit = findRecordReferenceComparand(node[i], `${at}[${i}]`); + if (hit) return hit; + } + return undefined; + } + if (!isFilterObject(node)) return undefined; + for (const [key, value] of Object.entries(node)) { + if (key === '$and' || key === '$or' || key === '$not') { + const hit = findRecordReferenceComparand(value, `${at}.${key}`); + if (hit) return hit; + continue; + } + if (key.startsWith('$')) continue; + if (isRecordReference(value)) return { reference: value, field: key, at: `${at}.${key}` }; + // A no-`$` object: a deep-equality comparand or a nested-relation condition — not judged. + if (!isOperatorObject(value)) continue; + for (const [op, comparand] of Object.entries(value)) { + if (op.startsWith('$') && isRecordReference(comparand)) { + return { reference: comparand, field: key, at: `${at}.${key}.${op}` }; + } + } + } + return undefined; +} + +/** + * [#34199] An unresolved `{ $record }` met where it is a field's comparand — + * see {@link findRecordReferenceComparand}. `INVALID_FILTER` / 400, the code + * every comparand door answers with and the one the drivers answered this + * input with before; the message names the field, the `$record` path and + * where it sits. ⛔ Not `FILTER_TOKEN_UNRESOLVED`: that code's declared meaning + * is a vocabulary placeholder STRING the request carries no context for, and + * the reference is a comparand object. + * + * On the engine's object path the doors in front of this pass meet most + * operator forms first: the comparand-type door refuses any plain object + * under an operator (`{ f: { $gt: { $record } } }`), and the temporal door the + * eq shorthand on a temporal column — each in its own words. What reaches + * this pass there is the eq shorthand on any other column, and every shape + * from a caller with no such door in front. + * + * Not exported, like the module's other `INVALID_FILTER` refusals: a caller + * reads `code` and `status`. + */ +class UnresolvedRecordReferenceError extends Error { + readonly status = 400; + readonly code = 'INVALID_FILTER' satisfies StandardErrorCode; + + constructor({ reference, field, at }: RecordReferenceComparand) { + super( + `A { "$record": ${previewReferencePath(reference.$record)} } comparand on field "${field}" at ${at} ` + + 'reached the server unresolved, and is refused rather than compared. { $record } reads the record ' + + 'being edited (a field of it, or one lookup hop such as "account.cb_market"), and only the record ' + + 'picker of the form editing that record can resolve it: the picker sends the referenced value in ' + + 'its place. No server path knows which record a form is editing, so reading the reference as null, ' + + 'or comparing the object as a literal, would answer rows the filter was written to exclude. Send ' + + 'the referenced value itself, or write { $record } only in a lookup field\'s lookupFilters, where ' + + 'the picker resolves it.', + ); + this.name = 'UnresolvedRecordReferenceError'; + } +} + +/** + * [#34199] The `$record` value as the refusal echoes it: JSON, bounded to 60 + * characters like the sibling comparand doors' previews — a malformed + * reference came off the wire and can carry any JSON value. + */ +function previewReferencePath(path: unknown): string { + let text: string; + try { + text = JSON.stringify(path) ?? String(path); + } catch { + text = String(path); + } + return text.length > 60 ? `${text.slice(0, 59)}…` : text; +} + /** [#25808] The anchor with its instant pinned — see {@link isUnresolvedNowAnchor}. */ function resolveNowAnchor(node: { $now: true; addDays?: unknown }, now: Date): Record { const offset = node.addDays; @@ -607,6 +771,10 @@ export function resolveFilterTokens( ctx: FilterTokenResolutionContext = {}, ): T { if (filter == null) return filter; + // [#34199] Before the fast path: the refusal must not depend on a string + // token being in the same tree, and it reads only comparand positions. + const reference = findRecordReferenceComparand(filter); + if (reference) throw new UnresolvedRecordReferenceError(reference); if (!hasFilterToken(filter)) return filter; // One instant for the whole tree (see FilterTokenResolutionContext.now). diff --git a/packages/drivers/driver-memory/src/memory-record-reference-refusal.test.ts b/packages/drivers/driver-memory/src/memory-record-reference-refusal.test.ts new file mode 100644 index 00000000000..6e7cdf2c13a --- /dev/null +++ b/packages/drivers/driver-memory/src/memory-record-reference-refusal.test.ts @@ -0,0 +1,102 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34199] An unresolved `lookupFilters` `{ $record: 'path' }` comparand never + * reaches this driver: the engine's token pass (`resolveFilterTokens`, + * `@objectstack/core`) refuses it by name, `INVALID_FILTER` / 400, naming the + * field, the `$record` path and its position. + * + * `{ $record }` reads the record a form is editing, which only that form's + * record picker knows; a picker that does not resolve it sends the eq + * shorthand `{ cb_market: { $record: 'account.cb_market' } }` or an operator + * comparand. Measured on `origin/main` 22438726f3, this driver refused the + * shorthand itself, as an operator it does not know (`Unsupported filter + * operator "$record"`, `INVALID_FILTER` / 400); the second half below pins + * that it still does for a caller that passes no seam. The operator form + * (`{ $eq: { $record } }`) is refused through the engine by its comparand + * door before this driver is asked, so it is pinned here at the seam only. + */ + +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { resolveFilterTokens } from '@objectstack/core'; +import type { FilterCondition } from '@objectstack/spec/data'; +import { InMemoryDriver } from './memory-driver.js'; + +/** What the engine's token pass hands a driver. */ +const seamed = (where: unknown): FilterCondition => + resolveFilterTokens(where, { userId: 'usr_1' }) as FilterCondition; + +interface Refusal { code?: string; status?: number; message: string } + +describe('[#34199] InMemoryDriver — an unresolved { $record } comparand', () => { + let driver: InMemoryDriver; + + beforeEach(async () => { + driver = new InMemoryDriver({ persistence: false }); + await driver.syncSchema('price_book', { + fields: { + id: { type: 'text', name: 'id' }, + cb_market: { type: 'text', name: 'cb_market' }, + owner: { type: 'text', name: 'owner' }, + attachment: { type: 'file', name: 'attachment' }, + }, + }); + await driver.create('price_book', { id: '1', cb_market: 'export', owner: 'usr_1', attachment: { meta: { $record: 'x' } } }); + await driver.create('price_book', { id: '2', cb_market: null, owner: 'usr_2', attachment: { meta: { other: 1 } } }); + }); + + const refusalOf = async (read: () => Promise): Promise => { + try { + await read(); + } catch (e) { + return e as Refusal; + } + throw new Error('expected a refusal, but the read resolved'); + }; + + const SHAPES: ReadonlyArray = [ + ['the eq shorthand', { cb_market: { $record: 'account.cb_market' } }, 'filter.cb_market'], + ['an operator comparand', { cb_market: { $eq: { $record: 'account.cb_market' } } }, 'filter.cb_market.$eq'], + ]; + + for (const [label, where, at] of SHAPES) { + it(`${label}: refused by name at the engine's token seam, before the driver is asked`, async () => { + const find = vi.spyOn(driver, 'find'); + const err = await refusalOf(async () => driver.find('price_book', { fields: ['id'], where: seamed(where) })); + expect(err.code).toBe('INVALID_FILTER'); + expect(err.status).toBe(400); + expect(err.message).toContain('{ "$record": "account.cb_market" }'); + expect(err.message).toContain('on field "cb_market"'); + expect(err.message).toContain(`at ${at} reached the server unresolved`); + expect(find).not.toHaveBeenCalled(); + }); + } + + it('the eq shorthand: a caller that passes no seam is refused by the driver itself, never answered rows', async () => { + const err = await refusalOf(() => + driver.find('price_book', { fields: ['id'], where: { cb_market: { $record: 'account.cb_market' } } as unknown as FilterCondition })); + expect(err.code).toBe('INVALID_FILTER'); + expect(err.status).toBe(400); + }); + + it('control — a { $record } inside a deep-equality comparand reaches the driver unchanged and is answered as before', async () => { + // Not a field's comparand: the no-`$` object beneath `attachment` is a + // deep-equality literal, which this driver compares whole. The token pass + // hands it over by reference, so the driver answers exactly as it did + // before the pass learned the reference: the one row holding that value. + const where = { attachment: { meta: { $record: 'x' } } }; + const find = vi.spyOn(driver, 'find'); + const seam = seamed(where); + expect(seam).toBe(where); + const rows = (await driver.find('price_book', { fields: ['id'], where: seam })) as Array<{ id: string }>; + expect(find).toHaveBeenCalledTimes(1); + expect(rows.map((r) => String(r.id))).toEqual(['1']); + }); + + it('control — an ordinary filter and a string token run through the same seam as before', async () => { + const ids = async (where: unknown) => + ((await driver.find('price_book', { fields: ['id'], where: seamed(where) })) as Array<{ id: string }>).map((r) => String(r.id)).sort(); + expect(await ids({ cb_market: 'export' })).toEqual(['1']); + expect(await ids({ owner: '{current_user_id}' })).toEqual(['1']); + }); +}); diff --git a/packages/drivers/driver-sql/src/sql-driver-record-reference-refusal.test.ts b/packages/drivers/driver-sql/src/sql-driver-record-reference-refusal.test.ts new file mode 100644 index 00000000000..b42b0a1638c --- /dev/null +++ b/packages/drivers/driver-sql/src/sql-driver-record-reference-refusal.test.ts @@ -0,0 +1,109 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34199] An unresolved `lookupFilters` `{ $record: 'path' }` comparand never + * reaches this driver: the engine's token pass (`resolveFilterTokens`, + * `@objectstack/core`) refuses it by name, `INVALID_FILTER` / 400, naming the + * field, the `$record` path and its position. + * + * `{ $record }` reads the record a form is editing, which only that form's + * record picker knows; a picker that does not resolve it sends the eq + * shorthand `{ cb_market: { $record: 'account.cb_market' } }` or an operator + * comparand. Measured on `origin/main` 22438726f3 (SQLite, in-process), this + * driver refused both itself, in words that withheld which operator and field + * it met: "A filter operator in this filter is not one this driver evaluates" + * (shorthand) and "requires a single comparable value" (`$eq`), each + * `INVALID_FILTER` / 400. The second half below pins that it still refuses, + * so a caller that passes no seam never gets rows for it either. + */ + +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { resolveFilterTokens } from '@objectstack/core'; +import type { FilterCondition } from '@objectstack/spec/data'; +import { lowerFilterCondition } from '@objectstack/spec/data'; +import { SqlDriver } from './index.js'; + +/** What the engine hands a driver: tokens resolved, then the shared lowering. */ +const seamed = (where: unknown): FilterCondition => + lowerFilterCondition(resolveFilterTokens(where, { userId: 'usr_1' }) as FilterCondition, { isDatetimeColumn: () => false }) as FilterCondition; + +interface Refusal { code?: string; status?: number; message: string } + +describe('[#34199] SqlDriver — an unresolved { $record } comparand', () => { + let driver: SqlDriver; + + beforeEach(async () => { + driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.initObjects([ + { + name: 'price_book', + fields: { + id: { type: 'text', name: 'id' }, + cb_market: { type: 'text', name: 'cb_market' }, + owner: { type: 'text', name: 'owner' }, + attachment: { type: 'json', name: 'attachment' }, + }, + } as any, + ]); + await driver.create('price_book', { id: '1', cb_market: 'export', owner: 'usr_1' }); + await driver.create('price_book', { id: '2', cb_market: null, owner: 'usr_2' }); + }); + + const refusalOf = async (read: () => Promise): Promise => { + try { + await read(); + } catch (e) { + return e as Refusal; + } + throw new Error('expected a refusal, but the read resolved'); + }; + + const SHAPES: ReadonlyArray = [ + ['the eq shorthand', { cb_market: { $record: 'account.cb_market' } }, 'filter.cb_market'], + ['an operator comparand', { cb_market: { $eq: { $record: 'account.cb_market' } } }, 'filter.cb_market.$eq'], + ]; + + for (const [label, where, at] of SHAPES) { + it(`${label}: refused by name at the engine's token seam, before the driver is asked`, async () => { + const find = vi.spyOn(driver, 'find'); + const err = await refusalOf(async () => driver.find('price_book', { fields: ['id'], where: seamed(where) })); + expect(err.code).toBe('INVALID_FILTER'); + expect(err.status).toBe(400); + expect(err.message).toContain('{ "$record": "account.cb_market" }'); + expect(err.message).toContain('on field "cb_market"'); + expect(err.message).toContain(`at ${at} reached the server unresolved`); + expect(find).not.toHaveBeenCalled(); + }); + + it(`${label}: a caller that passes no seam is refused by the driver itself, never answered rows`, async () => { + const err = await refusalOf(() => driver.find('price_book', { fields: ['id'], where: where as FilterCondition })); + expect(err.code).toBe('INVALID_FILTER'); + expect(err.status).toBe(400); + }); + } + + it('control — a { $record } inside a deep-equality comparand reaches the driver unchanged and is answered as before', async () => { + // Not a field's comparand: the no-`$` object beneath `attachment` is a + // deep-equality literal. The token pass hands it over by reference, so + // this driver gives the answer it gave before the pass learned the + // reference, whatever that answer is. + const where = { attachment: { meta: { $record: 'x' } } }; + expect(resolveFilterTokens(where, { userId: 'usr_1' })).toBe(where); + const answer = async (w: unknown) => { + try { + return { rows: await driver.find('price_book', { fields: ['id'], where: w as FilterCondition }) }; + } catch (e) { + const { code, status } = e as Refusal; + return { code, status }; + } + }; + expect(await answer(seamed(where))).toEqual(await answer(where)); + }); + + it('control — an ordinary filter and a string token run through the same seam as before', async () => { + const ids = async (where: unknown) => + ((await driver.find('price_book', { fields: ['id'], where: seamed(where) })) as Array<{ id: string }>).map((r) => String(r.id)).sort(); + expect(await ids({ cb_market: 'export' })).toEqual(['1']); + expect(await ids({ owner: '{current_user_id}' })).toEqual(['1']); + }); +}); diff --git a/packages/spec/src/data/field.test.ts b/packages/spec/src/data/field.test.ts index 7cd14c4ef70..7437396da75 100644 --- a/packages/spec/src/data/field.test.ts +++ b/packages/spec/src/data/field.test.ts @@ -2989,14 +2989,14 @@ describe('FieldSchema.lookupFilters — { $record } comparand and orEmpty', () = } }); - it('lets the eq shorthand the picker sends through the shared door unchanged (refused later, by the driver)', () => { + it('lets the eq shorthand the picker sends through the shared door unchanged (refused later, by the engine\'s token pass)', () => { // The card's market entry: the picker lowers `eq` to the shorthand // { field: value }, so an unresolved { $record } arrives as // { cb_market: { $record } }. The door reads that object as filter - // structure and passes it through as it is; a driver then meets `$record` - // as an operator it does not know and refuses the query (INVALID_FILTER). - // A refusal by name at the door is the server follow-up's: when it lands, - // this pin turns into a refusal and moves with it. + // structure and passes it through as it is; the engine's token pass + // (`resolveFilterTokens`, `@objectstack/core`) then refuses it by name, + // INVALID_FILTER / 400 naming the field and the path, before any driver + // is asked (pinned in `packages/core/src/utils/filter-tokens.test.ts`). const shorthand = { cb_market: { $record: 'account.cb_market' } }; expect(parseFilterAST(shorthand)).toEqual(shorthand); }); diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index d52a8651c37..7a4e0c5c908 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -2262,7 +2262,8 @@ export const FieldSchema = lazySchema(() => { + '{ $now: true, addDays } comparand for a date relative to today, or a { $record: "path" } reference to the ' + 'record being edited — a field of it, or one lookup hop ("account.cb_market"); a { $record } value pairs ' + 'only with eq, ne, gt, lt, gte or lte. In a record form, whatever its layout, the picker sends the referenced ' - + 'value in place of the reference; every other picker host leaves the entry out.', + + 'value in place of the reference; every other picker host leaves the entry out. A { $record } that reaches a ' + + 'server unresolved is refused (INVALID_FILTER), never read as null.', ), orEmpty: z.boolean().optional().describe( 'TRUE: the entry also matches a candidate whose column is null — "valid from the quote date, or with no ' @@ -2280,8 +2281,10 @@ export const FieldSchema = lazySchema(() => { + '(`dependsOn: [\'quote_date\']` adds `quote_date = …` to the query over the referenced object). While the value is ' + 'empty or cannot be read (the hop\'s row or field does not come back, no object is named for the hop, or the host ' + 'has no single-row reader), the entry is left out. A { $record } is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A { $record } that reaches a ' - + 'server unresolved is refused, never read as null. The picker narrows the choice only: a rule the save must ' - + 'enforce belongs on the server too.', + + 'server unresolved is refused (INVALID_FILTER), never read as null: by name, naming the field and the path, when ' + + 'it arrives as the eq shorthand on a column other than a date, datetime or time column; any other operator, and ' + + 'eq on a date, datetime or time column, is refused earlier, in generic words. The picker narrows the choice only: ' + + 'a rule the save must enforce belongs on the server too.', ), dependsOn: z.array(z.union([z.string(), strictObject({ surface: 'this dependsOn entry',