Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .changeset/35872-shared-record-ids-sql-compile.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
'@objectstack/driver-sql': patch
'@objectstack/driver-turso': patch
'@objectstack/spec': patch
---

feat(driver-sql, driver-turso): the SQL drivers compile the `SharedRecordIds` fixed-read leaf to a subquery (ADR-0155, step 3 of 6)

Clause-②: yes
Metadata-protocol: none

No visible change on its own: nothing on main writes a `SharedRecordIds` leaf yet. The sharing plugin starts writing it at ADR-0155's last step.

- **The compile** (`@objectstack/driver-sql`). A `SharedRecordIds` leaf in a field's `$in` compiles to one subquery in the list's own position: `id IN (SELECT record_id FROM sys_record_share WHERE object_name = ? AND recipient_type = 'user' AND recipient_id = ? AND record_id IS NOT NULL AND record_id <> '')`. The write form adds `AND access_level IN (…)` inside the subquery. Every value is bound. The subquery carries no tenant scope (ADR-0155 ① ruled A), and the outer statement's tenant wall is unchanged. It compiles on every read verb and on `updateMany`, for SQLite, PostgreSQL, MySQL, SQL Server and Oracle. SQLite and PostgreSQL were run live for this release. MySQL, SQL Server and Oracle are pinned at compile shape, and MySQL also runs live in CI's Temporal Conformance job. On PostgreSQL, an object whose `id` column is not text (an integer- or uuid-keyed federated table) fails the compiled subquery with `DATABASE_ERROR` (42883) instead of answering its rows. That case is open on #35906 (ADR-0155 D-0) and is settled before the sharing plugin writes the leaf. On Oracle the `<> ''` half is left out, because Oracle stores `''` as NULL. `SqliteWasmDriver` and Turso's local mode inherit the compile.
- **The remote transport** (`@objectstack/driver-turso`). Turso's remote mode compiles the same subquery with its own compiler, from the same predicates.
- **The declaration.** `SqlDriver.supports.fixedReadLeaves` is `['SharedRecordIds']`, and `TursoDriver` inherits it in every mode. The engine's seam now hands the leaf to these drivers instead of refusing it.
- **The refusal.** A leaf anywhere other than a field's `$in` comparand is refused before any statement runs, with `INTERNAL_ERROR` / 500, and logged at `error` once per driver.
- **New exports** (`@objectstack/driver-sql`). `findMisplacedFixedReadLeaf`, `fixedInnerReadPredicates` and `misplacedFixedReadLeafMessage` are the walk, the predicates and the refusal text the two compilers share.
- **The shared case-set** (`@objectstack/spec`). `SHARED_RECORD_IDS_CASE_SET` gains a note (`n5`) on a doc whose only grant is stamped in another organization, and a nested case read under a tenant. Together they witness, in the nested position, that the inner read carries no tenant scope.
208 changes: 208 additions & 0 deletions packages/drivers/driver-sql/src/fixed-read-leaf-compile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [ADR-0155 D2, D4] What `driver-sql`'s filter compiler and the Turso remote
* transport's compiler share for a FIXED-READ LEAF (`@objectstack/spec/data`'s
* `isFixedReadLeaf`: `SharedRecordIds` today): the walk that finds a leaf no
* compiler here compiles, and the predicates of the fixed inner read the leaf
* describes. Each compiler builds its own SQL from them, every value bound,
* ⛔ never spliced into the statement.
*
* ## Where a leaf compiles
*
* Only as the comparand of `$in` in a field's operator map,
* `{ field: { $in: leaf } }`: at any depth under `$and`, `$or` and `$not`, and
* inside the composed scope of a `ReadableIds` leaf. There it compiles to
* `field IN (SELECT column FROM table WHERE …)`, one statement, so `find`,
* `count` and `aggregate` agree by construction and a record matched by several
* rows of the table is one row (ADR-0155 D1: ⛔ no `EXISTS`, no correlated
* form, no join).
*
* Anywhere else (under another operator, as a field's bare value, as a list
* member, as a combinator's operand, as a node) the leaf is a composition
* fault, refused with ADR-0139 D3's envelope, `INTERNAL_ERROR` / 500
* (`@objectstack/core`'s `refuseFixedReadLeafOnce`). ⛔ It is never read as an
* ordinary comparand. The engine's seam places every leaf (ADR-0155 D1, D4);
* this walk is the compiler's own floor under that seam, for a caller that
* reached the driver another way.
*
* ## The inner read
*
* {@link fixedInnerReadPredicates} turns the leaf's own description
* (`fixedInnerReadOf`) into predicates, so ⛔ no compiler restates a leaf's
* predicate by hand:
*
* - each `equals` entry as `column = ?`, each `memberOf` entry as
* `column IN (?, …)`;
* - the blank-id guard, `column IS NOT NULL AND column <> ''`, so a negation
* (`NOT (id IN (…))`) answers every row the set does not hold. On a dialect
* that stores the empty string as NULL (Oracle) `<> ''` is `<> NULL`, which
* is never true and would empty the set, so the half is omitted there:
* `IS NOT NULL` already excludes the empty id;
* - **no tenant scope** (`tenantScope: 'none'`, ADR-0155 ① ruled A): ⛔ the
* compiler applies none to the inner read. The outer statement's wall is
* untouched.
*
* `index.ts` re-exports this module for `@objectstack/driver-turso`.
*/

import { describeFixedReadLeaf } from '@objectstack/core';
import { fixedInnerReadOf, isComposedReadableIds, isFixedReadLeaf } from '@objectstack/spec/data';
import type { FixedInnerRead, FixedReadLeaf } from '@objectstack/spec/data';

/** A fixed-read leaf the walk found where no compiler compiles one. */
export interface MisplacedFixedReadLeaf {
/** Where it sits, as a path from the `where` root (`where.owner.$eq`). */
readonly at: string;
/** The leaf itself, for `describeFixedReadLeaf`. */
readonly leaf: unknown;
}

/** Is `value` a plain object or a list: something a filter is built from and the walk descends into? */
function isPlainContainer(value: unknown): value is Record<string, unknown> | unknown[] {
if (value === null || typeof value !== 'object') return false;
if (Array.isArray(value)) return true;
const proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}

/**
* [ADR-0155 D1] The first fixed-read leaf in `where` that sits anywhere but as
* the `$in` comparand of a field's operator map, or `null` when every leaf
* sits there (or there is none).
*
* The walk reads roles, not just keys: a NODE's keys are combinators and field
* names, an OPERATOR MAP's keys are operators, and only an operator map's `$in`
* holds a leaf. A composed `ReadableIds` leaf's scope is a node, walked with
* the same rules, and so is the scope of any value `scopeOf` answers for (a
* compiler's own resolved form of that leaf, such as the Turso remote
* transport's semi-join). A value that is neither a plain object nor a list (a
* `Date`, a buffer) holds no leaf. Cycles are cut on the current path.
*/
export function findMisplacedFixedReadLeaf(
where: unknown,
path = 'where',
scopeOf: (value: unknown) => { readonly scope: unknown } | null = () => null,
): MisplacedFixedReadLeaf | null {
const onPath = new Set<object>();
const descend = <T>(value: object, walk: () => T): T | null => {
if (onPath.has(value)) return null;
onPath.add(value);
try {
return walk();
} finally {
onPath.delete(value);
}
};
/** Any value outside the two roles: a leaf here is misplaced, a composed `ReadableIds` scope is a node. */
const visitValue = (value: unknown, at: string): MisplacedFixedReadLeaf | null => {
if (isFixedReadLeaf(value)) return { at, leaf: value };
const nested = isComposedReadableIds(value) ? value : scopeOf(value);
if (nested !== null) return nested.scope === undefined ? null : visitNode(nested.scope, `${at}.scope`);
if (!isPlainContainer(value)) return null;
return descend(value, () => {
const entries: [string, unknown][] = Array.isArray(value)
? value.map((item, i) => [`[${i}]`, item])
: Object.keys(value).map((key) => [`.${key}`, value[key]]);
for (const [step, item] of entries) {
const found = visitValue(item, `${at}${step}`);
if (found) return found;
}
return null;
});
};
/** A filter node: `$and` / `$or` list members and `$not`'s operand are nodes, a field's value is an operator map. */
const visitNode = (node: unknown, at: string): MisplacedFixedReadLeaf | null => {
if (isFixedReadLeaf(node) || !isPlainContainer(node) || Array.isArray(node)) return visitValue(node, at);
return descend(node, () => {
for (const key of Object.keys(node)) {
const value = node[key];
const here = `${at}.${key}`;
let found: MisplacedFixedReadLeaf | null;
if ((key === '$and' || key === '$or') && Array.isArray(value)) {
found = null;
for (let i = 0; i < value.length && found === null; i++) found = visitNode(value[i], `${here}[${i}]`);
} else if (key === '$not') {
found = visitNode(value, here);
} else if (!key.startsWith('$') && !isFixedReadLeaf(value) && isPlainContainer(value) && !Array.isArray(value)) {
found = visitOperatorMap(value, here);
} else {
found = visitValue(value, here);
}
if (found) return found;
}
return null;
});
};
/** A field's operator map: its `$in` is the one place a leaf compiles. */
const visitOperatorMap = (map: Record<string, unknown>, at: string): MisplacedFixedReadLeaf | null =>
descend(map, () => {
for (const op of Object.keys(map)) {
const comparand = map[op];
if (op === '$in' && isFixedReadLeaf(comparand)) continue;
const found = visitValue(comparand, `${at}.${op}`);
if (found) return found;
}
return null;
});
return visitNode(where, path);
}

/**
* The refusal's message for a leaf {@link findMisplacedFixedReadLeaf} found:
* where it sits, what it is (by name and table, never its inputs: a recipient
* is a principal's id, and the message reaches logs), and the one position it
* compiles in.
*/
export function misplacedFixedReadLeafMessage(found: MisplacedFixedReadLeaf): string {
return `${describeFixedReadLeaf(found.at, found.leaf)}, where no filter compiler compiles one: a fixed-read leaf `
+ 'compiles only as the $in comparand of a field, the position the engine\'s seam places it in (ADR-0155 D1). '
+ 'The statement was NOT run, rather than read the leaf as an ordinary comparand. Place it as '
+ '{ id: { $in: leaf } }, directly or inside a composed ReadableIds scope.';
}

/** The predicates of a fixed inner read, in the order a compiler emits them. */
export interface FixedInnerReadPredicates {
/** The one table the read is of. */
readonly table: string;
/** The one column it projects, and the column the blank-id guard reads. */
readonly column: string;
/** `column = value`, ANDed. */
readonly equals: readonly (readonly [column: string, value: string])[];
/** `column IN (values…)`, ANDed; every list is non-empty. */
readonly memberOf: readonly (readonly [column: string, values: readonly string[]])[];
/**
* Whether the blank-id guard carries its `<> ''` half. Always true but where
* the dialect stores the empty string as NULL, where `IS NOT NULL` is the
* whole guard.
*/
readonly notEmpty: boolean;
}

/**
* [ADR-0155 D2, D4] The predicates of the fixed inner read `leaf` denotes,
* from its own description (`fixedInnerReadOf`).
*
* The description's tenant scope is a literal type: a leaf whose record ever
* rules a scope other than `'none'` widens it and stops this function from
* compiling until every compiler answers the new value.
*
* @param emptyStringIsNull the dialect stores `''` as NULL (Oracle).
* @throws TypeError when `leaf` is not a fixed-read leaf (`fixedInnerReadOf`).
*/
export function fixedInnerReadPredicates(
leaf: FixedReadLeaf,
{ emptyStringIsNull }: { readonly emptyStringIsNull: boolean },
): FixedInnerReadPredicates {
const read: FixedInnerRead = fixedInnerReadOf(leaf);
// ADR-0155 ① ruled A: no tenant scope on the inner read. A widened type fails here.
const tenantScope: 'none' = read.tenantScope;
void tenantScope;
return Object.freeze({
table: read.table,
column: read.column,
equals: Object.freeze(Object.entries(read.equals)),
memberOf: Object.freeze(Object.entries(read.memberOf)),
notEmpty: !emptyStringIsNull,
});
}
5 changes: 5 additions & 0 deletions packages/drivers/driver-sql/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ export { recoverUnencodedJsonText } from './unencoded-json-text.js';
// face compiles SQL text with its own compiler, and must regroup by the same
// rule the knex path does.
export { FLAT_GROUP_MAX_MEMBERS, joinBalancedGroup } from './sql-driver-balanced-group.js';
// [ADR-0155 D2, D4] Where a fixed-read leaf compiles and the predicates of its
// fixed inner read. Exported because the Turso remote face compiles the leaf
// with its own compiler, from the same walk and the same predicates.
export { findMisplacedFixedReadLeaf, fixedInnerReadPredicates, misplacedFixedReadLeafMessage } from './fixed-read-leaf-compile.js';
export type { FixedInnerReadPredicates, MisplacedFixedReadLeaf } from './fixed-read-leaf-compile.js';
// [cloud#3652 D3] The declared-rename refusal the sync throws before any DDL,
// and its renderer, so a host reporting a refused sync (the install door, `os
// migrate apply`) reads the structured refusals rather than parsing the text;
Expand Down
28 changes: 24 additions & 4 deletions packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,13 @@
* evaluation cycle. `index.ts` re-exports nothing from this module.
*/

import { isComposedReadableIds, resolveFilterSubtreeProvenance } from '@objectstack/spec/data';
import { isComposedReadableIds, isFixedReadLeaf, resolveFilterSubtreeProvenance } from '@objectstack/spec/data';
import type { DriverOptions, ValueShapeFieldDef } from '@objectstack/spec/data';
import { JSON_COLUMN_INCOMPATIBLE_OPERATORS, findMisplacedReadableIds, presentAsNumber, refuseReadableIdsOnce, temporalStorageForm } from '@objectstack/core';
import { JSON_COLUMN_INCOMPATIBLE_OPERATORS, findMisplacedReadableIds, presentAsNumber, refuseFixedReadLeafOnce, refuseReadableIdsOnce, temporalStorageForm } from '@objectstack/core';
import type { JsonColumnFieldClass } from '@objectstack/core';
import { StorageNameMapping } from '@objectstack/spec/system';
import { emitBalancedGroup } from './sql-driver-balanced-group.js';
import { findMisplacedFixedReadLeaf, misplacedFixedReadLeafMessage } from './fixed-read-leaf-compile.js';
import { presentStoredBoolean, sqliteBooleanBinding } from './sql-driver-sqlite-serialisation.js';
import type { Knex } from 'knex';
import {
Expand Down Expand Up @@ -101,6 +102,8 @@ export interface FilterHelpersHost {
readonly dateFieldsOnInstantColumn: SqlDriver['dateFieldsOnInstantColumn'];
readonly datetimeFields: SqlDriver['datetimeFields'];
filterColumnExpr: SqlDriver['filterColumnExpr'];
readonly fixedReadLeafRefusalLog: SqlDriver['fixedReadLeafRefusalLog'];
fixedReadLeafSubquery: SqlDriver['fixedReadLeafSubquery'];
isJsonColumn: SqlDriver['isJsonColumn'];
readonly isMssql: SqlDriver['isMssql'];
readonly isMysql: SqlDriver['isMysql'];
Expand Down Expand Up @@ -524,13 +527,20 @@ export class FilterHelpersFacet {
}

/** The body of `SqlDriver#applyFilters`; the method's docblock there is its contract. */
static applyFilters(this: Pick<FilterHelpersHost, 'compileFilters' | 'logger' | 'readableIdsDriverName' | 'readableIdsRefusalLog' | 'resolveWithheldFilterRefusal'>, builder: Knex.QueryBuilder, filters: any, options?: DriverOptions) {
static applyFilters(this: Pick<FilterHelpersHost, 'compileFilters' | 'fixedReadLeafRefusalLog' | 'logger' | 'readableIdsDriverName' | 'readableIdsRefusalLog' | 'resolveWithheldFilterRefusal'>, builder: Knex.QueryBuilder, filters: any, options?: DriverOptions) {
// [ADR-0139 D3] A `ReadableIds` leaf this compiler will not evaluate — an
// UNCOMPOSED one anywhere, a composed one outside a `$in` comparand — is
// refused before anything compiles: INTERNAL_ERROR / 500, logged at
// `error` once per driver. ⛔ Never evaluated as "no restriction".
const misplaced = findMisplacedReadableIds(filters, true);
if (misplaced) throw refuseReadableIdsOnce(this.readableIdsDriverName, misplaced, this.logger, this.readableIdsRefusalLog);
// [ADR-0155 D1, D4] Likewise a fixed-read leaf anywhere but as a field's
// `$in` comparand, the one position `applyFilterCondition` compiles it in:
// the same envelope, logged once per driver on its own flag.
const misplacedLeaf = findMisplacedFixedReadLeaf(filters);
if (misplacedLeaf) {
throw refuseFixedReadLeafOnce(this.readableIdsDriverName, misplacedFixedReadLeafMessage(misplacedLeaf), this.logger, this.fixedReadLeafRefusalLog);
}
try {
this.compileFilters(builder, filters, options);
} catch (err) {
Expand Down Expand Up @@ -697,7 +707,7 @@ export class FilterHelpersFacet {
}

/** The body of `SqlDriver#applyFilterCondition`; the method's docblock there is its contract. */
static applyFilterCondition(this: Pick<FilterHelpersHost, 'applyContainsLike' | 'applyCrossFieldComparison' | 'applyEmptyOperator' | 'applyFalseConstant' | 'applyFilterCondition' | 'applyJsonMembership' | 'applyLike' | 'applyLikePattern' | 'applyNormalizedComparison' | 'applyNowAnchorComparison' | 'applyNullSafeNegative' | 'applyTextOperatorOverNonTextColumn' | 'assertOperatorAppliesToColumn' | 'coerceFilterValue' | 'coercionKey' | 'filterColumnExpr' | 'isJsonColumn' | 'isMssql' | 'isNonTextColumn' | 'isOracle' | 'mapSortField' | 'mssqlGuidColumnsByObject' | 'oracleRawUuidFieldsByObject' | 'readableIdsSubquery' | 'remoteColumn' | 'withWithheldFilterLog'>,
static applyFilterCondition(this: Pick<FilterHelpersHost, 'applyContainsLike' | 'applyCrossFieldComparison' | 'applyEmptyOperator' | 'applyFalseConstant' | 'applyFilterCondition' | 'applyJsonMembership' | 'applyLike' | 'applyLikePattern' | 'applyNormalizedComparison' | 'applyNowAnchorComparison' | 'applyNullSafeNegative' | 'applyTextOperatorOverNonTextColumn' | 'assertOperatorAppliesToColumn' | 'coerceFilterValue' | 'coercionKey' | 'filterColumnExpr' | 'isJsonColumn' | 'isMssql' | 'isNonTextColumn' | 'isOracle' | 'mapSortField' | 'mssqlGuidColumnsByObject' | 'oracleRawUuidFieldsByObject' | 'readableIdsSubquery' | 'remoteColumn' | 'withWithheldFilterLog' | 'fixedReadLeafSubquery'>,
builder: Knex.QueryBuilder,
condition: any,
logicalOp: 'and' | 'or' = 'and',
Expand Down Expand Up @@ -845,6 +855,16 @@ export class FilterHelpersFacet {
(builder as any)[mIn](field, this.readableIdsSubquery(opValue, options));
continue;
}
// [ADR-0155 D2, D4] A fixed-read leaf, the other non-list a `$in` may
// hold, compiles to its fixed inner read in the list's own position,
// `field IN (SELECT …)` (`SqlDriver#fixedReadLeafSubquery`), under the
// outer statement's own wall and nothing else. `applyFilters` refused
// it at every other position.
if (rawOp === '$in' && isFixedReadLeaf(opValue)) {
const mIn = logicalOp === 'or' ? 'orWhereIn' : 'whereIn';
(builder as any)[mIn](field, this.fixedReadLeafSubquery(opValue));
continue;
}
// #5222 — a `{ $field }` that is the WHOLE comparand of a scalar
// comparison compiles to a same-table column-to-column comparison
// (or refuses inside the emitter, with the specific boundary named).
Expand Down
Loading
Loading