diff --git a/docs/reference/error-reference.md b/docs/reference/error-reference.md index 5f06fcb36bac..c4513507acc1 100644 --- a/docs/reference/error-reference.md +++ b/docs/reference/error-reference.md @@ -1251,7 +1251,7 @@ An aggregate was invoked for an operation/input pair the composed target declare ### ORM.ARGUMENT_INVALID -An argument to an ORM client or query-builder method, including the input of a nested relation mutation, is malformed or missing a required part. `problem: 'missing-where'` means a nested `updateFirst()` or `deleteFirst()` on a to-many relation has no `where` that filters, `problem: 'parent-link-column'` that the data or update defaults of a nested `updateAll()` or `updateFirst()` set a field linking the related rows to their parent, and `problem: 'foreign-key-with-relation-mutation'` that `updateFirst()` data sets a field of the foreign key the record holds for a relation (`fields`) and also has a callback on that relation (`relation`). The SQL builder's `fns.in` and `fns.notIn` raise it for a right operand that is an expression of one value, not an array, a subquery or an expression holding an array (payload `op`). +An argument to an ORM client or query-builder method, including the input of a nested relation mutation, is malformed or missing a required part. `problem: 'missing-where'` means a nested `updateFirst()` or `deleteFirst()` on a to-many relation has no `where` that filters, `problem: 'parent-link-column'` that the data or update defaults of a nested `updateAll()` or `updateFirst()` set a field linking the related rows to their parent, `problem: 'foreign-key-with-relation-mutation'` that `updateFirst()` data sets a field of the foreign key the record holds for a relation (`fields`) and also has a callback on that relation (`relation`), and `problem: 'too-many-bind-parameters'` that one INSERT statement — from `createAll()`, `createAndCount()` or the SQL builder's `insert()` — would bind more parameters than the target allows (`parameters` and `limit` carry the numbers; PostgreSQL and MySQL allow 65,535 per statement); the oversized statement is refused before it is sent, though in a nested write that only exceeds the limit once parent or junction keys are attached, earlier statements in the same run may already have written rows and the surrounding transaction determines whether those writes persist. The SQL builder's `fns.in` and `fns.notIn` raise it for a right operand that is an expression of one value, not an array, a subquery or an expression holding an array (payload `op`). ### ORM.CAPABILITY_MISSING diff --git a/packages/2-sql-family/4-lanes/relational-core/src/bind-parameter-limit.ts b/packages/2-sql-family/4-lanes/relational-core/src/bind-parameter-limit.ts new file mode 100644 index 000000000000..0f6aec5a25a6 --- /dev/null +++ b/packages/2-sql-family/4-lanes/relational-core/src/bind-parameter-limit.ts @@ -0,0 +1,23 @@ +import type { AnyQueryAst } from './ast/types'; +import { collectOrderedParamRefs } from './ast/util'; + +const targetNames: Record = { mysql: 'MySQL', postgres: 'PostgreSQL' }; + +/** The name a message about a target's own limit uses, e.g. `PostgreSQL` for `postgres`. */ +export function targetDisplayNameOf(target: string): string { + return targetNames[target] ?? target; +} + +/** + * The bind parameters one statement may carry on a target whose wire protocol or server fixes that number: PostgreSQL numbers a Bind message's parameters in a 16-bit field and MySQL allows 65,535 placeholders per statement, and both reject a statement past the limit with an error that reads as a broken connection. SQLite's limit is a compile-time option of the bundled engine, so no number is declared for it here. + */ +export function bindParameterLimitOfTarget(target: string): number | undefined { + return target === 'postgres' || target === 'mysql' ? 65_535 : undefined; +} + +/** + * The bind parameters `ast` occupies in one statement on `target`: the number its limit counts. PostgreSQL numbers a parameter reference once and writes that `$N` wherever the statement repeats it, so a reference that several rows share is bound once. MySQL takes only positional parameters, and its driver writes a repeated reference as one `?` per occurrence with the value repeated, so there every occurrence is bound. + */ +export function bindParameterCountOf(ast: AnyQueryAst, target: string): number { + return (target === 'mysql' ? ast.collectParamRefs() : collectOrderedParamRefs(ast)).length; +} diff --git a/packages/2-sql-family/4-lanes/relational-core/src/exports/plan.ts b/packages/2-sql-family/4-lanes/relational-core/src/exports/plan.ts index fb7db081fa93..091aad28cd60 100644 --- a/packages/2-sql-family/4-lanes/relational-core/src/exports/plan.ts +++ b/packages/2-sql-family/4-lanes/relational-core/src/exports/plan.ts @@ -1,2 +1,3 @@ +export * from '../bind-parameter-limit'; export * from '../plan'; export type { SqlExecutionPlan } from '../sql-execution-plan'; diff --git a/packages/2-sql-family/4-lanes/relational-core/test/bind-parameter-limit.test.ts b/packages/2-sql-family/4-lanes/relational-core/test/bind-parameter-limit.test.ts new file mode 100644 index 000000000000..0bd733b7bbd4 --- /dev/null +++ b/packages/2-sql-family/4-lanes/relational-core/test/bind-parameter-limit.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest'; +import { bindParameterCountOf, bindParameterLimitOfTarget } from '../src/bind-parameter-limit'; +import { InsertAst, ParamRef, TableSource } from '../src/exports/ast'; + +describe('bindParameterLimitOfTarget', () => { + it('declares the same limit for PostgreSQL and MySQL, and none for a target whose limit is not fixed', () => { + expect(bindParameterLimitOfTarget('postgres')).toBe(65_535); + expect(bindParameterLimitOfTarget('mysql')).toBe(65_535); + expect(bindParameterLimitOfTarget('sqlite')).toBeUndefined(); + }); +}); + +describe('bindParameterCountOf', () => { + // Three rows of one parameter of their own, and a parent key they all share: four references, + // six occurrences. + const parentKey = ParamRef.of(1); + const ast = InsertAst.into(TableSource.named('post')).withRows( + [0, 1, 2].map((i) => ({ id: ParamRef.of(i + 1), user_id: parentKey })), + ); + + it('counts a shared parameter once on PostgreSQL, which numbers a reference once', () => { + expect(bindParameterCountOf(ast, 'postgres')).toBe(4); + }); + + it('counts a shared parameter once per occurrence on MySQL, whose driver binds a value per placeholder', () => { + expect(bindParameterCountOf(ast, 'mysql')).toBe(6); + }); +}); diff --git a/packages/2-sql-family/4-lanes/sql-builder/src/runtime/mutation-impl.ts b/packages/2-sql-family/4-lanes/sql-builder/src/runtime/mutation-impl.ts index 53491bf44b6d..89ad44b7f884 100644 --- a/packages/2-sql-family/4-lanes/sql-builder/src/runtime/mutation-impl.ts +++ b/packages/2-sql-family/4-lanes/sql-builder/src/runtime/mutation-impl.ts @@ -17,7 +17,12 @@ import { UpdateAst, } from '@internal/sql-relational-core/ast'; import { createFunctions } from '@internal/sql-relational-core/functions'; -import type { SqlQueryPlan } from '@internal/sql-relational-core/plan'; +import { + bindParameterCountOf, + bindParameterLimitOfTarget, + type SqlQueryPlan, + targetDisplayNameOf, +} from '@internal/sql-relational-core/plan'; import { ifDefined } from '@internal/utils/defined'; import { structuredError } from '@internal/utils/structured-error'; import type { Expression, ExpressionBuilder } from '../expression'; @@ -63,6 +68,35 @@ function mergeWriteAnnotations( return next; } +function requireBindParametersWithinLimit( + ctx: BuilderContext, + ast: InsertAst, + namespaceId: string, + tableName: string, +): void { + const limit = bindParameterLimitOfTarget(ctx.target); + if (limit === undefined) return; + const parameters = bindParameterCountOf(ast, ctx.target); + if (parameters <= limit) return; + throw structuredError( + 'ORM.ARGUMENT_INVALID', + `insert() on table "${tableName}" would bind ${parameters} parameters in one INSERT statement; ${targetDisplayNameOf(ctx.target)} allows ${limit} per statement.`, + { + why: 'The database rejects a statement past its bind-parameter limit with a driver error that reads as a broken connection, so the builder refuses the statement before sending it; nothing was sent.', + fix: `Split the rows into smaller insert() calls so no single INSERT statement binds more than ${limit} parameters.`, + meta: { + problem: 'too-many-bind-parameters', + method: 'insert()', + namespaceId, + table: tableName, + parameters, + limit, + target: ctx.target, + }, + }, + ); +} + type WhereCallback = ExpressionBuilder; export type UpdateSetCallback = ( fields: ReturnType, @@ -295,6 +329,7 @@ export class InsertQueryImpl< ); const ast = InsertAst.into(this.#tableSource).withRows(paramRows); + requireBindParametersWithinLimit(this.ctx, ast, this.#namespaceId, this.#tableName); if (this.#returningColumns.length === 0) { return ast; diff --git a/packages/2-sql-family/4-lanes/sql-builder/test/runtime/builders.test.ts b/packages/2-sql-family/4-lanes/sql-builder/test/runtime/builders.test.ts index a9085b68e38a..f1501bc017eb 100644 --- a/packages/2-sql-family/4-lanes/sql-builder/test/runtime/builders.test.ts +++ b/packages/2-sql-family/4-lanes/sql-builder/test/runtime/builders.test.ts @@ -18,6 +18,7 @@ import { TableSource, } from '@internal/sql-relational-core/ast'; import type { ExecutionContext } from '@internal/sql-relational-core/query-lane-context'; +import { blindCast } from '@internal/utils/casts'; import { describe, expect, it, vi } from 'vitest'; import { sql } from '../../src/runtime/sql'; import { contract as contractJson } from '../fixtures/contract'; @@ -804,6 +805,67 @@ describe('INSERT multi-row', () => { ); }); + it('refuses a build whose one statement binds more parameters than the target allows', () => { + const rows = Array.from({ length: 21_846 }, (_, i) => ({ + id: i + 1, + name: `u${i}`, + email: `u${i}@example.test`, + })); + + expect(() => db().public.users.insert(rows).build()).toThrow( + expect.objectContaining({ + code: 'ORM.ARGUMENT_INVALID', + message: + 'insert() on table "users" would bind 65538 parameters in one INSERT statement; PostgreSQL allows 65535 per statement.', + meta: expect.objectContaining({ + problem: 'too-many-bind-parameters', + method: 'insert()', + table: 'users', + parameters: 65_538, + limit: 65_535, + target: 'postgres', + }), + }), + ); + }); + + it('keeps building at exactly the target limit', () => { + const rows = Array.from({ length: 21_845 }, (_, i) => ({ + id: i + 1, + name: `u${i}`, + email: `u${i}@example.test`, + })); + + expect(() => db().public.users.insert(rows).build()).not.toThrow(); + }); + + it('names MySQL and its own limit on a mysql target', () => { + const mysqlContract = blindCast< + Contract, + 'the dsl reads contract.target as a plain string field' + >({ ...sqlContract, target: 'mysql' }); + const d = sql({ + context: { ...stubBase, contract: mysqlContract } as unknown as ExecutionContext< + typeof mysqlContract + >, + rawCodecInferer: stubInferer, + }); + const rows = Array.from({ length: 21_846 }, (_, i) => ({ + id: i + 1, + name: `u${i}`, + email: `u${i}@example.test`, + })); + + expect(() => d.public.users.insert(rows).build()).toThrow( + expect.objectContaining({ + code: 'ORM.ARGUMENT_INVALID', + message: + 'insert() on table "users" would bind 65538 parameters in one INSERT statement; MySQL allows 65535 per statement.', + meta: expect.objectContaining({ limit: 65_535, target: 'mysql' }), + }), + ); + }); + it('single row via array calls applyMutationDefaults once', () => { const spy = vi.fn(() => []); const d = sql({ diff --git a/packages/3-extensions/sql-orm-client/src/collection-contract.ts b/packages/3-extensions/sql-orm-client/src/collection-contract.ts index 6d7132b515c9..93f96bbe40f3 100644 --- a/packages/3-extensions/sql-orm-client/src/collection-contract.ts +++ b/packages/3-extensions/sql-orm-client/src/collection-contract.ts @@ -8,6 +8,7 @@ import type { import { capabilityUnavailableMessage } from '@internal/sql-contract/capability-messages'; import type { SqlStorage, StorageTable } from '@internal/sql-contract/types'; import { isExpression } from '@internal/sql-relational-core/expression'; +import { bindParameterLimitOfTarget } from '@internal/sql-relational-core/plan'; import { blindCast } from '@internal/utils/casts'; import { ifDefined } from '@internal/utils/defined'; import { InvariantError } from '@internal/utils/invariant-error'; @@ -1027,6 +1028,11 @@ export function supportsDefaultInInsert(contract: Contract): boolean return hasContractCapability(contract, 'db.defaultInInsert'); } +/** The bind parameters one statement may carry on the contract's target, from `bindParameterLimitOfTarget` on the SQL relational core. */ +export function bindParameterLimitOf(contract: Contract): number | undefined { + return bindParameterLimitOfTarget(contract.target); +} + /** Whether `contract` requires `capability`. */ export function hasContractCapability(contract: Contract, capability: string): boolean { return contract.requiredCapabilities.includes(capability); diff --git a/packages/3-extensions/sql-orm-client/src/statement-graph/bind-parameter-limit.ts b/packages/3-extensions/sql-orm-client/src/statement-graph/bind-parameter-limit.ts new file mode 100644 index 000000000000..df562d381efb --- /dev/null +++ b/packages/3-extensions/sql-orm-client/src/statement-graph/bind-parameter-limit.ts @@ -0,0 +1,51 @@ +import type { Contract } from '@internal/contract/types'; +import type { SqlStorage } from '@internal/sql-contract/types'; +import type { InsertAst } from '@internal/sql-relational-core/ast'; +import { bindParameterCountOf, targetDisplayNameOf } from '@internal/sql-relational-core/plan'; +import { bindParameterLimitOf } from '../collection-contract'; +import { ormError } from '../orm-errors'; +import type { WrittenRowOwner } from '../written-keys'; + +/** + * Refuses INSERT statements that bind more parameters than the target allows in one statement. + * + * `construction` runs on the ASTs a graph is built from, before any statement is sent. `execution` + * runs in `Insert.execute` on the ASTs after payload parameters (parent keys, junction keys) have + * been added to every row, because those push the statement past a limit its construction-time + * count was under. The count is the target's, from `bindParameterCountOf`: MySQL binds a parameter + * the statement repeats once per occurrence, so the one payload parameter every row shares counts + * once per row there. The `why` of each refusal matches its point: at construction nothing was sent, + * while at execution earlier statements of the same run may already have written rows. + */ +export function requireBindParametersWithinLimit( + contract: Contract, + asts: readonly InsertAst[], + owner: WrittenRowOwner, + point: 'construction' | 'execution' = 'construction', +): void { + const limit = bindParameterLimitOf(contract); + if (limit === undefined) return; + for (const ast of asts) { + const parameters = bindParameterCountOf(ast, contract.target); + if (parameters <= limit) continue; + throw ormError( + 'ORM.ARGUMENT_INVALID', + `${owner.operation}() on model "${owner.modelName}" would bind ${parameters} parameters in one INSERT statement; ${targetDisplayNameOf(contract.target)} allows ${limit} per statement.`, + { + why: + point === 'construction' + ? 'The database rejects a statement past its bind-parameter limit with a driver error that reads as a broken connection, so the ORM refuses the write before sending it; nothing was written.' + : 'The database rejects a statement past its bind-parameter limit with a driver error that reads as a broken connection, so the ORM refuses the statement before sending it; statements earlier in the same run may already have written rows, and the surrounding transaction decides whether they stay.', + fix: `Split the rows into smaller batches so no single INSERT statement binds more than ${limit} parameters.`, + meta: { + problem: 'too-many-bind-parameters', + method: `${owner.operation}()`, + model: owner.modelName, + parameters, + limit, + target: contract.target, + }, + }, + ); + } +} diff --git a/packages/3-extensions/sql-orm-client/src/statement-graph/collection-graphs.ts b/packages/3-extensions/sql-orm-client/src/statement-graph/collection-graphs.ts index 101335712705..e8b99af2354f 100644 --- a/packages/3-extensions/sql-orm-client/src/statement-graph/collection-graphs.ts +++ b/packages/3-extensions/sql-orm-client/src/statement-graph/collection-graphs.ts @@ -356,8 +356,12 @@ export function createAllGraph( return b.graph; } const rows = createRowsOf(collection, data); + // The diagnostics name the requested API: the count terminal is createAndCount(), the + // rows-returning bulk call is createAll() (create() when it carries one row). + const operation = + returns === 'count' ? 'createAndCount' : rows.length === 1 ? 'create' : 'createAll'; if (conflict !== undefined) { - const method = returns === 'rows' ? 'createAll()' : 'createAndCount()'; + const method = `${operation}()`; const { modelName, state } = collection; requireRowsThatCanConflict( collection.context.contract, @@ -377,7 +381,7 @@ export function createAllGraph( keys: [], requires: [], owner: { - operation: rows.length === 1 ? 'create' : 'createAll', + operation, modelName: collection.modelName, }, returns, diff --git a/packages/3-extensions/sql-orm-client/src/statement-graph/insert.ts b/packages/3-extensions/sql-orm-client/src/statement-graph/insert.ts index a01889875864..353f61cae90a 100644 --- a/packages/3-extensions/sql-orm-client/src/statement-graph/insert.ts +++ b/packages/3-extensions/sql-orm-client/src/statement-graph/insert.ts @@ -7,6 +7,7 @@ import type { } from '@internal/sql-relational-core/ast'; import type { ExecutionContext } from '@internal/sql-relational-core/query-lane-context'; import type { WrittenRowOwner } from '../written-keys'; +import { requireBindParametersWithinLimit } from './bind-parameter-limit'; import type { NodeId, StorageRow } from './edge'; import { withColumns } from './filtered-statement'; import type { Graph } from './graph'; @@ -55,6 +56,11 @@ export class Insert extends StatementNode { const payload = inputs.payload === null ? undefined : payloadOf(inputs.payload, this.junction); const asts = payload === undefined ? this.asts : this.asts.map((ast) => withPayload(ast, payload)); + if (payload !== undefined) { + // Payload parameters (parent keys, junction keys) join every row only here, so a batch whose + // construction-time count was within the limit can exceed it once they are added. + requireBindParametersWithinLimit(run.context.contract, asts, this.owner, 'execution'); + } const [only, ...others] = asts; if (givesOwnValues(run.context, this.returns)) { return insertGivingOwnValues(asts, this.returns, this.owner, run); diff --git a/packages/3-extensions/sql-orm-client/src/statement-graph/model-statements.ts b/packages/3-extensions/sql-orm-client/src/statement-graph/model-statements.ts index b756b9ba0dcd..0f827b16a421 100644 --- a/packages/3-extensions/sql-orm-client/src/statement-graph/model-statements.ts +++ b/packages/3-extensions/sql-orm-client/src/statement-graph/model-statements.ts @@ -16,6 +16,7 @@ import { collectionSelectAst, collectionSelectWithIncludesAst } from '../query-p import type { AliasedTable } from '../table-scope'; import { type CollectionState, emptyState } from '../types'; import type { WrittenRowOwner } from '../written-keys'; +import { requireBindParametersWithinLimit } from './bind-parameter-limit'; import { Delete } from './delete'; import type { ColumnMapping, NodeId } from './edge'; import { FilterData } from './filter-data'; @@ -87,11 +88,9 @@ export function addInsert( ): NodeId { const { contract } = context; const groups = supportsDefaultInInsert(contract) ? [rows] : groupRowsByColumnSignature(rows); - const inserted = new Insert( - groups.map((group) => insertAst(contract, table, group, conflict)), - owner, - junction, - ); + const asts = groups.map((group) => insertAst(contract, table, group, conflict)); + requireBindParametersWithinLimit(contract, asts, owner); + const inserted = new Insert(asts, owner, junction); return graph.add(inserted, { payload: keys.map(({ from, columns }) => new PayloadData(from, columns)), state: graph.stateEdgesFor(inserted), diff --git a/packages/3-extensions/sql-orm-client/test/collection-fixtures.ts b/packages/3-extensions/sql-orm-client/test/collection-fixtures.ts index 303db8ca60f5..8653d2041100 100644 --- a/packages/3-extensions/sql-orm-client/test/collection-fixtures.ts +++ b/packages/3-extensions/sql-orm-client/test/collection-fixtures.ts @@ -1,6 +1,7 @@ import { type Contract, soleDomainNamespaceId } from '@internal/contract/types'; import type { SqlStorage } from '@internal/sql-contract/types'; import type { ExecutionContext } from '@internal/sql-relational-core/query-lane-context'; +import { blindCast } from '@internal/utils/casts'; import { Collection } from '../src/collection'; import type { RelatedCollection } from '../src/relation-mutations'; import type { MockRuntime, TestContract } from './helpers'; @@ -69,6 +70,12 @@ export function withoutDefaultInInsert(contract: TestContract = baseContract): T return deserializeTestContract(raw); } +export function withTarget(contract: TestContract, target: string): TestContract { + return blindCast( + { ...contract, target }, + ); +} + export function withoutCapabilityKeys( contract: TestContract, keys: readonly string[], diff --git a/packages/3-extensions/sql-orm-client/test/statement-graph/insert-bind-limit.test.ts b/packages/3-extensions/sql-orm-client/test/statement-graph/insert-bind-limit.test.ts new file mode 100644 index 000000000000..054795e4e348 --- /dev/null +++ b/packages/3-extensions/sql-orm-client/test/statement-graph/insert-bind-limit.test.ts @@ -0,0 +1,249 @@ +import type { Contract } from '@internal/contract/types'; +import type { SqlStorage } from '@internal/sql-contract/types'; +import { collectOrderedParamRefs } from '@internal/sql-relational-core/ast'; +import { describe, expect, it } from 'vitest'; +import { parseMutationInput } from '../../src/relation-mutations'; +import { createAllGraph, createGraph } from '../../src/statement-graph/collection-graphs'; +import { executeGraph } from '../../src/statement-graph/run-graph'; +import type { RelationMutator } from '../../src/types'; +import { + baseContract, + createCollectionFor, + relatedCollectionOf, + withTarget, +} from '../collection-fixtures'; +import { createMockRuntime, getTestContext } from '../helpers'; +import { printGraph } from './print-graph'; + +const users = createCollectionFor('User').collection.select('id', 'name'); +const contextMysql = { ...getTestContext(), contract: withTarget(baseContract, 'mysql') }; +const contextSqlite = { ...getTestContext(), contract: withTarget(baseContract, 'sqlite') }; + +function targetOf(context = getTestContext()) { + return { context, state: users.state, modelName: 'User', namespaceId: 'public' }; +} + +const target = targetOf(); + +function rowOf(i: number, columns: readonly string[]): Record { + const value = (column: string) => (column === 'id' ? i + 1 : `u${i}`); + return Object.fromEntries(columns.map((column) => [column, value(column)])); +} + +function rowsOf(count: number, columns: readonly string[]): Record[] { + return Array.from({ length: count }, (_, i) => rowOf(i, columns)); +} + +const fourColumns = ['id', 'name', 'email', 'address']; +const threeColumns = ['id', 'name', 'email']; +const overWireLimitRows = rowsOf(16_384, fourColumns); + +function thrownOf(run: () => unknown): unknown { + try { + run(); + } catch (error) { + return error; + } + return undefined; +} + +describe('createAllGraph bind-parameter limit', () => { + it('refuses a createAll whose one statement binds more parameters than the target allows, before sending', () => { + const thrown = thrownOf(() => createAllGraph(target, overWireLimitRows, undefined, 'rows')); + + expect(thrown).toMatchObject({ + code: 'ORM.ARGUMENT_INVALID', + message: + 'createAll() on model "User" would bind 65536 parameters in one INSERT statement; PostgreSQL allows 65535 per statement.', + meta: { + problem: 'too-many-bind-parameters', + method: 'createAll()', + model: 'User', + parameters: 65_536, + limit: 65_535, + target: 'postgres', + }, + }); + }); + + it('keeps one Insert of every row while the statement binds under the limit', () => { + const graph = createAllGraph(target, rowsOf(16_383, fourColumns), undefined, 'rows'); + + expect(printGraph(graph)).toBe(['n1 Insert users 16383 rows', 'result: n1'].join('\n')); + }); + + it('keeps one Insert of every row at exactly the limit', () => { + const graph = createAllGraph(target, rowsOf(21_845, threeColumns), undefined, 'rows'); + + expect(printGraph(graph)).toBe(['n1 Insert users 21845 rows', 'result: n1'].join('\n')); + }); + + it('names MySQL and its own limit on a mysql target', () => { + const thrown = thrownOf(() => + createAllGraph(targetOf(contextMysql), overWireLimitRows, undefined, 'rows'), + ); + + expect(thrown).toMatchObject({ + code: 'ORM.ARGUMENT_INVALID', + message: + 'createAll() on model "User" would bind 65536 parameters in one INSERT statement; MySQL allows 65535 per statement.', + meta: { limit: 65_535, target: 'mysql' }, + }); + }); + + it('builds the same statement on a target that declares no bind-parameter limit', () => { + const graph = createAllGraph(targetOf(contextSqlite), overWireLimitRows, undefined, 'rows'); + + expect(printGraph(graph)).toBe(['n1 Insert users 16384 rows', 'result: n1'].join('\n')); + }); + + it('refuses createAndCount() the same way and names createAndCount() as the operation', () => { + const thrown = thrownOf(() => createAllGraph(target, overWireLimitRows, undefined, 'count')); + + expect(thrown).toMatchObject({ + code: 'ORM.ARGUMENT_INVALID', + message: + 'createAndCount() on model "User" would bind 65536 parameters in one INSERT statement; PostgreSQL allows 65535 per statement.', + meta: { problem: 'too-many-bind-parameters', method: 'createAndCount()' }, + }); + }); +}); + +describe('nested insert bind-parameter limit', () => { + // 21,845 rows x 3 columns pass the construction-time check at exactly 65,535 parameters. + const postRows = Array.from({ length: 21_845 }, (_, i) => ({ + id: i + 1, + title: `p${i}`, + views: 0, + })); + + function nestedGraphOf() { + return createGraph( + target, + parseMutationInput( + target.context.contract, + 'public', + 'User', + { + id: 1, + name: 'Ada', + email: 'ada@example.com', + posts: (postsMutator: RelationMutator, 'Post'>) => + postsMutator.create(postRows), + } as never, + relatedCollectionOf(target.context), + ), + ); + } + + it('refuses a nested multi-row insert whose parent-key payload pushes it past the limit, before sending', async () => { + const graph = nestedGraphOf(); + const runtime = createMockRuntime(); + // The parent's read-back row feeds the child's PayloadData edge. + runtime.setNextResults([[{ id: 1 }]]); + + // The shared parent-key parameter of the payload joins the 65,535 row parameters, pushing the + // statement to 65,536, one past the limit, at the moment withPayload applies it. + await expect(executeGraph(graph, { runtime, context: target.context })).rejects.toMatchObject({ + code: 'ORM.ARGUMENT_INVALID', + message: + 'create() on model "Post" would bind 65536 parameters in one INSERT statement; PostgreSQL allows 65535 per statement.', + meta: expect.objectContaining({ + problem: 'too-many-bind-parameters', + method: 'create()', + model: 'Post', + parameters: 65_536, + limit: 65_535, + target: 'postgres', + }), + }); + // The parent insert ran; only the nested insert is refused. + expect(runtime.executions).toHaveLength(1); + }); +}); + +describe('nested insert bind-parameter limit on MySQL', () => { + // 16,384 rows x 3 columns bind 49,152 parameters of their own, and the payload adds one parent-key + // parameter that every row shares: 49,153 references, under the limit where a shared reference is + // bound once. MySQL has only positional parameters, so its driver binds the shared one again in + // every row: 16,384 x 4 = 65,536 values, one past its limit. + const postRows = Array.from({ length: 16_384 }, (_, i) => ({ + id: i + 1, + title: `p${i}`, + views: 0, + })); + + function nestedGraphOf(context: typeof target.context) { + return createGraph( + { ...target, context }, + parseMutationInput( + context.contract, + 'public', + 'User', + { + id: 1, + name: 'Ada', + email: 'ada@example.com', + posts: (postsMutator: RelationMutator, 'Post'>) => + postsMutator.create(postRows), + } as never, + relatedCollectionOf(context), + ), + ); + } + + it('refuses a nested insert whose shared payload parameter is bound once per row, past the MySQL limit', async () => { + const graph = nestedGraphOf(contextMysql); + const runtime = createMockRuntime(); + runtime.setNextResults([[{ id: 1 }]]); + + await expect(executeGraph(graph, { runtime, context: contextMysql })).rejects.toMatchObject({ + code: 'ORM.ARGUMENT_INVALID', + message: + 'create() on model "Post" would bind 65536 parameters in one INSERT statement; MySQL allows 65535 per statement.', + meta: expect.objectContaining({ + problem: 'too-many-bind-parameters', + method: 'create()', + model: 'Post', + parameters: 65_536, + limit: 65_535, + target: 'mysql', + }), + }); + // The parent insert ran; only the nested insert is refused. + expect(runtime.executions).toHaveLength(1); + }); + + it('sends the same nested insert on PostgreSQL, which binds the shared parameter once', async () => { + const graph = nestedGraphOf(target.context); + const runtime = createMockRuntime(); + runtime.setNextResults([[{ id: 1 }], []]); + + await executeGraph(graph, { runtime, context: target.context }); + + // The statement is the same one: 65,536 occurrences of 49,153 parameters, which PostgreSQL binds + // as 49,153. + const nested = runtime.executions[1]?.plan.ast; + if (nested === undefined) throw new Error('the nested insert was not sent'); + expect(nested.collectParamRefs()).toHaveLength(65_536); + expect(collectOrderedParamRefs(nested)).toHaveLength(49_153); + }); +}); + +describe('createAll bind-parameter limit', () => { + it('refuses createAll() before any statement reaches the driver', () => { + const { collection, runtime } = createCollectionFor('User'); + + expect(() => collection.createAll(overWireLimitRows as never)).toThrow( + expect.objectContaining({ + code: 'ORM.ARGUMENT_INVALID', + meta: expect.objectContaining({ + problem: 'too-many-bind-parameters', + parameters: 65_536, + limit: 65_535, + }), + }), + ); + expect(runtime.executions).toEqual([]); + }); +}); diff --git a/skills/prisma-8/references/debug.md b/skills/prisma-8/references/debug.md index a182c3ec1d45..a8f912d65408 100644 --- a/skills/prisma-8/references/debug.md +++ b/skills/prisma-8/references/debug.md @@ -118,6 +118,7 @@ The single source of truth: read the envelope, find the row by `code`, follow th | `ORM.OPERATION_UNSUPPORTED` | ORM operation used where it is not supported; `meta.reason` says why | With `reason: 'junction-required-columns'` (nested `create` / `connect` on an N:M relation whose junction has required payload columns): write the junction table directly or use the SQL builder (`meta.junction`). Other reasons: `docs/reference/error-reference.md#ORM.OPERATION_UNSUPPORTED`. | | `ORM.OPERATION_UNSUPPORTED` with `reason: 'required-foreign-key'` | ORM nested `disconnect()` on a relation whose foreign key is required, or `deleteFirst()` on a relation the record holds a required key for (`meta.model`, `meta.fields`) | For `disconnect`: if `meta.model` is the model being updated, the record holds the key (a many-to-one relation, such as `Post.author`): `connect` it to another row or delete the record. Otherwise the related rows hold it (one-to-many, or one-to-one from the side without the key): connect them to another record or delete them. For `deleteFirst` (the record holds the key): `connect` the record to another row, or delete the record, before deleting the related row through its own collection. Or make the key optional. | | `ORM.ARGUMENT_INVALID` with `problem: 'missing-where'` | ORM nested `updateFirst()` / `deleteFirst()` on a to-many relation without a `where` that filters | Add `where(...)` naming the related row to change. | +| `ORM.ARGUMENT_INVALID` with `problem: 'too-many-bind-parameters'` | One INSERT statement — from `createAll()` / `createAndCount()` / the SQL builder's `insert()` — binds more parameters than the target allows (`meta.parameters` past `meta.limit`; PostgreSQL and MySQL allow 65,535 per statement) | Split the rows into smaller batches so one statement stays within `meta.limit`. The oversized statement is refused before it is sent; in a nested write, earlier statements in the same run may already have written rows, and the surrounding transaction determines whether those writes persist. | | `RUNTIME.ABORTED` (`details.phase` = `encode\|decode\|stream\|beforeEncode\|onRow`) | Runtime, when an `AbortSignal` fires mid-execute | Cancellation, not a bug; surface to the caller. | | `SqlQueryError` (no dotted code) | Raw-SQL paths surfacing a driver error | Inspect `sqlState` + `constraint` + `table` + `column`. Postgres `23505` = unique violation, `23503` = foreign-key violation, etc. Fix the data or the schema. | | TypeScript error mentioning a capability (e.g. `returning()` not on the type, `include` of a many-relation off a many-load) | Authoring-time, before any envelope fires | A method is offered only when the contract requires its capability. On PostgreSQL the contract's `requiredCapabilities` list (in `defineContract`, or beside the path in the config's contract entry) is that list; the error message names the key to add. Route to `references/contract.md` for the list and to `references/queries.md` for which method gates on which capability. Re-emit (`pnpm prisma contract emit`) after adding it. |