From 81da4a8ba672e21652eda042dc6e6d8c5a6b0ca2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 14:31:37 +0000 Subject: [PATCH 1/4] fix(driver-sql): split a long $in/$nin list on Oracle, refuse one past SQL Server's parameter ceiling Claude-Session: https://claude.ai/code/session_01Utp6CaJjkQx5fPE4Fbmoeq Co-authored-by: Claude --- .../src/sql-driver-filter-helpers.ts | 10 +- .../src/sql-driver-in-list-ceiling.ts | 114 ++++++++++++++++++ 2 files changed, 121 insertions(+), 3 deletions(-) create mode 100644 packages/drivers/driver-sql/src/sql-driver-in-list-ceiling.ts diff --git a/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts b/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts index 4f7a57e2865..014d2ce4ebc 100644 --- a/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts +++ b/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts @@ -45,6 +45,7 @@ import { JSON_COLUMN_INCOMPATIBLE_OPERATORS, findMisplacedReadableIds, presentAs import type { JsonColumnFieldClass } from '@objectstack/core'; import { StorageNameMapping } from '@objectstack/spec/system'; import { emitBalancedGroup } from './sql-driver-balanced-group.js'; +import { assertInListWithinRequestCeiling, emitInList, emitNotInValueTest } from './sql-driver-in-list-ceiling.js'; import { findMisplacedFixedReadLeaf, misplacedFixedReadLeafMessage } from './fixed-read-leaf-compile.js'; import { presentStoredBoolean, sqliteBooleanBinding } from './sql-driver-sqlite-serialisation.js'; import type { Knex } from 'knex'; @@ -999,15 +1000,18 @@ export class FilterHelpersFacet { (builder as any)[method](field, '<=', coerced); break; case '$in': { - const mIn = logicalOp === 'or' ? 'orWhereIn' : 'whereIn'; - (builder as any)[mIn](field, coerced as any[]); + // [#39312] Within the dialect's list ceilings: split on Oracle, + // refused past SQL Server's request ceiling (sql-driver-in-list-ceiling.ts). + assertInListWithinRequestCeiling(this, op, field, coerced, refusalSubtree(value, condition)); + emitInList(builder, logicalOp, field, coerced, this); break; } case '$nin': { + assertInListWithinRequestCeiling(this, op, field, coerced, refusalSubtree(value, condition)); // [#5298] NULL-safe: "not among this list" holds vacuously for a // value that is not there, which is what every JS backend answers. this.applyNullSafeNegative(builder, method, field, (qb) => - qb.orWhereNotIn(field, coerced as any[]), + emitNotInValueTest(qb, field, coerced, this), ); break; } diff --git a/packages/drivers/driver-sql/src/sql-driver-in-list-ceiling.ts b/packages/drivers/driver-sql/src/sql-driver-in-list-ceiling.ts new file mode 100644 index 00000000000..ae26d5392df --- /dev/null +++ b/packages/drivers/driver-sql/src/sql-driver-in-list-ceiling.ts @@ -0,0 +1,114 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#39312] A literal `$in` / `$nin` list, emitted within the two dialect + * ceilings a long list meets. + * + * ## The two ceilings + * + * - **Oracle** refuses an IN list of more than {@link ORACLE_IN_LIST_MAX_ITEMS} + * expressions (ORA-01795). The ceiling is per list, not per statement, so a + * longer list is emitted as several lists of at most that many members: + * `$in` as their disjunction, `(col IN (…) OR col IN (…))`, and `$nin` as + * their conjunction, `(col NOT IN (…) AND col NOT IN (…))`. Both are the same + * set test as the one long list under SQL's three-valued logic, member for + * member, so the answer is the one the unsplit list gives on every other + * dialect. + * - **SQL Server** refuses a request carrying more than + * {@link MSSQL_MAX_REQUEST_PARAMETERS} parameters. That ceiling is per + * request, so splitting the list changes nothing: every member is still a + * parameter of the one statement. A list whose members alone exceed it can + * never run, and is refused before any statement is built — + * `INVALID_FILTER` / 400, naming the ceiling — rather than reaching the + * server and coming back as its own error. A statement whose lists each fit + * but whose parameters together exceed the ceiling still reaches the server + * and is answered by its error: this module sees one list, not the statement. + * + * ## What stays as it was + * + * Every other dialect, and every list within the ceiling, is emitted exactly as + * before: one `whereIn` / `whereNotIn`, byte-identical SQL. Neither ceiling was + * measured against a live server here; both are the vendors' documented limits. + */ + +import { withheldFilterError } from './sql-driver-top-level.js'; + +/** The most expressions Oracle accepts in one IN list (ORA-01795). */ +export const ORACLE_IN_LIST_MAX_ITEMS = 1_000; + +/** The most parameters SQL Server accepts in one request. */ +export const MSSQL_MAX_REQUEST_PARAMETERS = 2_100; + +/** Which of the two ceilings applies to the datasource compiling the list. */ +export interface InListDialect { + readonly isOracle: boolean; + readonly isMssql: boolean; +} + +/** `list` cut into consecutive runs of at most `size` members, in order. */ +function chunksOf(list: readonly unknown[], size: number): unknown[][] { + const out: unknown[][] = []; + for (let i = 0; i < list.length; i += size) out.push(list.slice(i, i + size)); + return out; +} + +/** Whether `list` is longer than one Oracle IN list may be on this datasource. */ +function splitsOnOracle(dialect: InListDialect, list: unknown): list is unknown[] { + return dialect.isOracle && Array.isArray(list) && list.length > ORACLE_IN_LIST_MAX_ITEMS; +} + +/** + * Refuse a `$in` / `$nin` list that cannot fit in one SQL Server request. + * A no-op on every other dialect and for every list within the ceiling. + * `subtree` is the node the refusal is resolved against (author-written or not). + */ +export function assertInListWithinRequestCeiling( + dialect: InListDialect, + operator: '$in' | '$nin', + field: string, + list: unknown, + subtree?: unknown, +): void { + if (!dialect.isMssql || !Array.isArray(list) || list.length <= MSSQL_MAX_REQUEST_PARAMETERS) return; + const why = + `a list of ${list.length} values, and SQL Server accepts at most ` + + `${MSSQL_MAX_REQUEST_PARAMETERS.toLocaleString('en-US')} parameters in one request, so the statement can ` + + 'never run. Read the records in batches of a shorter list, or narrow the filter.'; + throw withheldFilterError( + `This filter's "${operator}" names ${why} The field is withheld from the message; the full diagnostic is in ` + + 'the server log.', + `Field "${field}" "${operator}" names ${why}`, + subtree, + ); +} + +/** + * Emit `field IN (list)` into `builder`, attached by `logicalOp`: one `whereIn`, + * or on Oracle above {@link ORACLE_IN_LIST_MAX_ITEMS} members a parenthesised + * disjunction of lists that each fit. + */ +export function emitInList(builder: any, logicalOp: 'and' | 'or', field: string, list: unknown, dialect: InListDialect): void { + if (!splitsOnOracle(dialect, list)) { + builder[logicalOp === 'or' ? 'orWhereIn' : 'whereIn'](field, list); + return; + } + builder[logicalOp === 'or' ? 'orWhere' : 'where']((qb: any) => { + for (const chunk of chunksOf(list, ORACLE_IN_LIST_MAX_ITEMS)) qb.orWhereIn(field, chunk); + }); +} + +/** + * Emit the value test of `field NOT IN (list)`, OR-attached to `qb` — the + * callback {@link SqlDriver.applyNullSafeNegative} hands its group: one + * `orWhereNotIn`, or on Oracle above {@link ORACLE_IN_LIST_MAX_ITEMS} members a + * parenthesised conjunction of lists that each fit. + */ +export function emitNotInValueTest(qb: any, field: string, list: unknown, dialect: InListDialect): void { + if (!splitsOnOracle(dialect, list)) { + qb.orWhereNotIn(field, list); + return; + } + qb.orWhere((inner: any) => { + for (const chunk of chunksOf(list, ORACLE_IN_LIST_MAX_ITEMS)) inner.whereNotIn(field, chunk); + }); +} From 7fb172ca73202a60091e7a1ab02855b36b2a0bcc Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 14:38:12 +0000 Subject: [PATCH 2/4] test(driver-sql): pin the $in/$nin dialect list ceilings Claude-Session: https://claude.ai/code/session_01Utp6CaJjkQx5fPE4Fbmoeq Co-authored-by: Claude --- ...iver-39312-in-list-dialect-ceiling.test.ts | 170 ++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 packages/drivers/driver-sql/src/sql-driver-39312-in-list-dialect-ceiling.test.ts diff --git a/packages/drivers/driver-sql/src/sql-driver-39312-in-list-dialect-ceiling.test.ts b/packages/drivers/driver-sql/src/sql-driver-39312-in-list-dialect-ceiling.test.ts new file mode 100644 index 00000000000..7def169f7d8 --- /dev/null +++ b/packages/drivers/driver-sql/src/sql-driver-39312-in-list-dialect-ceiling.test.ts @@ -0,0 +1,170 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#39312] A literal `$in` / `$nin` list within the dialect ceilings it meets + * (`sql-driver-in-list-ceiling.ts`). + * + * Oracle refuses an IN list of more than 1,000 expressions (ORA-01795) and SQL + * Server a request of more than 2,100 parameters. Neither server runs here: the + * Oracle and SQL Server halves are read from `toSQL()` through each dialect's + * own knex client, offline, and the split shape's ANSWER is measured on a real + * SQLite database, which evaluates the same `IN` / `NOT IN` / `OR` / `AND` + * under the same three-valued logic. + */ + +import { describe, expect, it } from 'vitest'; +import knex, { type Knex } from 'knex'; +import { ReadableIds, type FilterCondition } from '@objectstack/spec/data'; +import { SqlDriver, type SqlDriverConfig } from './sql-driver.js'; +import { emitInList, emitNotInValueTest, MSSQL_MAX_REQUEST_PARAMETERS, ORACLE_IN_LIST_MAX_ITEMS } from './sql-driver-in-list-ceiling.js'; + +class CompileProbe extends SqlDriver { + constructor(config: Record, parents: readonly string[] = []) { + super({ ...config, schemaMode: 'external' } as unknown as SqlDriverConfig); + this.registerExternalObject({ name: 't', fields: { name: { type: 'text' }, owner_id: { type: 'text' } }, external: { remoteName: 't' } } as any); + for (const p of parents) { + this.registerExternalObject({ name: p, fields: { owner_id: { type: 'text' } }, external: { remoteName: p } } as any); + } + } + compileWhere(where: FilterCondition): { sql: string; bindings: readonly unknown[] } { + const builder: Knex.QueryBuilder = this.getKnex()('t'); + this.applyFilters(builder, where); + const native = builder.toSQL().toNative(); + return { sql: native.sql, bindings: native.bindings }; + } +} + +const ORACLE = { client: 'oracledb', connection: { user: 'nobody', password: 'unused', connectString: '127.0.0.1:1/NONE' } }; +const MSSQL = { client: 'mssql', connection: {} }; +const PG = { client: 'pg', connection: {} }; +const MYSQL = { client: 'mysql2', connection: {} }; +const SQLITE = { client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }; + +const ids = (n: number): string[] => Array.from({ length: n }, (_, i) => `r${i}`); +/** The member counts of every IN / NOT IN list in `sql`, in order. */ +const listSizes = (sql: string): number[] => + [...sql.matchAll(/ (?:not )?in \(([^()]*)\)/g)].map((m) => m[1]!.split(',').length); + +describe('[#39312] Oracle: a list longer than one IN list may be is split into lists that each fit', () => { + it('a $in of 2,500 ids compiles to an OR of three lists of at most 1,000, binding every id once, in order', () => { + const { sql, bindings } = new CompileProbe(ORACLE).compileWhere({ name: { $in: ids(2_500) } }); + expect(listSizes(sql)).toEqual([1_000, 1_000, 500]); + expect(sql).toMatch(/^select \* from "t" where \("name" in \(.*\) or "name" in \(.*\) or "name" in \(.*\)\)$/); + expect(bindings).toEqual(ids(2_500)); + }); + + it('a $nin of 2,500 ids compiles to the NULL-safe arm over an AND of three lists of at most 1,000', () => { + const { sql, bindings } = new CompileProbe(ORACLE).compileWhere({ name: { $nin: ids(2_500) } }); + expect(listSizes(sql)).toEqual([1_000, 1_000, 500]); + expect(sql).toMatch(/^select \* from "t" where \("name" is null or \("name" not in \(.*\) and "name" not in \(.*\) and "name" not in \(.*\)\)\)$/); + expect(bindings).toEqual(ids(2_500)); + }); + + it('a split $in under $or stays one disjunct of the $or', () => { + const { sql } = new CompileProbe(ORACLE).compileWhere({ $or: [{ owner_id: 'u1' }, { name: { $in: ids(1_001) } }] }); + expect(listSizes(sql)).toEqual([1_000, 1]); + expect(sql).toMatch(/^select \* from "t" where \(\("owner_id" = :1\) or \(\("name" in \(.*\) or "name" in \(:1002\)\)\)\)$/); + }); + + it('a list of exactly 1,000 is one list, as before', () => { + expect(listSizes(new CompileProbe(ORACLE).compileWhere({ name: { $in: ids(ORACLE_IN_LIST_MAX_ITEMS) } }).sql)).toEqual([1_000]); + }); +}); + +describe('[#39312] SQL Server: a list that alone exceeds the request ceiling is refused, naming it', () => { + const refusal = (where: FilterCondition): (Error & { code?: string; status?: number }) | undefined => { + try { + new CompileProbe(MSSQL).compileWhere(where); + } catch (e) { + return e as Error & { code?: string; status?: number }; + } + return undefined; + }; + + for (const op of ['$in', '$nin'] as const) { + it(`${op} of 2,101 values: INVALID_FILTER / 400, the message naming the 2,100-parameter ceiling`, () => { + const err = refusal({ name: { [op]: ids(MSSQL_MAX_REQUEST_PARAMETERS + 1) } } as FilterCondition); + expect(err?.code).toBe('INVALID_FILTER'); + expect(err?.status).toBe(400); + expect(err?.message).toMatch(/^This filter's "\$n?in" names a list of 2101 values, and SQL Server accepts at most 2,100 parameters in one request, so the statement can never run\./); + }); + } + + it('a list of 2,100 compiles as one list; SQL Server is never split', () => { + const { sql, bindings } = new CompileProbe(MSSQL).compileWhere({ name: { $in: ids(MSSQL_MAX_REQUEST_PARAMETERS) } }); + expect(listSizes(sql)).toEqual([2_100]); + expect(bindings).toHaveLength(2_100); + }); + + it('measured: the comment thread gate binds 1 + s parameters per parent object (s = its composed scope\'s own)', () => { + // The gate's leaf: one `{ object_name: P, record_id: { $in: ReadableIds.compose(of(P), scope) } }` + // branch per registered parent object, ORed. Measured with a one-binding owner scope; + // `name` stands in for `object_name`, `owner_id` for `record_id`. + const parents = Array.from({ length: 120 }, (_, i) => `p${i}`); + const branch = (p: string) => ({ + name: p, + owner_id: { $in: ReadableIds.compose(ReadableIds.of(p), { owner_id: 'u1' }) }, + }); + const { bindings } = new CompileProbe(MSSQL, parents).compileWhere({ $or: parents.map(branch) } as unknown as FilterCondition); + expect(bindings).toHaveLength(120 * 2); + }); +}); + +describe('[#39312] every other dialect, and every list within the ceiling, compiles byte-identically', () => { + const plain = (config: Record, op: 'in' | 'nin', n: number): string => { + const k = knex(config as Knex.Config); + const b = k('t'); + if (op === 'in') b.whereIn('name', ids(n)); + else b.where((qb) => { qb.whereNull('name'); qb.orWhereNotIn('name', ids(n)); }); + const sql = b.toSQL().toNative().sql; + void k.destroy(); + return sql; + }; + const cases: Array<[string, Record, number]> = [ + ['sqlite', SQLITE, 2_500], ['postgres', PG, 2_500], ['mysql', MYSQL, 2_500], + ['mssql', MSSQL, 2_100], ['oracle within the list ceiling', ORACLE, 1_000], + ]; + for (const [name, config, n] of cases) { + it(`${name}: $in and $nin of ${n}`, () => { + const d = new CompileProbe(config); + expect(d.compileWhere({ name: { $in: ids(n) } }).sql).toBe(plain(config, 'in', n)); + expect(d.compileWhere({ name: { $nin: ids(n) } }).sql).toBe(plain(config, 'nin', n)); + }); + } +}); + +describe('[#39312] the split shape answers what the one long list answers (measured on SQLite)', () => { + const SPLIT = { isOracle: true, isMssql: false } as const; + const ROWS = 3_000; + const withTable = async (run: (k: Knex) => Promise): Promise => { + const k = knex(SQLITE as Knex.Config); + try { + await k.schema.createTable('t', (tb) => { tb.integer('n'); tb.string('k').nullable(); }); + // Every seventh row has no value: `$nin` holds vacuously for it (the NULL-safe arm). + const rows = Array.from({ length: ROWS }, (_, n) => ({ n, k: n % 7 === 0 ? null : `r${n}` })); + for (let i = 0; i < rows.length; i += 200) await k('t').insert(rows.slice(i, i + 200)); + await run(k); + } finally { + await k.destroy(); + } + }; + const answer = async (q: Knex.QueryBuilder): Promise => (await q.select('n').orderBy('n')).map((r: { n: number }) => r.n); + // 2,400 members, every third id plus ids no row holds — three lists once split. + const list = [...ids(ROWS).filter((_, i) => i % 3 !== 0).slice(0, 1_900), ...Array.from({ length: 500 }, (_, i) => `absent${i}`)]; + + it('$in', async () => { + await withTable(async (k) => { + const split = await answer(k('t').where((qb) => emitInList(qb, 'and', 'k', list, SPLIT))); + expect(split).toEqual(await answer(k('t').whereIn('k', list))); + expect(split.length).toBe(list.filter((v) => v.startsWith('r') && Number(v.slice(1)) % 7 !== 0).length); + }); + }); + + it('$nin, NULL-safe', async () => { + await withTable(async (k) => { + const split = await answer(k('t').where((qb) => { qb.whereNull('k'); emitNotInValueTest(qb, 'k', list, SPLIT); })); + expect(split).toEqual(await answer(k('t').where((qb) => { qb.whereNull('k'); qb.orWhereNotIn('k', list); }))); + expect(split.length).toBeGreaterThan(0); + }); + }); +}); From ca39fab3eaf78ea07a2d800131e302b8fe95f4d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 14:38:41 +0000 Subject: [PATCH 3/4] chore(changeset): driver-sql $in list dialect ceilings Claude-Session: https://claude.ai/code/session_01Utp6CaJjkQx5fPE4Fbmoeq Co-authored-by: Claude --- .changeset/39312-driver-sql-in-list-ceiling.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .changeset/39312-driver-sql-in-list-ceiling.md diff --git a/.changeset/39312-driver-sql-in-list-ceiling.md b/.changeset/39312-driver-sql-in-list-ceiling.md new file mode 100644 index 00000000000..471c6cd6652 --- /dev/null +++ b/.changeset/39312-driver-sql-in-list-ceiling.md @@ -0,0 +1,14 @@ +--- +'@objectstack/driver-sql': patch +--- + +fix(driver-sql): a `$in` / `$nin` of more than 1,000 values runs on Oracle, and one past SQL Server's 2,100-parameter ceiling is refused by name + +Clause-②: no +Metadata-protocol: none + +A literal `$in` / `$nin` list compiled to one IN list however long it was. Oracle refuses an IN list of more than 1,000 expressions (ORA-01795), so on an Oracle datasource a read naming more than 1,000 values failed. On Oracle a longer list is now emitted as several lists of at most 1,000: `$in` as their disjunction, `$nin` as their conjunction inside the same NULL-safe arm, which select the same rows. + +SQL Server refuses a request of more than 2,100 parameters, and splitting a list does not change how many it binds. A `$in` / `$nin` list of more than 2,100 values on a SQL Server datasource is now refused before any statement is built, as `INVALID_FILTER` / 400 naming the ceiling, instead of reaching the server and coming back as its own error. A statement whose lists each fit but whose parameters together pass the ceiling is still answered by the server's error. + +SQLite, PostgreSQL and MySQL, and every list within the ceilings, compile to the same SQL as before. From 62243fe9c9319e81e212dbbfbe8f3ceeabdb6600 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 02:04:56 +0000 Subject: [PATCH 4/4] test(driver-sql): enumerate the SQL Server list-ceiling refusal on the compile seam The new $in/$nin refusal goes through withheldFilterError, so the compile-refusal roster gets its row, and the tenant-chokepoint gate declares the new sql-driver module it now scans. Claude-Session: https://claude.ai/code/session_016WV4cwiNRyb9B38wT2fjYj Co-authored-by: Claude --- .../src/sql-driver-compile-refusal-seam.test.ts | 11 +++++++++++ scripts/check-tenant-chokepoint.mjs | 1 + 2 files changed, 12 insertions(+) diff --git a/packages/drivers/driver-sql/src/sql-driver-compile-refusal-seam.test.ts b/packages/drivers/driver-sql/src/sql-driver-compile-refusal-seam.test.ts index 35391ee464b..f5201fde757 100644 --- a/packages/drivers/driver-sql/src/sql-driver-compile-refusal-seam.test.ts +++ b/packages/drivers/driver-sql/src/sql-driver-compile-refusal-seam.test.ts @@ -320,6 +320,17 @@ const DOORS: readonly Door[] = [ Object.defineProperty(driver, 'dialectName', { get: () => 'mssql', configurable: true }); }, }, + // ── #39312: a $in list past SQL Server's per-request parameter ceiling ──── + { + builder: 'assertInListWithinRequestCeiling', + where: () => ({ [POLICY_COL]: { $in: Array.from({ length: 2_101 }, (_, i) => `v${i}`) } }), + secrets: [POLICY_COL], + klass: 'SQL Server accepts at most 2,100 parameters in one request', + // The fixture is SQLite; the refusal reads the dialect the driver answers. + setup: (driver) => { + Object.defineProperty(driver, 'isMssql', { get: () => true, configurable: true }); + }, + }, ]; // ── Half 1: the enumeration ─────────────────────────────────────────────────── diff --git a/scripts/check-tenant-chokepoint.mjs b/scripts/check-tenant-chokepoint.mjs index d980d88cfe8..770f36a78ef 100644 --- a/scripts/check-tenant-chokepoint.mjs +++ b/scripts/check-tenant-chokepoint.mjs @@ -265,6 +265,7 @@ const DECLARED_WATCH_HINTS = [ 'packages/drivers/driver-sql/src/sql-driver-facet-hosts.ts', 'packages/drivers/driver-sql/src/sql-driver-field-mapping.ts', 'packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts', + 'packages/drivers/driver-sql/src/sql-driver-in-list-ceiling.ts', 'packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts', 'packages/drivers/driver-sql/src/sql-driver-introspection.ts', 'packages/drivers/driver-sql/src/sql-driver-latest-per.ts',