Skip to content
Open
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
2 changes: 1 addition & 1 deletion docs/reference/error-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import type { AnyQueryAst } from './ast/types';
import { collectOrderedParamRefs } from './ast/util';

const targetNames: Record<string, string> = { 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;
}
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from '../bind-parameter-limit';
export * from '../plan';
export type { SqlExecutionPlan } from '../sql-execution-plan';
Original file line number Diff line number Diff line change
@@ -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);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<Scope, QueryContext>;
export type UpdateSetCallback = (
fields: ReturnType<typeof createFieldProxy>,
Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -1027,6 +1028,11 @@ export function supportsDefaultInInsert(contract: Contract<SqlStorage>): 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<SqlStorage>): number | undefined {
return bindParameterLimitOfTarget(contract.target);
}

/** Whether `contract` requires `capability`. */
export function hasContractCapability(contract: Contract<SqlStorage>, capability: string): boolean {
return contract.requiredCapabilities.includes(capability);
Expand Down
Original file line number Diff line number Diff line change
@@ -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<SqlStorage>,
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,
},
},
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -377,7 +381,7 @@ export function createAllGraph(
keys: [],
requires: [],
owner: {
operation: rows.length === 1 ? 'create' : 'createAll',
operation,
modelName: collection.modelName,
},
returns,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -55,6 +56,11 @@ export class Insert extends StatementNode<Payloads> {
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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const inserted = new Insert(asts, owner, junction);
return graph.add(inserted, {
payload: keys.map(({ from, columns }) => new PayloadData(from, columns)),
state: graph.stateEdgesFor(inserted),
Expand Down
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -69,6 +70,12 @@ export function withoutDefaultInInsert(contract: TestContract = baseContract): T
return deserializeTestContract(raw);
}

export function withTarget(contract: TestContract, target: string): TestContract {
return blindCast<TestContract, 'the graph builders read contract.target as a plain string field'>(
{ ...contract, target },
);
}

export function withoutCapabilityKeys(
contract: TestContract,
keys: readonly string[],
Expand Down
Loading