joist-core 2.4.0-next.5 → 2.4.0-next.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/queries/sql/execute.cjs +3 -8
- package/build/queries/sql/execute.cjs.map +1 -1
- package/build/queries/sql/execute.d.cts.map +1 -1
- package/build/queries/sql/execute.d.mts.map +1 -1
- package/build/queries/sql/execute.js +4 -9
- package/build/queries/sql/execute.js.map +1 -1
- package/build/queries/sql/query.cjs +54 -18
- package/build/queries/sql/query.cjs.map +1 -1
- package/build/queries/sql/query.d.cts +30 -5
- package/build/queries/sql/query.d.cts.map +1 -1
- package/build/queries/sql/query.d.mts +30 -5
- package/build/queries/sql/query.d.mts.map +1 -1
- package/build/queries/sql/query.js +54 -19
- package/build/queries/sql/query.js.map +1 -1
- package/package.json +2 -2
|
@@ -139,15 +139,10 @@ function parseStatement(arg) {
|
|
|
139
139
|
sql += ` RETURNING ${returning.selects.map((select) => select.sql).join(", ")}`;
|
|
140
140
|
for (const select of returning.selects) bindings.push(...select.bindings);
|
|
141
141
|
}
|
|
142
|
-
const
|
|
143
|
-
if (keptCtes.length > 0) {
|
|
144
|
-
const clause = require_queries_sql_query.withFragment(keptCtes);
|
|
145
|
-
sql = clause.sql + sql;
|
|
146
|
-
bindings.unshift(...clause.bindings);
|
|
147
|
-
}
|
|
142
|
+
const withCtes = require_queries_sql_query.prependCtes(ctes, new Set(refs), sql, bindings);
|
|
148
143
|
return {
|
|
149
|
-
sql,
|
|
150
|
-
bindings,
|
|
144
|
+
sql: withCtes.sql,
|
|
145
|
+
bindings: withCtes.bindings,
|
|
151
146
|
outerRefs: [],
|
|
152
147
|
output: returning?.output ?? {
|
|
153
148
|
kind: "pojo",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execute.cjs","names":["isReadQueryValue","parseUserQuery","AliasAssigner","Ctx","registerCtes","projectionToSql","tableSqlName","kq","parseNestedQuery","safeKq","conditionToSql","injectedConditions","pruneCtes","withFragment","isEntityTable","getTableMgmt","isCustomTable","fail","isExpr","isEntity","asNode","keyToTaggedId","toTaggedId"],"sources":["../../../src/queries/sql/execute.ts"],"sourcesContent":["import type { DriverQueryResult } from \"src/drivers/Driver.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport type { IdOf } from \"src/EntityManager.ts\";\nimport type { EntityMetadata } from \"src/EntityMetadata.ts\";\nimport { keyToTaggedId, toTaggedId } from \"src/keys.ts\";\nimport type { SqlCondition } from \"src/queries/conditions.ts\";\nimport { AliasAssigner } from \"src/queries/sql/AliasAssigner.ts\";\nimport {\n type CustomColumnInputs,\n type CustomColumnValue,\n type CustomColumnsOf,\n type CustomTableFor,\n} from \"src/queries/sql/custom.ts\";\nimport { type ExprBrand, type ExprLike, type SqlFragment, asNode, exprBrand, isExpr } from \"src/queries/sql/Expr.ts\";\nimport { kq, safeKq } from \"src/queries/sql/keywords.ts\";\nimport {\n type CheckReadQuery,\n type CheckScope,\n type CheckSetQuery,\n Ctx,\n type EntityHydrator,\n type NameOf,\n type Plan,\n type Query,\n type QueryJoinInput,\n type QueryRow,\n type ReadQueryRow,\n type SetOperand,\n type SetOperation,\n type SetQuery,\n type Subquery,\n type WithInput,\n checkPojoKeys,\n conditionToSql,\n entityQueryBrand,\n injectedConditions,\n isReadQueryValue,\n parseNestedQuery,\n parseUserQuery,\n projectionToSql,\n pruneCtes,\n registerCtes,\n subqueryBrand,\n withFragment,\n} from \"src/queries/sql/query.ts\";\nimport {\n type TableFor,\n type TableSourceMgmt,\n getTableMgmt,\n isCustomTable,\n isEntityTable,\n tableMgmt,\n tableSqlName,\n} from \"src/queries/sql/Tables.ts\";\nimport type { Column, ColumnDescriptors } from \"src/serde/columns.ts\";\nimport type { ColumnsOf, TypeMapEntry } from \"src/typeMap.ts\";\nimport { fail } from \"src/utils.ts\";\n\n/** The native command count and decoded rows from one immediate SQL statement. */\nexport interface ExecuteResult<R> {\n rowCount: number;\n rows: R[];\n}\n\n/** A mutation's RETURNING projection: one SQL expression or a named object of expressions. */\nexport type MutationReturning = (ExprLike<unknown> | Readonly<Record<string, ExprLike<unknown>>>) & {\n readonly [tableMgmt]?: never;\n readonly [subqueryBrand]?: never;\n readonly [entityQueryBrand]?: never;\n};\n\n/** SQL INSERT inputs, based on physical storage rather than entity creation options. */\nexport type InsertValues<T extends Entity> = {\n [K in RequiredInsertKey<T>]: Assignment<T, K>;\n} & {\n [K in Exclude<InsertKey<T>, RequiredInsertKey<T>>]?: Assignment<T, K> | undefined;\n};\n\n/** SQL UPDATE inputs include persisted derived columns, but never primary keys. */\nexport type UpdateValues<T extends Entity> = {\n [K in UpdateKey<T>]?: Assignment<T, K> | undefined;\n};\n\n/** A reusable INSERT POJO; use a concrete Q for annotated INSERT SELECT source checking. */\nexport type InsertStatement<\n T extends Entity,\n R extends MutationReturning | undefined = MutationReturning | undefined,\n Q extends SetOperand = Query<InsertProjection<T>, []> | Subquery<InsertSourceRow<T>, string>,\n> = {\n readonly insert: MutationTargetTable<T>;\n readonly returning?: R;\n readonly update?: never;\n readonly delete?: never;\n readonly set?: never;\n readonly where?: never;\n readonly allowAll?: never;\n readonly softDeletes?: never;\n /** CTEs to add to a `WITH` before the INSERT; see `Clauses.with`. */\n readonly with?: WithInput;\n} & NoMutationReadClauses &\n (\n | { readonly values: readonly InsertValues<T>[]; readonly from?: never }\n | { readonly from: Q & CheckInsertSource<T, Q>; readonly values?: never }\n );\n\n/** A reusable guarded UPDATE POJO. Undefined assignments leave existing columns unchanged. */\nexport type UpdateStatement<\n T extends Entity,\n R extends MutationReturning | undefined = MutationReturning | undefined,\n> = {\n readonly update: MutationTargetTable<T>;\n readonly set: UpdateValues<T>;\n readonly returning?: R;\n readonly insert?: never;\n readonly delete?: never;\n readonly values?: never;\n readonly from?: never;\n /** CTEs to add to a `WITH` before the UPDATE; see `Clauses.with`. */\n readonly with?: WithInput;\n} & MutationFilter &\n NoMutationReadClauses;\n\n/** A reusable guarded physical DELETE POJO, not an ORM soft delete. */\nexport type DeleteStatement<\n T extends Entity,\n R extends MutationReturning | undefined = MutationReturning | undefined,\n> = {\n readonly delete: MutationTargetTable<T>;\n readonly returning?: R;\n readonly insert?: never;\n readonly update?: never;\n readonly values?: never;\n readonly from?: never;\n readonly set?: never;\n /** CTEs to add to a `WITH` before the DELETE; see `Clauses.with`. */\n readonly with?: WithInput;\n} & MutationFilter &\n NoMutationReadClauses;\n\n/** Public statement annotations retain the target's physical field policy. */\nexport type MutationStatement<\n T extends Entity,\n R extends MutationReturning | undefined = MutationReturning | undefined,\n> = InsertStatement<T, R> | UpdateStatement<T, R> | DeleteStatement<T, R>;\n\n/** Inference starts with the literal POJO; CheckMutation checks its target and every supplied key. */\nexport type MutationInput = (\n | { readonly insert: TableFor<Entity>; readonly values: readonly object[]; readonly from?: never }\n | { readonly insert: TableFor<Entity>; readonly from: SetOperand; readonly values?: never }\n | { readonly update: TableFor<Entity>; readonly set: object }\n | { readonly delete: TableFor<Entity> }\n | {\n readonly insert: CustomTableFor;\n readonly values: readonly object[];\n readonly from?: never;\n }\n | { readonly insert: CustomTableFor; readonly from: SetOperand; readonly values?: never }\n | { readonly update: CustomTableFor; readonly set: object }\n | { readonly delete: CustomTableFor }\n) & { readonly returning?: MutationReturning; readonly with?: WithInput } & MutationFilter;\n\n/** Without RETURNING the row type is never; scalar expressions produce scalar rows. */\nexport type MutationRow<M> = M extends { readonly returning?: infer R }\n ? R extends MutationReturning\n ? R extends ExprLike<unknown>\n ? QueryRow<R>\n : { -readonly [K in keyof QueryRow<R>]: QueryRow<R>[K] }\n : never\n : never;\n\n/** Checks nonliteral statements as well as fresh literals without widening their inferred result. */\nexport type CheckMutation<M> = M extends unknown\n ? [CustomColumnsOf<TargetTable<M>>] extends [never]\n ? TargetEntity<M> extends infer T extends Entity\n ? TypeMapEntry<T, \"supportsEmExecute\"> extends true\n ? { readonly [K in keyof M]: K extends MutationClause<M> ? unknown : never } & {\n readonly returning?: M extends { readonly returning?: infer R }\n ? CheckReturning<R, NameOf<TargetTable<M>>>\n : never;\n } & (\n | (M extends { readonly values: infer V extends readonly unknown[] }\n ? { readonly values: CheckValues<InsertValues<T>, V> }\n : never)\n | (M extends { readonly from: infer Q extends SetOperand }\n ? { readonly from: CheckInsertSource<T, Q> }\n : never)\n | (M extends { readonly set: infer V }\n ? { readonly set: CheckAssignments<V, UpdateValues<T>, NameOf<TargetTable<M>>> }\n : never)\n | (M extends { readonly delete: unknown } ? unknown : never)\n )\n : \"SQL mutations require a supported non-inherited target and regenerated metadata\"\n : never\n : CheckCustomMutation<M>\n : never;\n\n/** Classifies mutation roots before EntityManager applies write permissions, including malformed roots. */\nexport function isMutation(arg: unknown): boolean {\n return (\n typeof arg === \"object\" &&\n arg !== null &&\n !isReadQueryValue(arg) &&\n [\"insert\", \"update\", \"delete\"].some((key) => key in arg)\n );\n}\n\n/**\n * Compiles one immediate statement using the read compiler's scopes, projections, and codecs.\n * INSERT SELECT keeps source rows in PostgreSQL; only RETURNING rows pass through JS decoders.\n * An undefined plan represents a validated standalone empty VALUES array, not DEFAULT VALUES.\n */\nexport function parseStatement(arg: unknown): Plan | undefined {\n if (!isMutation(arg)) return parseUserQuery(arg);\n const statement = arg as Record<string, unknown>;\n const roots = [\"insert\", \"update\", \"delete\"].filter((key) => key in statement);\n if (roots.length !== 1) fail(\"A mutation requires exactly one insert, update, or delete root\");\n const operation = roots[0];\n const allowed =\n operation === \"insert\"\n ? [\"insert\", \"values\", \"from\", \"returning\", \"with\"]\n : [\n operation,\n \"where\",\n \"allowAll\",\n \"softDeletes\",\n \"returning\",\n \"with\",\n ...(operation === \"update\" ? [\"set\"] : []),\n ];\n checkPojoKeys(statement, allowed, `SQL ${operation}`);\n const target = mutationTarget(statement[operation]);\n const { meta } = target;\n if (meta) {\n if (meta.inheritanceType || meta.baseType || meta.baseTypes.length || meta.subTypes.length) {\n fail(\"SQL mutations do not support CTI/STI targets or inherited table families\");\n }\n if (meta.supportsEmExecute !== true)\n fail(`SQL mutations require supported physical metadata for ${meta.type}; run codegen`);\n // Every column is checked here, so the writable-column lookups below can trust their metadata.\n for (const column of Object.values(meta.columns)) requireColumnMetadata(target, column);\n } else if (statement.softDeletes !== undefined) {\n fail(\"Custom table mutations do not support softDeletes\");\n }\n const fields = Object.entries(target.columns);\n const assigner = new AliasAssigner();\n // A CTE is in scope for the whole statement, so its scope is the parent of every other one here. It\n // deliberately holds no target alias, which is what lets INSERT VALUES cells and the INSERT SELECT\n // source read the CTEs without also seeing the row being written.\n const withCtx = new Ctx(assigner, undefined);\n const ctes = registerCtes(statement, withCtx, assigner);\n // Aliases the rest of the statement reads, so an unread CTE prunes like it does on a read query.\n const refs: string[] = [];\n const ctx = new Ctx(assigner, withCtx);\n const alias = assigner.getAlias(target.mgmt.tableName);\n ctx.register(target.mgmt, alias);\n const returning = statement.returning === undefined ? undefined : projectionToSql(statement.returning, ctx);\n if (returning) for (const select of returning.selects) refs.push(...select.refs);\n let sql = `${operation === \"delete\" ? \"DELETE FROM\" : operation.toUpperCase() + (operation === \"insert\" ? \" INTO\" : \"\")} ${tableSqlName(target.mgmt)} AS ${kq(alias)}`;\n const bindings: unknown[] = [];\n if (operation === \"insert\") {\n if (\"values\" in statement === \"from\" in statement) fail(\"INSERT requires exactly one of values or from\");\n const required = fields.filter(([, column]) => column.insert === \"required\");\n if (\"values\" in statement) {\n if (!Array.isArray(statement.values)) fail(\"INSERT values must be an array of field POJOs\");\n const rows = statement.values;\n // A VALUES cell *is* the new row, so there is no existing row for it to read: this scope skips\n // the `ctx.register(mgmt, alias)` above, so a cell naming the target fails instead of emitting a\n // `b` with no FROM clause. I.e. an UPDATE can say `set: { title: b.title }`; an INSERT cannot.\n // A value subquery still works, because it brings its own sources, and the parent here is the CTE\n // scope rather than `ctx`, so a cell can read a `with` entry but not the row being written.\n const valuesCtx = new Ctx(assigner, withCtx);\n const entries = rows.map((row) => assignments(target, row, \"insert\"));\n for (const row of entries) {\n for (const [key] of required) {\n if (!row.some((entry) => entry[0] === key)) fail(`INSERT requires ${target.name}.${key}`);\n }\n }\n if (rows.length === 0) return undefined;\n const keys = fields\n .filter(([key]) => entries.some((row) => row.some((entry) => entry[0] === key)))\n .map(([key, field]) => [key, field.columnName] as const);\n sql += ` (${keys.map(([, column]) => kq(column)).join(\", \")}) VALUES `;\n sql += entries\n .map((row) => {\n const cells = keys.map(([key]) => {\n const entry = row.find((entry) => entry[0] === key);\n if (!entry) return \"DEFAULT\";\n const cell = assignmentToSql(target, writableField(target, key, \"insert\"), entry[1], valuesCtx);\n bindings.push(...cell.bindings);\n refs.push(...cell.refs);\n return cell.sql;\n });\n return `(${cells.join(\", \")})`;\n })\n .join(\", \");\n } else {\n const source = parseNestedQuery(statement.from, withCtx, assigner);\n if (source.output.kind !== \"pojo\") fail(\"INSERT SELECT requires named POJO output columns\");\n const columns = source.output.columns;\n for (const [key] of required) {\n if (!columns.some((column) => column[0] === key)) {\n fail(`INSERT requires ${target.name}.${key}`);\n }\n }\n for (const [key, expr] of columns) {\n const field = writableField(target, key, \"insert\");\n const left = field.outputType;\n const right = expr.outputType;\n if (\n !left ||\n !right ||\n left.dbType !== right.dbType ||\n left.domain !== right.domain ||\n left.idMeta !== right.idMeta\n ) {\n fail(`INSERT SELECT ${target.name}.${key} has incompatible or unknown storage codecs`);\n }\n if (!field.sqlNullable && expr.sqlNullable === true)\n fail(`INSERT SELECT ${target.name}.${key} cannot accept a nullable output`);\n }\n const keys = fields\n .filter(([key]) => columns.some((column) => column[0] === key))\n .map(([key, field]) => [key, field.columnName] as const);\n const sourceAlias = safeKq(assigner.getLiteralAlias(\"sq\"));\n sql += ` (${keys.map(([, column]) => kq(column)).join(\", \")}) SELECT ${keys.map(([key]) => `${sourceAlias}.${safeKq(key)}`).join(\", \")} FROM (${source.sql}) AS ${sourceAlias}`;\n bindings.push(...source.bindings);\n refs.push(...source.outerRefs);\n }\n } else {\n if (statement.allowAll !== undefined && typeof statement.allowAll !== \"boolean\") fail(\"allowAll must be a boolean\");\n if (\n statement.softDeletes !== undefined &&\n statement.softDeletes !== \"include\" &&\n statement.softDeletes !== \"exclude\"\n )\n fail(\"softDeletes must be 'include' or 'exclude'\");\n const whereCondition = mutationCondition(statement.where, ctx);\n if (Object.hasOwn(statement, \"where\") && !whereCondition && statement.allowAll !== true)\n fail(\"UPDATE and DELETE require allowAll: true when a supplied where is undefined or fully pruned\");\n if (operation === \"update\") {\n const entries = assignments(target, statement.set, \"update\");\n sql +=\n \" SET \" +\n entries\n .map((entry) => {\n const [key, value] = entry;\n const field = writableField(target, key, \"update\");\n const cell = assignmentToSql(target, field, value, ctx);\n bindings.push(...cell.bindings);\n refs.push(...cell.refs);\n return `${kq(field.columnName)} = ${cell.sql}`;\n })\n .join(\", \");\n }\n const injected = meta\n ? conditionToSql({ and: injectedConditions({ meta, alias }, statement.softDeletes ?? \"exclude\") }, ctx, true)\n : undefined;\n const conditions = [whereCondition, injected].filter((condition) => condition !== undefined);\n if (conditions.length) {\n sql += ` WHERE ${conditions.map((condition) => `(${condition.sql})`).join(\" AND \")}`;\n for (const condition of conditions) {\n bindings.push(...condition.bindings);\n refs.push(...condition.refs);\n }\n }\n }\n if (returning) {\n sql += ` RETURNING ${returning.selects.map((select) => select.sql).join(\", \")}`;\n for (const select of returning.selects) bindings.push(...select.bindings);\n }\n const keptCtes = pruneCtes(ctes, new Set(refs));\n if (keptCtes.length > 0) {\n const clause = withFragment(keptCtes);\n sql = clause.sql + sql;\n bindings.unshift(...clause.bindings);\n }\n return {\n sql,\n bindings,\n outerRefs: [],\n output: returning?.output ?? { kind: \"pojo\", columns: [] },\n decodeRows: returning?.decodeRows ?? (() => []),\n };\n}\n\n/** Retains native counts even when no rows return, and propagates decoding failures after execution. */\nexport function decodeStatementResult(\n em: EntityHydrator,\n plan: Plan,\n result: DriverQueryResult,\n): ExecuteResult<unknown> {\n if (typeof result.rowCount !== \"number\" || !Number.isInteger(result.rowCount) || result.rowCount < 0)\n fail(\"The driver did not return a numeric command rowCount\");\n return { rowCount: result.rowCount, rows: plan.decodeRows(em, result.rows) };\n}\n\n/** An entity table whose generated metadata permits direct SQL mutations. */\ntype MutationTargetTable<T extends Entity> = TableFor<T> &\n (TypeMapEntry<T, \"supportsEmExecute\"> extends true ? unknown : never);\n\n/**\n * What a mutation needs from its target, an entity table or a `declareTable` table alike.\n *\n * Both kinds describe their storage with the same `Column`, so the INSERT/UPDATE/DELETE compiler reads\n * `columns` without caring which it has; `meta` is the one thing only an entity table brings.\n */\ninterface MutationTarget {\n /** The SQL identity, for the alias and the qualified table name; also the key `Ctx` registers. */\n mgmt: TableSourceMgmt;\n /** Names the target in errors: the entity type, i.e. `Book`, or the table name, i.e. `book_reviews`. */\n name: string;\n columns: ColumnDescriptors;\n /** Entity tables only; a custom table has no soft-delete, inheritance, or ID-tagging policy. */\n meta: EntityMetadata | undefined;\n}\n\n/** Shared filtering and full-table consent clauses for UPDATE and DELETE. */\ntype MutationFilter = {\n /**\n * An `{ and: [...] }` or `{ or: [...] }` group, a boolean expression, or a bare condition such as `a.age.gte(18)`.\n *\n * Arrays are shorthand for `{ and: [...] }`; undefined conditions are pruned.\n */\n readonly where?: SqlCondition | ExprLike<boolean> | readonly (SqlCondition | undefined)[];\n /** Allows a supplied where to be undefined or fully pruned; unnecessary when where is omitted. */\n readonly allowAll?: boolean;\n readonly softDeletes?: \"include\" | \"exclude\";\n};\n\n/** Read-only query clauses that mutations explicitly reject. */\ntype NoMutationReadClauses = Partial<\n Record<\n | \"select\"\n | \"join\"\n | \"groupBy\"\n | \"having\"\n | \"orderBy\"\n | \"limit\"\n | \"offset\"\n | \"distinct\"\n | \"pruneJoins\"\n | \"as\"\n | \"union\"\n | \"unionAll\"\n | \"intersect\"\n | \"intersectAll\"\n | \"except\"\n | \"exceptAll\"\n | \"ctes\"\n | \"using\"\n | \"onConflict\",\n never\n >\n>;\n\n/** Column keys allowed in INSERT, i.e. Book's optional `id` and required `authorId`. */\ntype InsertKey<T> = {\n [K in keyof ColumnsOf<T>]: ColumnsOf<T>[K] extends { insert: \"required\" | \"optional\" } ? K : never;\n}[keyof ColumnsOf<T>];\n\n/** Column keys that each INSERT row must supply, i.e. Book's `authorId` despite its ORM default. */\ntype RequiredInsertKey<T> = {\n [K in keyof ColumnsOf<T>]: ColumnsOf<T>[K] extends { insert: \"required\" } ? K : never;\n}[keyof ColumnsOf<T>];\n\n/** Column keys allowed in UPDATE SET, i.e. Book's `title` and `authorId`, but not `id`. */\ntype UpdateKey<T> = {\n [K in keyof ColumnsOf<T>]: ColumnsOf<T>[K] extends { update: true } ? K : never;\n}[keyof ColumnsOf<T>];\n\n/** A column's domain value before SQL nullability is added, i.e. Book's `id` is BookId and `authorId` is AuthorId. */\ntype DomainValue<T, K extends keyof ColumnsOf<T>> = K extends \"id\"\n ? IdOf<T>\n : ColumnsOf<T>[K] extends { entity: infer U }\n ? IdOf<U>\n : ColumnsOf<T>[K] extends { type: infer V }\n ? V\n : never;\n\n/** A modeled column's domain value with SQL nullability applied. */\ntype SqlValue<T, K extends keyof ColumnsOf<T>> =\n | DomainValue<T, K>\n | (ColumnsOf<T>[K] extends { nullable: true } ? null : never);\n\n/** A modeled-column value, entity reference, or SQL expression that produces one. */\ntype Assignment<T, K extends keyof ColumnsOf<T>> =\n | SqlValue<T, K>\n | ExprLike<SqlValue<T, K>>\n | (K extends \"id\" ? never : ColumnsOf<T>[K] extends { entity: infer U } ? U : never);\n\n/** A custom column's declared value with SQL nullability applied. */\ntype CustomSqlValue<I> = CustomColumnValue<I> | (I extends { nullable: true } ? null : never);\n\n/** A custom-column value or SQL expression that produces one. */\ntype CustomAssignment<I> = CustomSqlValue<I> | ExprLike<CustomSqlValue<I>>;\n\n/** Custom-column keys accepted by INSERT, excluding generated columns. */\ntype CustomInsertKey<C extends CustomColumnInputs> = {\n [K in keyof C]: C[K] extends { generated: true } ? never : K;\n}[keyof C];\n\n/** Custom-column keys each INSERT row must supply because they have no default and are not nullable. */\ntype CustomRequiredInsertKey<C extends CustomColumnInputs> = {\n [K in CustomInsertKey<C>]: C[K] extends { nullable: true } | { hasDefault: true } ? never : K;\n}[CustomInsertKey<C>];\n\n/** Custom-column keys accepted by UPDATE, excluding generated columns and the physical primary key. */\ntype CustomUpdateKey<C extends CustomColumnInputs> = {\n [K in keyof C]: C[K] extends { generated: true }\n ? never\n : K extends \"id\"\n ? never\n : C[K] extends { columnName: \"id\" }\n ? never\n : K;\n}[keyof C];\n\n/** Values accepted by INSERT for a custom table's declared columns. */\ntype CustomInsertValues<C extends CustomColumnInputs> = {\n [K in CustomRequiredInsertKey<C>]: CustomAssignment<C[K]>;\n} & {\n [K in Exclude<CustomInsertKey<C>, CustomRequiredInsertKey<C>>]?: CustomAssignment<C[K]> | undefined;\n};\n\n/** Assignments accepted by UPDATE for a custom table's writable columns. */\ntype CustomUpdateValues<C extends CustomColumnInputs> = {\n [K in CustomUpdateKey<C>]?: CustomAssignment<C[K]> | undefined;\n};\n\n/** Named row shape that an INSERT SELECT source must produce for a custom table. */\ntype CustomInsertSourceRow<C extends CustomColumnInputs> = {\n [K in CustomRequiredInsertKey<C>]: CustomSqlValue<C[K]>;\n} & {\n [K in Exclude<CustomInsertKey<C>, CustomRequiredInsertKey<C>>]?: CustomSqlValue<C[K]>;\n};\n\n/** Named row shape that an entity INSERT SELECT source must produce. */\ntype InsertSourceRow<T> = { [K in RequiredInsertKey<T>]: SqlValue<T, K> } & {\n [K in Exclude<InsertKey<T>, RequiredInsertKey<T>>]?: SqlValue<T, K>;\n};\n\n/** Named expression projection accepted from an entity INSERT SELECT source. */\ntype InsertProjection<T> = { [K in RequiredInsertKey<T>]: ExprLike<SqlValue<T, K>> } & {\n [K in Exclude<InsertKey<T>, RequiredInsertKey<T>>]?: ExprLike<SqlValue<T, K>>;\n};\n\n/** Collects the keys from every member of a union instead of only their shared keys. */\ntype UnionKeys<V> = V extends unknown ? keyof V : never;\n\n/** Collects every alternative before scope checking; a valid branch cannot hide an unrelated alias. */\ntype UnionValue<V, K extends PropertyKey> = V extends unknown ? (K extends keyof V ? V[K] : never) : never;\n\n/** Extracts the source names carried by a SQL expression. */\ntype ExprSource<V> = V extends { readonly [exprBrand]: ExprBrand<unknown, infer Src> } ? Src : never;\n\n/** Rejects expressions that reference tables outside the statement's allowed scope. */\ntype CheckExprScope<V, Scope> =\n string extends ExprSource<V>\n ? unknown\n : [Exclude<ExprSource<V>, Scope>] extends [never]\n ? unknown\n : \"Expression source is not in the statement scope\";\n\n/** Extracts each expression from a scalar or named RETURNING projection. */\ntype ReturningExpr<R> = R extends ExprLike<unknown> ? R : R extends undefined ? never : R[keyof R];\n\n/** Detects an empty named RETURNING projection. */\ntype EmptyReturning<R> = R extends object ? (keyof R extends never ? true : false) : false;\n\n/** Rejects empty RETURNING objects and expressions outside the target scope. */\ntype CheckReturning<R, Scope> = true extends EmptyReturning<R> ? never : CheckExprScope<ReturningExpr<R>, Scope>;\n\n/** Validates assignment keys, values, and expression sources without distributing union inputs. */\ntype CheckAssignments<V, Allowed, Scope> = [Exclude<UnionKeys<V>, keyof Allowed>] extends [never]\n ? Allowed & {\n [K in UnionKeys<V>]?: CheckExprScope<UnionValue<V, K>, Scope>;\n }\n : \"SQL assignments have unknown target fields\";\n\n/**\n * Checks every INSERT row in a readonly collection against the target's writable columns.\n *\n * `Allowed` is the target's accepted assignments, i.e. `InsertValues<T>` for an entity table and\n * `CustomInsertValues<C>` for a declared one. The scope is `never` because a VALUES cell cannot read\n * the row being written.\n */\ntype CheckValues<Allowed, V extends readonly unknown[]> = readonly CheckAssignments<V[number], Allowed, never>[];\n\n/**\n * Checks a custom-table mutation against its declared primitive columns.\n *\n * Only clauses for the selected operation are allowed, and `softDeletes` is rejected because there is no entity\n * policy. Assignments use declaration keys and honor nullability, defaults, and generated columns. INSERT VALUES\n * cannot read the target row, while UPDATE SET and RETURNING can. INSERT SELECT must be a valid named read with all\n * required columns and compatible declared value types; runtime checks also compare its SQL codecs and nullability.\n */\ntype CheckCustomMutation<M> = {\n // Reject clauses outside the selected operation, plus softDeletes because custom tables have no entity policy.\n readonly [K in keyof M]: K extends MutationClause<M> ? (K extends \"softDeletes\" ? never : unknown) : never;\n} & {\n readonly returning?: M extends { readonly returning?: infer R } ? CheckReturning<R, NameOf<TargetTable<M>>> : never;\n} &\n // INSERT VALUES checks every row against the custom table's writable columns.\n (\n | (M extends { readonly values: infer V extends readonly unknown[] }\n ? { readonly values: CheckValues<CustomInsertValues<CustomColumnsOf<TargetTable<M>>>, V> }\n : never)\n // INSERT SELECT checks the source's names, values, and expression scopes.\n | (M extends { readonly from: infer Q extends SetOperand }\n ? { readonly from: CheckCustomInsertSource<CustomColumnsOf<TargetTable<M>>, Q> }\n : never)\n // UPDATE checks assignments against writable columns and permits target-scoped expressions.\n | (M extends { readonly set: infer V }\n ? {\n readonly set: CheckAssignments<\n V,\n CustomUpdateValues<CustomColumnsOf<TargetTable<M>>>,\n NameOf<TargetTable<M>>\n >;\n }\n : never)\n // DELETE has no assignments or source that needs further type checking.\n | (M extends { readonly delete: unknown } ? unknown : never)\n );\n\n/**\n * Checks an INSERT SELECT's named outputs, required columns, values, and read source.\n *\n * `Row` is the row shape the source must produce and `Keys` the target's writable column keys, i.e.\n * `InsertSourceRow<T>` and `InsertKey<T>` for an entity table.\n */\ntype CheckInsertSourceOf<Row, Keys extends PropertyKey, Q> = SetOperand extends Q\n ? \"INSERT source type lost its select keys; use `satisfies Query` or `satisfies SetQuery` instead of a type annotation\"\n : ReadQueryRow<Q> extends Row\n ? Exclude<UnionKeys<ReadQueryRow<Q>>, Keys> extends never\n ? CheckReadQuery<Q> &\n CheckSourceScope<Q> &\n (Q extends SetQuery<readonly SetOperand[]> ? CheckSetQuery<Q> : unknown)\n : \"INSERT SELECT has unknown target fields\"\n : \"INSERT SELECT requires compatible values for all SQL-required fields\";\n\n/** Checks a custom INSERT SELECT against the table's declared writable columns. */\ntype CheckCustomInsertSource<C extends CustomColumnInputs, Q> = CheckInsertSourceOf<\n CustomInsertSourceRow<C>,\n CustomInsertKey<C>,\n Q\n>;\n\n/** Checks every SELECT expression against the tables visible within its read-query branch. */\ntype CheckSourceScope<Q> = Q extends { readonly select: infer S; readonly from: infer F }\n ? CheckScope<S, F, \"join\" extends keyof Q ? Extract<Q[keyof Q & \"join\"], QueryJoinInput> : []>\n : {\n [K in keyof Q]: K extends SetOperation\n ? Q[K] extends readonly unknown[]\n ? { [I in keyof Q[K]]: CheckSourceScope<Q[K][I]> }\n : unknown\n : unknown;\n };\n\n/** Checks an entity INSERT SELECT against the entity's writable columns. */\ntype CheckInsertSource<T, Q extends SetOperand> = CheckInsertSourceOf<InsertSourceRow<T>, InsertKey<T>, Q>;\n\n/** Extracts the entity type from any mutation target clause. */\ntype TargetEntity<M> = M extends\n | { readonly insert: TableFor<infer T> }\n | { readonly update: TableFor<infer T> }\n | { readonly delete: TableFor<infer T> }\n ? T\n : never;\n\n/** Extracts the table handle from any mutation target clause. */\ntype TargetTable<M> = M extends\n | { readonly insert: infer A }\n | { readonly update: infer A }\n | { readonly delete: infer A }\n ? A\n : never;\n\n/** Clauses permitted by the selected INSERT, UPDATE, or DELETE operation. */\ntype MutationClause<M> =\n | \"returning\"\n | \"with\"\n | (M extends { readonly insert: unknown }\n ? \"insert\" | (M extends { readonly values: unknown } ? \"values\" : \"from\")\n : \"where\" | \"allowAll\" | \"softDeletes\" | (M extends { readonly update: unknown } ? \"update\" | \"set\" : \"delete\"));\n\n/** Reads the writable columns from either kind of table handle, so the compiler has one target shape. */\nfunction mutationTarget(target: unknown): MutationTarget {\n if (isEntityTable(target)) {\n const mgmt = getTableMgmt(target);\n return { mgmt, name: mgmt.meta.type, columns: mgmt.meta.columns, meta: mgmt.meta };\n }\n if (isCustomTable(target)) {\n const mgmt = getTableMgmt(target);\n return { mgmt, name: mgmt.tableName, columns: mgmt.columns, meta: undefined };\n }\n return fail(\"A mutation target must be a table\");\n}\n\n/** SQL mutations require complete physical metadata. */\nfunction requireColumnMetadata(target: MutationTarget, column: Column): void {\n if (\n typeof column.sqlNullable !== \"boolean\" ||\n typeof column.hasDefault !== \"boolean\" ||\n typeof column.isGenerated !== \"boolean\"\n )\n fail(`Missing physical metadata for ${target.name}.${column.columnName}; run codegen`);\n}\n\n/** Validates every supplied key, including undefined fields, before pruning omitted values. */\nfunction assignments(target: MutationTarget, value: unknown, operation: \"insert\" | \"update\"): [string, unknown][] {\n if (!value || typeof value !== \"object\" || Array.isArray(value) || isExpr(value) || isEntity(value))\n fail(`${operation} assignments must be a field POJO`);\n const entries = Object.entries(value);\n for (const [key] of entries) writableField(target, key, operation);\n checkPojoKeys(value, Object.keys(target.columns), `${operation} assignments`);\n const defined = entries.filter((entry) => entry[1] !== undefined);\n if (!defined.length) fail(`${operation} requires at least one defined field; empty rows/sets are not DEFAULT VALUES`);\n return defined;\n}\n\n/**\n * Applies physical write restrictions, not ORM-derived, protected, or business-immutable flags.\n *\n * The primary-key and generated checks only sharpen the message: `Column` already denies both through\n * `insert: \"never\"` and `update: false`, for declared custom columns as well as generated ones.\n */\nfunction writableField(target: MutationTarget, key: string, operation: \"insert\" | \"update\"): Column {\n const column = Object.hasOwn(target.columns, key) ? target.columns[key] : undefined;\n if (!column) fail(`Unsupported SQL mutation field ${target.name}.${key}`);\n if (operation === \"update\" && column.columnName === \"id\") fail(\"UPDATE primary-key assignments are not supported\");\n if (column.isGenerated) fail(`Generated field ${target.name}.${key} is omit-only`);\n if (operation === \"update\" ? !column.update : column.insert === \"never\")\n fail(`Unsupported SQL mutation field ${target.name}.${key}`);\n return column;\n}\n\n/**\n * Classifies SQL expressions and SQL NULL before invoking the column's entity-independent write codec.\n * Normalizes public PK/FK ids to internal tagged ids using the target entity's idType.\n *\n * A custom table's columns never carry `idMetadata`, so they take the literal path below unchanged.\n */\nfunction assignmentToSql(target: MutationTarget, column: Column, value: unknown, ctx: Ctx): SqlFragment {\n if (isExpr(value)) return asNode(value).toSql(ctx);\n if (value === null) {\n if (!column.sqlNullable) fail(`${target.name}.${column.columnName} is physically NOT NULL`);\n return { sql: \"NULL\", bindings: [], refs: [] };\n }\n if (column.idMetadata) {\n const other = column.idMetadata();\n if (isEntity(value)) {\n if (column.columnName === \"id\" || !(value instanceof other.cstr)) fail(`Expected a ${other.type} reference`);\n if (value.isNewEntity || value.idTaggedMaybe === undefined)\n fail(`Cannot reference an unflushed ${other.type}, even with an assigned ID`);\n value = value.idTaggedMaybe;\n } else if (typeof value !== (other.idType === \"number\" ? \"number\" : \"string\")) {\n fail(`Expected a persisted ${other.type} or its ID; nested creation is not supported`);\n } else {\n // Public untagged TEXT ids may contain delimiters or start with the entity tag.\n value =\n other.idType === \"untagged-string\"\n ? keyToTaggedId(other, value as string)\n : toTaggedId(other, value as string | number);\n }\n }\n if (!column.codec.mapToDbValue)\n fail(`The codec for ${target.name}.${column.columnName} does not support SQL value writes`);\n return { sql: \"?\", bindings: [column.mapToDbValue(value)], refs: [] };\n}\n\n/** Checks the user predicate independently so metadata filters cannot turn a pruned guard into consent. */\nfunction mutationCondition(value: unknown, ctx: Ctx): SqlFragment | undefined {\n if (isExpr(value)) return asNode(value).toSql(ctx);\n if (Array.isArray(value)) return conditionToSql({ and: value }, ctx, true);\n return conditionToSql(value as SqlCondition | undefined, ctx, true);\n}\n"],"mappings":";;;;;;;;;;;;AAqMA,SAAgB,WAAW,KAAuB;CAChD,OACE,OAAO,QAAQ,YACf,QAAQ,QACR,CAACA,0BAAAA,iBAAiB,GAAG,KACrB;EAAC;EAAU;EAAU;CAAQ,CAAC,CAAC,MAAM,QAAQ,OAAO,GAAG;AAE3D;;;;;;AAOA,SAAgB,eAAe,KAAgC;CAC7D,IAAI,CAAC,WAAW,GAAG,GAAG,OAAOC,0BAAAA,eAAe,GAAG;CAC/C,MAAM,YAAY;CAClB,MAAM,QAAQ;EAAC;EAAU;EAAU;CAAQ,CAAC,CAAC,QAAQ,QAAQ,OAAO,SAAS;CAC7E,IAAI,MAAM,WAAW,GAAG,cAAA,KAAK,gEAAgE;CAC7F,MAAM,YAAY,MAAM;CACxB,MAAM,UACJ,cAAc,WAC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"execute.cjs","names":["isReadQueryValue","parseUserQuery","AliasAssigner","Ctx","registerCtes","projectionToSql","tableSqlName","kq","parseNestedQuery","safeKq","conditionToSql","injectedConditions","prependCtes","isEntityTable","getTableMgmt","isCustomTable","fail","isExpr","isEntity","asNode","keyToTaggedId","toTaggedId"],"sources":["../../../src/queries/sql/execute.ts"],"sourcesContent":["import type { DriverQueryResult } from \"src/drivers/Driver.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport type { IdOf } from \"src/EntityManager.ts\";\nimport type { EntityMetadata } from \"src/EntityMetadata.ts\";\nimport { keyToTaggedId, toTaggedId } from \"src/keys.ts\";\nimport type { SqlCondition } from \"src/queries/conditions.ts\";\nimport { AliasAssigner } from \"src/queries/sql/AliasAssigner.ts\";\nimport {\n type CustomColumnInputs,\n type CustomColumnValue,\n type CustomColumnsOf,\n type CustomTableFor,\n} from \"src/queries/sql/custom.ts\";\nimport { type ExprBrand, type ExprLike, type SqlFragment, asNode, exprBrand, isExpr } from \"src/queries/sql/Expr.ts\";\nimport { kq, safeKq } from \"src/queries/sql/keywords.ts\";\nimport {\n type CheckReadQuery,\n type CheckScope,\n type CheckSetQuery,\n Ctx,\n type EntityHydrator,\n type NameOf,\n type Plan,\n type Query,\n type QueryJoinInput,\n type QueryRow,\n type ReadQueryRow,\n type SetOperand,\n type SetOperation,\n type SetQuery,\n type Subquery,\n type WithInput,\n checkPojoKeys,\n conditionToSql,\n entityQueryBrand,\n injectedConditions,\n isReadQueryValue,\n parseNestedQuery,\n parseUserQuery,\n prependCtes,\n projectionToSql,\n registerCtes,\n subqueryBrand,\n} from \"src/queries/sql/query.ts\";\nimport {\n type TableFor,\n type TableSourceMgmt,\n getTableMgmt,\n isCustomTable,\n isEntityTable,\n tableMgmt,\n tableSqlName,\n} from \"src/queries/sql/Tables.ts\";\nimport type { Column, ColumnDescriptors } from \"src/serde/columns.ts\";\nimport type { ColumnsOf, TypeMapEntry } from \"src/typeMap.ts\";\nimport { fail } from \"src/utils.ts\";\n\n/** The native command count and decoded rows from one immediate SQL statement. */\nexport interface ExecuteResult<R> {\n rowCount: number;\n rows: R[];\n}\n\n/** A mutation's RETURNING projection: one SQL expression or a named object of expressions. */\nexport type MutationReturning = (ExprLike<unknown> | Readonly<Record<string, ExprLike<unknown>>>) & {\n readonly [tableMgmt]?: never;\n readonly [subqueryBrand]?: never;\n readonly [entityQueryBrand]?: never;\n};\n\n/** SQL INSERT inputs, based on physical storage rather than entity creation options. */\nexport type InsertValues<T extends Entity> = {\n [K in RequiredInsertKey<T>]: Assignment<T, K>;\n} & {\n [K in Exclude<InsertKey<T>, RequiredInsertKey<T>>]?: Assignment<T, K> | undefined;\n};\n\n/** SQL UPDATE inputs include persisted derived columns, but never primary keys. */\nexport type UpdateValues<T extends Entity> = {\n [K in UpdateKey<T>]?: Assignment<T, K> | undefined;\n};\n\n/** A reusable INSERT POJO; use a concrete Q for annotated INSERT SELECT source checking. */\nexport type InsertStatement<\n T extends Entity,\n R extends MutationReturning | undefined = MutationReturning | undefined,\n Q extends SetOperand = Query<InsertProjection<T>, []> | Subquery<InsertSourceRow<T>, string>,\n> = {\n readonly insert: MutationTargetTable<T>;\n readonly returning?: R;\n readonly update?: never;\n readonly delete?: never;\n readonly set?: never;\n readonly where?: never;\n readonly allowAll?: never;\n readonly softDeletes?: never;\n /** CTEs to add to a `WITH` before the INSERT; see `Clauses.with`. */\n readonly with?: WithInput;\n} & NoMutationReadClauses &\n (\n | { readonly values: readonly InsertValues<T>[]; readonly from?: never }\n | { readonly from: Q & CheckInsertSource<T, Q>; readonly values?: never }\n );\n\n/** A reusable guarded UPDATE POJO. Undefined assignments leave existing columns unchanged. */\nexport type UpdateStatement<\n T extends Entity,\n R extends MutationReturning | undefined = MutationReturning | undefined,\n> = {\n readonly update: MutationTargetTable<T>;\n readonly set: UpdateValues<T>;\n readonly returning?: R;\n readonly insert?: never;\n readonly delete?: never;\n readonly values?: never;\n readonly from?: never;\n /** CTEs to add to a `WITH` before the UPDATE; see `Clauses.with`. */\n readonly with?: WithInput;\n} & MutationFilter &\n NoMutationReadClauses;\n\n/** A reusable guarded physical DELETE POJO, not an ORM soft delete. */\nexport type DeleteStatement<\n T extends Entity,\n R extends MutationReturning | undefined = MutationReturning | undefined,\n> = {\n readonly delete: MutationTargetTable<T>;\n readonly returning?: R;\n readonly insert?: never;\n readonly update?: never;\n readonly values?: never;\n readonly from?: never;\n readonly set?: never;\n /** CTEs to add to a `WITH` before the DELETE; see `Clauses.with`. */\n readonly with?: WithInput;\n} & MutationFilter &\n NoMutationReadClauses;\n\n/** Public statement annotations retain the target's physical field policy. */\nexport type MutationStatement<\n T extends Entity,\n R extends MutationReturning | undefined = MutationReturning | undefined,\n> = InsertStatement<T, R> | UpdateStatement<T, R> | DeleteStatement<T, R>;\n\n/** Inference starts with the literal POJO; CheckMutation checks its target and every supplied key. */\nexport type MutationInput = (\n | { readonly insert: TableFor<Entity>; readonly values: readonly object[]; readonly from?: never }\n | { readonly insert: TableFor<Entity>; readonly from: SetOperand; readonly values?: never }\n | { readonly update: TableFor<Entity>; readonly set: object }\n | { readonly delete: TableFor<Entity> }\n | {\n readonly insert: CustomTableFor;\n readonly values: readonly object[];\n readonly from?: never;\n }\n | { readonly insert: CustomTableFor; readonly from: SetOperand; readonly values?: never }\n | { readonly update: CustomTableFor; readonly set: object }\n | { readonly delete: CustomTableFor }\n) & { readonly returning?: MutationReturning; readonly with?: WithInput } & MutationFilter;\n\n/** Without RETURNING the row type is never; scalar expressions produce scalar rows. */\nexport type MutationRow<M> = M extends { readonly returning?: infer R }\n ? R extends MutationReturning\n ? R extends ExprLike<unknown>\n ? QueryRow<R>\n : { -readonly [K in keyof QueryRow<R>]: QueryRow<R>[K] }\n : never\n : never;\n\n/** Checks nonliteral statements as well as fresh literals without widening their inferred result. */\nexport type CheckMutation<M> = M extends unknown\n ? [CustomColumnsOf<TargetTable<M>>] extends [never]\n ? TargetEntity<M> extends infer T extends Entity\n ? TypeMapEntry<T, \"supportsEmExecute\"> extends true\n ? { readonly [K in keyof M]: K extends MutationClause<M> ? unknown : never } & {\n readonly returning?: M extends { readonly returning?: infer R }\n ? CheckReturning<R, NameOf<TargetTable<M>>>\n : never;\n } & (\n | (M extends { readonly values: infer V extends readonly unknown[] }\n ? { readonly values: CheckValues<InsertValues<T>, V> }\n : never)\n | (M extends { readonly from: infer Q extends SetOperand }\n ? { readonly from: CheckInsertSource<T, Q> }\n : never)\n | (M extends { readonly set: infer V }\n ? { readonly set: CheckAssignments<V, UpdateValues<T>, NameOf<TargetTable<M>>> }\n : never)\n | (M extends { readonly delete: unknown } ? unknown : never)\n )\n : \"SQL mutations require a supported non-inherited target and regenerated metadata\"\n : never\n : CheckCustomMutation<M>\n : never;\n\n/** Classifies mutation roots before EntityManager applies write permissions, including malformed roots. */\nexport function isMutation(arg: unknown): boolean {\n return (\n typeof arg === \"object\" &&\n arg !== null &&\n !isReadQueryValue(arg) &&\n [\"insert\", \"update\", \"delete\"].some((key) => key in arg)\n );\n}\n\n/**\n * Compiles one immediate statement using the read compiler's scopes, projections, and codecs.\n * INSERT SELECT keeps source rows in PostgreSQL; only RETURNING rows pass through JS decoders.\n * An undefined plan represents a validated standalone empty VALUES array, not DEFAULT VALUES.\n */\nexport function parseStatement(arg: unknown): Plan | undefined {\n if (!isMutation(arg)) return parseUserQuery(arg);\n const statement = arg as Record<string, unknown>;\n const roots = [\"insert\", \"update\", \"delete\"].filter((key) => key in statement);\n if (roots.length !== 1) fail(\"A mutation requires exactly one insert, update, or delete root\");\n const operation = roots[0];\n const allowed =\n operation === \"insert\"\n ? [\"insert\", \"values\", \"from\", \"returning\", \"with\"]\n : [\n operation,\n \"where\",\n \"allowAll\",\n \"softDeletes\",\n \"returning\",\n \"with\",\n ...(operation === \"update\" ? [\"set\"] : []),\n ];\n checkPojoKeys(statement, allowed, `SQL ${operation}`);\n const target = mutationTarget(statement[operation]);\n const { meta } = target;\n if (meta) {\n if (meta.inheritanceType || meta.baseType || meta.baseTypes.length || meta.subTypes.length) {\n fail(\"SQL mutations do not support CTI/STI targets or inherited table families\");\n }\n if (meta.supportsEmExecute !== true)\n fail(`SQL mutations require supported physical metadata for ${meta.type}; run codegen`);\n // Every column is checked here, so the writable-column lookups below can trust their metadata.\n for (const column of Object.values(meta.columns)) requireColumnMetadata(target, column);\n } else if (statement.softDeletes !== undefined) {\n fail(\"Custom table mutations do not support softDeletes\");\n }\n const fields = Object.entries(target.columns);\n const assigner = new AliasAssigner();\n // A CTE is in scope for the whole statement, so its scope is the parent of every other one here. It\n // deliberately holds no target alias, which is what lets INSERT VALUES cells and the INSERT SELECT\n // source read the CTEs without also seeing the row being written.\n const withCtx = new Ctx(assigner, undefined);\n const ctes = registerCtes(statement, withCtx, assigner);\n // Aliases the rest of the statement reads, so an unread CTE prunes like it does on a read query.\n const refs: string[] = [];\n const ctx = new Ctx(assigner, withCtx);\n const alias = assigner.getAlias(target.mgmt.tableName);\n ctx.register(target.mgmt, alias);\n const returning = statement.returning === undefined ? undefined : projectionToSql(statement.returning, ctx);\n if (returning) for (const select of returning.selects) refs.push(...select.refs);\n let sql = `${operation === \"delete\" ? \"DELETE FROM\" : operation.toUpperCase() + (operation === \"insert\" ? \" INTO\" : \"\")} ${tableSqlName(target.mgmt)} AS ${kq(alias)}`;\n const bindings: unknown[] = [];\n if (operation === \"insert\") {\n if (\"values\" in statement === \"from\" in statement) fail(\"INSERT requires exactly one of values or from\");\n const required = fields.filter(([, column]) => column.insert === \"required\");\n if (\"values\" in statement) {\n if (!Array.isArray(statement.values)) fail(\"INSERT values must be an array of field POJOs\");\n const rows = statement.values;\n // A VALUES cell *is* the new row, so there is no existing row for it to read: this scope skips\n // the `ctx.register(mgmt, alias)` above, so a cell naming the target fails instead of emitting a\n // `b` with no FROM clause. I.e. an UPDATE can say `set: { title: b.title }`; an INSERT cannot.\n // A value subquery still works, because it brings its own sources, and the parent here is the CTE\n // scope rather than `ctx`, so a cell can read a `with` entry but not the row being written.\n const valuesCtx = new Ctx(assigner, withCtx);\n const entries = rows.map((row) => assignments(target, row, \"insert\"));\n for (const row of entries) {\n for (const [key] of required) {\n if (!row.some((entry) => entry[0] === key)) fail(`INSERT requires ${target.name}.${key}`);\n }\n }\n if (rows.length === 0) return undefined;\n const keys = fields\n .filter(([key]) => entries.some((row) => row.some((entry) => entry[0] === key)))\n .map(([key, field]) => [key, field.columnName] as const);\n sql += ` (${keys.map(([, column]) => kq(column)).join(\", \")}) VALUES `;\n sql += entries\n .map((row) => {\n const cells = keys.map(([key]) => {\n const entry = row.find((entry) => entry[0] === key);\n if (!entry) return \"DEFAULT\";\n const cell = assignmentToSql(target, writableField(target, key, \"insert\"), entry[1], valuesCtx);\n bindings.push(...cell.bindings);\n refs.push(...cell.refs);\n return cell.sql;\n });\n return `(${cells.join(\", \")})`;\n })\n .join(\", \");\n } else {\n const source = parseNestedQuery(statement.from, withCtx, assigner);\n if (source.output.kind !== \"pojo\") fail(\"INSERT SELECT requires named POJO output columns\");\n const columns = source.output.columns;\n for (const [key] of required) {\n if (!columns.some((column) => column[0] === key)) {\n fail(`INSERT requires ${target.name}.${key}`);\n }\n }\n for (const [key, expr] of columns) {\n const field = writableField(target, key, \"insert\");\n const left = field.outputType;\n const right = expr.outputType;\n if (\n !left ||\n !right ||\n left.dbType !== right.dbType ||\n left.domain !== right.domain ||\n left.idMeta !== right.idMeta\n ) {\n fail(`INSERT SELECT ${target.name}.${key} has incompatible or unknown storage codecs`);\n }\n if (!field.sqlNullable && expr.sqlNullable === true)\n fail(`INSERT SELECT ${target.name}.${key} cannot accept a nullable output`);\n }\n const keys = fields\n .filter(([key]) => columns.some((column) => column[0] === key))\n .map(([key, field]) => [key, field.columnName] as const);\n const sourceAlias = safeKq(assigner.getLiteralAlias(\"sq\"));\n sql += ` (${keys.map(([, column]) => kq(column)).join(\", \")}) SELECT ${keys.map(([key]) => `${sourceAlias}.${safeKq(key)}`).join(\", \")} FROM (${source.sql}) AS ${sourceAlias}`;\n bindings.push(...source.bindings);\n refs.push(...source.outerRefs);\n }\n } else {\n if (statement.allowAll !== undefined && typeof statement.allowAll !== \"boolean\") fail(\"allowAll must be a boolean\");\n if (\n statement.softDeletes !== undefined &&\n statement.softDeletes !== \"include\" &&\n statement.softDeletes !== \"exclude\"\n )\n fail(\"softDeletes must be 'include' or 'exclude'\");\n const whereCondition = mutationCondition(statement.where, ctx);\n if (Object.hasOwn(statement, \"where\") && !whereCondition && statement.allowAll !== true)\n fail(\"UPDATE and DELETE require allowAll: true when a supplied where is undefined or fully pruned\");\n if (operation === \"update\") {\n const entries = assignments(target, statement.set, \"update\");\n sql +=\n \" SET \" +\n entries\n .map((entry) => {\n const [key, value] = entry;\n const field = writableField(target, key, \"update\");\n const cell = assignmentToSql(target, field, value, ctx);\n bindings.push(...cell.bindings);\n refs.push(...cell.refs);\n return `${kq(field.columnName)} = ${cell.sql}`;\n })\n .join(\", \");\n }\n const injected = meta\n ? conditionToSql({ and: injectedConditions({ meta, alias }, statement.softDeletes ?? \"exclude\") }, ctx, true)\n : undefined;\n const conditions = [whereCondition, injected].filter((condition) => condition !== undefined);\n if (conditions.length) {\n sql += ` WHERE ${conditions.map((condition) => `(${condition.sql})`).join(\" AND \")}`;\n for (const condition of conditions) {\n bindings.push(...condition.bindings);\n refs.push(...condition.refs);\n }\n }\n }\n if (returning) {\n sql += ` RETURNING ${returning.selects.map((select) => select.sql).join(\", \")}`;\n for (const select of returning.selects) bindings.push(...select.bindings);\n }\n const withCtes = prependCtes(ctes, new Set(refs), sql, bindings);\n return {\n sql: withCtes.sql,\n bindings: withCtes.bindings,\n outerRefs: [],\n output: returning?.output ?? { kind: \"pojo\", columns: [] },\n decodeRows: returning?.decodeRows ?? (() => []),\n };\n}\n\n/** Retains native counts even when no rows return, and propagates decoding failures after execution. */\nexport function decodeStatementResult(\n em: EntityHydrator,\n plan: Plan,\n result: DriverQueryResult,\n): ExecuteResult<unknown> {\n if (typeof result.rowCount !== \"number\" || !Number.isInteger(result.rowCount) || result.rowCount < 0)\n fail(\"The driver did not return a numeric command rowCount\");\n return { rowCount: result.rowCount, rows: plan.decodeRows(em, result.rows) };\n}\n\n/** An entity table whose generated metadata permits direct SQL mutations. */\ntype MutationTargetTable<T extends Entity> = TableFor<T> &\n (TypeMapEntry<T, \"supportsEmExecute\"> extends true ? unknown : never);\n\n/**\n * What a mutation needs from its target, an entity table or a `declareTable` table alike.\n *\n * Both kinds describe their storage with the same `Column`, so the INSERT/UPDATE/DELETE compiler reads\n * `columns` without caring which it has; `meta` is the one thing only an entity table brings.\n */\ninterface MutationTarget {\n /** The SQL identity, for the alias and the qualified table name; also the key `Ctx` registers. */\n mgmt: TableSourceMgmt;\n /** Names the target in errors: the entity type, i.e. `Book`, or the table name, i.e. `book_reviews`. */\n name: string;\n columns: ColumnDescriptors;\n /** Entity tables only; a custom table has no soft-delete, inheritance, or ID-tagging policy. */\n meta: EntityMetadata | undefined;\n}\n\n/** Shared filtering and full-table consent clauses for UPDATE and DELETE. */\ntype MutationFilter = {\n /**\n * An `{ and: [...] }` or `{ or: [...] }` group, a boolean expression, or a bare condition such as `a.age.gte(18)`.\n *\n * Arrays are shorthand for `{ and: [...] }`; undefined conditions are pruned.\n */\n readonly where?: SqlCondition | ExprLike<boolean> | readonly (SqlCondition | undefined)[];\n /** Allows a supplied where to be undefined or fully pruned; unnecessary when where is omitted. */\n readonly allowAll?: boolean;\n readonly softDeletes?: \"include\" | \"exclude\";\n};\n\n/** Read-only query clauses that mutations explicitly reject. */\ntype NoMutationReadClauses = Partial<\n Record<\n | \"select\"\n | \"join\"\n | \"groupBy\"\n | \"having\"\n | \"orderBy\"\n | \"limit\"\n | \"offset\"\n | \"distinct\"\n | \"pruneJoins\"\n | \"as\"\n | \"union\"\n | \"unionAll\"\n | \"intersect\"\n | \"intersectAll\"\n | \"except\"\n | \"exceptAll\"\n | \"ctes\"\n | \"using\"\n | \"onConflict\",\n never\n >\n>;\n\n/** Column keys allowed in INSERT, i.e. Book's optional `id` and required `authorId`. */\ntype InsertKey<T> = {\n [K in keyof ColumnsOf<T>]: ColumnsOf<T>[K] extends { insert: \"required\" | \"optional\" } ? K : never;\n}[keyof ColumnsOf<T>];\n\n/** Column keys that each INSERT row must supply, i.e. Book's `authorId` despite its ORM default. */\ntype RequiredInsertKey<T> = {\n [K in keyof ColumnsOf<T>]: ColumnsOf<T>[K] extends { insert: \"required\" } ? K : never;\n}[keyof ColumnsOf<T>];\n\n/** Column keys allowed in UPDATE SET, i.e. Book's `title` and `authorId`, but not `id`. */\ntype UpdateKey<T> = {\n [K in keyof ColumnsOf<T>]: ColumnsOf<T>[K] extends { update: true } ? K : never;\n}[keyof ColumnsOf<T>];\n\n/** A column's domain value before SQL nullability is added, i.e. Book's `id` is BookId and `authorId` is AuthorId. */\ntype DomainValue<T, K extends keyof ColumnsOf<T>> = K extends \"id\"\n ? IdOf<T>\n : ColumnsOf<T>[K] extends { entity: infer U }\n ? IdOf<U>\n : ColumnsOf<T>[K] extends { type: infer V }\n ? V\n : never;\n\n/** A modeled column's domain value with SQL nullability applied. */\ntype SqlValue<T, K extends keyof ColumnsOf<T>> =\n | DomainValue<T, K>\n | (ColumnsOf<T>[K] extends { nullable: true } ? null : never);\n\n/** A modeled-column value, entity reference, or SQL expression that produces one. */\ntype Assignment<T, K extends keyof ColumnsOf<T>> =\n | SqlValue<T, K>\n | ExprLike<SqlValue<T, K>>\n | (K extends \"id\" ? never : ColumnsOf<T>[K] extends { entity: infer U } ? U : never);\n\n/** A custom column's declared value with SQL nullability applied. */\ntype CustomSqlValue<I> = CustomColumnValue<I> | (I extends { nullable: true } ? null : never);\n\n/** A custom-column value or SQL expression that produces one. */\ntype CustomAssignment<I> = CustomSqlValue<I> | ExprLike<CustomSqlValue<I>>;\n\n/** Custom-column keys accepted by INSERT, excluding generated columns. */\ntype CustomInsertKey<C extends CustomColumnInputs> = {\n [K in keyof C]: C[K] extends { generated: true } ? never : K;\n}[keyof C];\n\n/** Custom-column keys each INSERT row must supply because they have no default and are not nullable. */\ntype CustomRequiredInsertKey<C extends CustomColumnInputs> = {\n [K in CustomInsertKey<C>]: C[K] extends { nullable: true } | { hasDefault: true } ? never : K;\n}[CustomInsertKey<C>];\n\n/** Custom-column keys accepted by UPDATE, excluding generated columns and the physical primary key. */\ntype CustomUpdateKey<C extends CustomColumnInputs> = {\n [K in keyof C]: C[K] extends { generated: true }\n ? never\n : K extends \"id\"\n ? never\n : C[K] extends { columnName: \"id\" }\n ? never\n : K;\n}[keyof C];\n\n/** Values accepted by INSERT for a custom table's declared columns. */\ntype CustomInsertValues<C extends CustomColumnInputs> = {\n [K in CustomRequiredInsertKey<C>]: CustomAssignment<C[K]>;\n} & {\n [K in Exclude<CustomInsertKey<C>, CustomRequiredInsertKey<C>>]?: CustomAssignment<C[K]> | undefined;\n};\n\n/** Assignments accepted by UPDATE for a custom table's writable columns. */\ntype CustomUpdateValues<C extends CustomColumnInputs> = {\n [K in CustomUpdateKey<C>]?: CustomAssignment<C[K]> | undefined;\n};\n\n/** Named row shape that an INSERT SELECT source must produce for a custom table. */\ntype CustomInsertSourceRow<C extends CustomColumnInputs> = {\n [K in CustomRequiredInsertKey<C>]: CustomSqlValue<C[K]>;\n} & {\n [K in Exclude<CustomInsertKey<C>, CustomRequiredInsertKey<C>>]?: CustomSqlValue<C[K]>;\n};\n\n/** Named row shape that an entity INSERT SELECT source must produce. */\ntype InsertSourceRow<T> = { [K in RequiredInsertKey<T>]: SqlValue<T, K> } & {\n [K in Exclude<InsertKey<T>, RequiredInsertKey<T>>]?: SqlValue<T, K>;\n};\n\n/** Named expression projection accepted from an entity INSERT SELECT source. */\ntype InsertProjection<T> = { [K in RequiredInsertKey<T>]: ExprLike<SqlValue<T, K>> } & {\n [K in Exclude<InsertKey<T>, RequiredInsertKey<T>>]?: ExprLike<SqlValue<T, K>>;\n};\n\n/** Collects the keys from every member of a union instead of only their shared keys. */\ntype UnionKeys<V> = V extends unknown ? keyof V : never;\n\n/** Collects every alternative before scope checking; a valid branch cannot hide an unrelated alias. */\ntype UnionValue<V, K extends PropertyKey> = V extends unknown ? (K extends keyof V ? V[K] : never) : never;\n\n/** Extracts the source names carried by a SQL expression. */\ntype ExprSource<V> = V extends { readonly [exprBrand]: ExprBrand<unknown, infer Src> } ? Src : never;\n\n/** Rejects expressions that reference tables outside the statement's allowed scope. */\ntype CheckExprScope<V, Scope> =\n string extends ExprSource<V>\n ? unknown\n : [Exclude<ExprSource<V>, Scope>] extends [never]\n ? unknown\n : \"Expression source is not in the statement scope\";\n\n/** Extracts each expression from a scalar or named RETURNING projection. */\ntype ReturningExpr<R> = R extends ExprLike<unknown> ? R : R extends undefined ? never : R[keyof R];\n\n/** Detects an empty named RETURNING projection. */\ntype EmptyReturning<R> = R extends object ? (keyof R extends never ? true : false) : false;\n\n/** Rejects empty RETURNING objects and expressions outside the target scope. */\ntype CheckReturning<R, Scope> = true extends EmptyReturning<R> ? never : CheckExprScope<ReturningExpr<R>, Scope>;\n\n/** Validates assignment keys, values, and expression sources without distributing union inputs. */\ntype CheckAssignments<V, Allowed, Scope> = [Exclude<UnionKeys<V>, keyof Allowed>] extends [never]\n ? Allowed & {\n [K in UnionKeys<V>]?: CheckExprScope<UnionValue<V, K>, Scope>;\n }\n : \"SQL assignments have unknown target fields\";\n\n/**\n * Checks every INSERT row in a readonly collection against the target's writable columns.\n *\n * `Allowed` is the target's accepted assignments, i.e. `InsertValues<T>` for an entity table and\n * `CustomInsertValues<C>` for a declared one. The scope is `never` because a VALUES cell cannot read\n * the row being written.\n */\ntype CheckValues<Allowed, V extends readonly unknown[]> = readonly CheckAssignments<V[number], Allowed, never>[];\n\n/**\n * Checks a custom-table mutation against its declared primitive columns.\n *\n * Only clauses for the selected operation are allowed, and `softDeletes` is rejected because there is no entity\n * policy. Assignments use declaration keys and honor nullability, defaults, and generated columns. INSERT VALUES\n * cannot read the target row, while UPDATE SET and RETURNING can. INSERT SELECT must be a valid named read with all\n * required columns and compatible declared value types; runtime checks also compare its SQL codecs and nullability.\n */\ntype CheckCustomMutation<M> = {\n // Reject clauses outside the selected operation, plus softDeletes because custom tables have no entity policy.\n readonly [K in keyof M]: K extends MutationClause<M> ? (K extends \"softDeletes\" ? never : unknown) : never;\n} & {\n readonly returning?: M extends { readonly returning?: infer R } ? CheckReturning<R, NameOf<TargetTable<M>>> : never;\n} &\n // INSERT VALUES checks every row against the custom table's writable columns.\n (\n | (M extends { readonly values: infer V extends readonly unknown[] }\n ? { readonly values: CheckValues<CustomInsertValues<CustomColumnsOf<TargetTable<M>>>, V> }\n : never)\n // INSERT SELECT checks the source's names, values, and expression scopes.\n | (M extends { readonly from: infer Q extends SetOperand }\n ? { readonly from: CheckCustomInsertSource<CustomColumnsOf<TargetTable<M>>, Q> }\n : never)\n // UPDATE checks assignments against writable columns and permits target-scoped expressions.\n | (M extends { readonly set: infer V }\n ? {\n readonly set: CheckAssignments<\n V,\n CustomUpdateValues<CustomColumnsOf<TargetTable<M>>>,\n NameOf<TargetTable<M>>\n >;\n }\n : never)\n // DELETE has no assignments or source that needs further type checking.\n | (M extends { readonly delete: unknown } ? unknown : never)\n );\n\n/**\n * Checks an INSERT SELECT's named outputs, required columns, values, and read source.\n *\n * `Row` is the row shape the source must produce and `Keys` the target's writable column keys, i.e.\n * `InsertSourceRow<T>` and `InsertKey<T>` for an entity table.\n */\ntype CheckInsertSourceOf<Row, Keys extends PropertyKey, Q> = SetOperand extends Q\n ? \"INSERT source type lost its select keys; use `satisfies Query` or `satisfies SetQuery` instead of a type annotation\"\n : ReadQueryRow<Q> extends Row\n ? Exclude<UnionKeys<ReadQueryRow<Q>>, Keys> extends never\n ? CheckReadQuery<Q> &\n CheckSourceScope<Q> &\n (Q extends SetQuery<readonly SetOperand[]> ? CheckSetQuery<Q> : unknown)\n : \"INSERT SELECT has unknown target fields\"\n : \"INSERT SELECT requires compatible values for all SQL-required fields\";\n\n/** Checks a custom INSERT SELECT against the table's declared writable columns. */\ntype CheckCustomInsertSource<C extends CustomColumnInputs, Q> = CheckInsertSourceOf<\n CustomInsertSourceRow<C>,\n CustomInsertKey<C>,\n Q\n>;\n\n/** Checks every SELECT expression against the tables visible within its read-query branch. */\ntype CheckSourceScope<Q> = Q extends { readonly select: infer S; readonly from: infer F }\n ? CheckScope<S, F, \"join\" extends keyof Q ? Extract<Q[keyof Q & \"join\"], QueryJoinInput> : []>\n : {\n [K in keyof Q]: K extends SetOperation\n ? Q[K] extends readonly unknown[]\n ? { [I in keyof Q[K]]: CheckSourceScope<Q[K][I]> }\n : unknown\n : unknown;\n };\n\n/** Checks an entity INSERT SELECT against the entity's writable columns. */\ntype CheckInsertSource<T, Q extends SetOperand> = CheckInsertSourceOf<InsertSourceRow<T>, InsertKey<T>, Q>;\n\n/** Extracts the entity type from any mutation target clause. */\ntype TargetEntity<M> = M extends\n | { readonly insert: TableFor<infer T> }\n | { readonly update: TableFor<infer T> }\n | { readonly delete: TableFor<infer T> }\n ? T\n : never;\n\n/** Extracts the table handle from any mutation target clause. */\ntype TargetTable<M> = M extends\n | { readonly insert: infer A }\n | { readonly update: infer A }\n | { readonly delete: infer A }\n ? A\n : never;\n\n/** Clauses permitted by the selected INSERT, UPDATE, or DELETE operation. */\ntype MutationClause<M> =\n | \"returning\"\n | \"with\"\n | (M extends { readonly insert: unknown }\n ? \"insert\" | (M extends { readonly values: unknown } ? \"values\" : \"from\")\n : \"where\" | \"allowAll\" | \"softDeletes\" | (M extends { readonly update: unknown } ? \"update\" | \"set\" : \"delete\"));\n\n/** Reads the writable columns from either kind of table handle, so the compiler has one target shape. */\nfunction mutationTarget(target: unknown): MutationTarget {\n if (isEntityTable(target)) {\n const mgmt = getTableMgmt(target);\n return { mgmt, name: mgmt.meta.type, columns: mgmt.meta.columns, meta: mgmt.meta };\n }\n if (isCustomTable(target)) {\n const mgmt = getTableMgmt(target);\n return { mgmt, name: mgmt.tableName, columns: mgmt.columns, meta: undefined };\n }\n return fail(\"A mutation target must be a table\");\n}\n\n/** SQL mutations require complete physical metadata. */\nfunction requireColumnMetadata(target: MutationTarget, column: Column): void {\n if (\n typeof column.sqlNullable !== \"boolean\" ||\n typeof column.hasDefault !== \"boolean\" ||\n typeof column.isGenerated !== \"boolean\"\n )\n fail(`Missing physical metadata for ${target.name}.${column.columnName}; run codegen`);\n}\n\n/** Validates every supplied key, including undefined fields, before pruning omitted values. */\nfunction assignments(target: MutationTarget, value: unknown, operation: \"insert\" | \"update\"): [string, unknown][] {\n if (!value || typeof value !== \"object\" || Array.isArray(value) || isExpr(value) || isEntity(value))\n fail(`${operation} assignments must be a field POJO`);\n const entries = Object.entries(value);\n for (const [key] of entries) writableField(target, key, operation);\n checkPojoKeys(value, Object.keys(target.columns), `${operation} assignments`);\n const defined = entries.filter((entry) => entry[1] !== undefined);\n if (!defined.length) fail(`${operation} requires at least one defined field; empty rows/sets are not DEFAULT VALUES`);\n return defined;\n}\n\n/**\n * Applies physical write restrictions, not ORM-derived, protected, or business-immutable flags.\n *\n * The primary-key and generated checks only sharpen the message: `Column` already denies both through\n * `insert: \"never\"` and `update: false`, for declared custom columns as well as generated ones.\n */\nfunction writableField(target: MutationTarget, key: string, operation: \"insert\" | \"update\"): Column {\n const column = Object.hasOwn(target.columns, key) ? target.columns[key] : undefined;\n if (!column) fail(`Unsupported SQL mutation field ${target.name}.${key}`);\n if (operation === \"update\" && column.columnName === \"id\") fail(\"UPDATE primary-key assignments are not supported\");\n if (column.isGenerated) fail(`Generated field ${target.name}.${key} is omit-only`);\n if (operation === \"update\" ? !column.update : column.insert === \"never\")\n fail(`Unsupported SQL mutation field ${target.name}.${key}`);\n return column;\n}\n\n/**\n * Classifies SQL expressions and SQL NULL before invoking the column's entity-independent write codec.\n * Normalizes public PK/FK ids to internal tagged ids using the target entity's idType.\n *\n * A custom table's columns never carry `idMetadata`, so they take the literal path below unchanged.\n */\nfunction assignmentToSql(target: MutationTarget, column: Column, value: unknown, ctx: Ctx): SqlFragment {\n if (isExpr(value)) return asNode(value).toSql(ctx);\n if (value === null) {\n if (!column.sqlNullable) fail(`${target.name}.${column.columnName} is physically NOT NULL`);\n return { sql: \"NULL\", bindings: [], refs: [] };\n }\n if (column.idMetadata) {\n const other = column.idMetadata();\n if (isEntity(value)) {\n if (column.columnName === \"id\" || !(value instanceof other.cstr)) fail(`Expected a ${other.type} reference`);\n if (value.isNewEntity || value.idTaggedMaybe === undefined)\n fail(`Cannot reference an unflushed ${other.type}, even with an assigned ID`);\n value = value.idTaggedMaybe;\n } else if (typeof value !== (other.idType === \"number\" ? \"number\" : \"string\")) {\n fail(`Expected a persisted ${other.type} or its ID; nested creation is not supported`);\n } else {\n // Public untagged TEXT ids may contain delimiters or start with the entity tag.\n value =\n other.idType === \"untagged-string\"\n ? keyToTaggedId(other, value as string)\n : toTaggedId(other, value as string | number);\n }\n }\n if (!column.codec.mapToDbValue)\n fail(`The codec for ${target.name}.${column.columnName} does not support SQL value writes`);\n return { sql: \"?\", bindings: [column.mapToDbValue(value)], refs: [] };\n}\n\n/** Checks the user predicate independently so metadata filters cannot turn a pruned guard into consent. */\nfunction mutationCondition(value: unknown, ctx: Ctx): SqlFragment | undefined {\n if (isExpr(value)) return asNode(value).toSql(ctx);\n if (Array.isArray(value)) return conditionToSql({ and: value }, ctx, true);\n return conditionToSql(value as SqlCondition | undefined, ctx, true);\n}\n"],"mappings":";;;;;;;;;;;;AAoMA,SAAgB,WAAW,KAAuB;CAChD,OACE,OAAO,QAAQ,YACf,QAAQ,QACR,CAACA,0BAAAA,iBAAiB,GAAG,KACrB;EAAC;EAAU;EAAU;CAAQ,CAAC,CAAC,MAAM,QAAQ,OAAO,GAAG;AAE3D;;;;;;AAOA,SAAgB,eAAe,KAAgC;CAC7D,IAAI,CAAC,WAAW,GAAG,GAAG,OAAOC,0BAAAA,eAAe,GAAG;CAC/C,MAAM,YAAY;CAClB,MAAM,QAAQ;EAAC;EAAU;EAAU;CAAQ,CAAC,CAAC,QAAQ,QAAQ,OAAO,SAAS;CAC7E,IAAI,MAAM,WAAW,GAAG,cAAA,KAAK,gEAAgE;CAC7F,MAAM,Y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Gf;WAAqB;gBACN;WAAqB;iEACO;WAAqB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execute.d.mts","names":[],"sources":["../../../src/queries/sql/execute.ts"],"mappings":";;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"execute.d.mts","names":[],"sources":["../../../src/queries/sql/execute.ts"],"mappings":";;;;;;;;;;;UA0DiB,cAAc;EAC7B;EACA,MAAM;;;KAII,qBAAqB,oBAAoB,SAAS,eAAe;YACjE;YACA;YACA;;;KAIA,aAAa,UAAU,aAChC,KAAK,kBAAkB,KAAK,WAAW,GAAG,WAE1C,KAAK,QAAQ,UAAU,IAAI,kBAAkB,OAAO,WAAW,GAAG;;KAIzD,aAAa,UAAU,aAChC,KAAK,UAAU,MAAM,WAAW,GAAG;;KAI1B,gBACV,UAAU,QACV,UAAU,gCAAgC,+BAC1C,UAAU,aAAa,MAAM,iBAAiB,UAAU,SAAS,gBAAgB;WAExE,QAAQ,oBAAoB;WAC5B,YAAY;WACZ;WACA;WACA;WACA;WACA;WACA;;WAEA,OAAO;IACd;WAEa,iBAAiB,aAAa;WAAe;;WAC7C,MAAM,IAAI,kBAAkB,GAAG;WAAa;;;KAIjD,gBACV,UAAU,QACV,UAAU,gCAAgC;WAEjC,QAAQ,oBAAoB;WAC5B,KAAK,aAAa;WAClB,YAAY;WACZ;WACA;WACA;WACA;;WAEA,OAAO;IACd,iBACF;;KAGU,gBACV,UAAU,QACV,UAAU,gCAAgC;WAEjC,QAAQ,oBAAoB;WAC5B,YAAY;WACZ;WACA;WACA;WACA;WACA;;WAEA,OAAO;IACd,iBACF;;KAGU,kBACV,UAAU,QACV,UAAU,gCAAgC,iCACxC,gBAAgB,GAAG,KAAK,gBAAgB,GAAG,KAAK,gBAAgB,GAAG;;KAG3D;WACG,QAAQ,SAAS;WAAkB;WAAoC;;WACvE,QAAQ,SAAS;WAAkB,MAAM;WAAqB;;WAC9D,QAAQ,SAAS;WAAkB;;WACnC,QAAQ,SAAS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;WACvB,QAAQ,eAAe;;WACvB,QAAQ,eAAe;IAClC;;KAIC,YAAY,KAAK;WACP,cAAc;;WACd,cAAc;;WACd,cAAc;IACzB;;KAIC,eAAe,6BAGf;WAAqB;gBACN;WAAqB;iEACO;WAAqB"}
|
|
@@ -5,7 +5,7 @@ import { fail } from "../../utils.js";
|
|
|
5
5
|
import { AliasAssigner } from "./AliasAssigner.js";
|
|
6
6
|
import "./custom.js";
|
|
7
7
|
import { getTableMgmt, isCustomTable, isEntityTable, tableSqlName } from "./Tables.js";
|
|
8
|
-
import { Ctx, checkPojoKeys, conditionToSql, injectedConditions, isReadQueryValue, parseNestedQuery, parseUserQuery,
|
|
8
|
+
import { Ctx, checkPojoKeys, conditionToSql, injectedConditions, isReadQueryValue, parseNestedQuery, parseUserQuery, prependCtes, projectionToSql, registerCtes } from "./query.js";
|
|
9
9
|
import { isEntity } from "../../Entity.js";
|
|
10
10
|
//#region src/queries/sql/execute.ts
|
|
11
11
|
/** Classifies mutation roots before EntityManager applies write permissions, including malformed roots. */
|
|
@@ -138,15 +138,10 @@ function parseStatement(arg) {
|
|
|
138
138
|
sql += ` RETURNING ${returning.selects.map((select) => select.sql).join(", ")}`;
|
|
139
139
|
for (const select of returning.selects) bindings.push(...select.bindings);
|
|
140
140
|
}
|
|
141
|
-
const
|
|
142
|
-
if (keptCtes.length > 0) {
|
|
143
|
-
const clause = withFragment(keptCtes);
|
|
144
|
-
sql = clause.sql + sql;
|
|
145
|
-
bindings.unshift(...clause.bindings);
|
|
146
|
-
}
|
|
141
|
+
const withCtes = prependCtes(ctes, new Set(refs), sql, bindings);
|
|
147
142
|
return {
|
|
148
|
-
sql,
|
|
149
|
-
bindings,
|
|
143
|
+
sql: withCtes.sql,
|
|
144
|
+
bindings: withCtes.bindings,
|
|
150
145
|
outerRefs: [],
|
|
151
146
|
output: returning?.output ?? {
|
|
152
147
|
kind: "pojo",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execute.js","names":[],"sources":["../../../src/queries/sql/execute.ts"],"sourcesContent":["import type { DriverQueryResult } from \"src/drivers/Driver.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport type { IdOf } from \"src/EntityManager.ts\";\nimport type { EntityMetadata } from \"src/EntityMetadata.ts\";\nimport { keyToTaggedId, toTaggedId } from \"src/keys.ts\";\nimport type { SqlCondition } from \"src/queries/conditions.ts\";\nimport { AliasAssigner } from \"src/queries/sql/AliasAssigner.ts\";\nimport {\n type CustomColumnInputs,\n type CustomColumnValue,\n type CustomColumnsOf,\n type CustomTableFor,\n} from \"src/queries/sql/custom.ts\";\nimport { type ExprBrand, type ExprLike, type SqlFragment, asNode, exprBrand, isExpr } from \"src/queries/sql/Expr.ts\";\nimport { kq, safeKq } from \"src/queries/sql/keywords.ts\";\nimport {\n type CheckReadQuery,\n type CheckScope,\n type CheckSetQuery,\n Ctx,\n type EntityHydrator,\n type NameOf,\n type Plan,\n type Query,\n type QueryJoinInput,\n type QueryRow,\n type ReadQueryRow,\n type SetOperand,\n type SetOperation,\n type SetQuery,\n type Subquery,\n type WithInput,\n checkPojoKeys,\n conditionToSql,\n entityQueryBrand,\n injectedConditions,\n isReadQueryValue,\n parseNestedQuery,\n parseUserQuery,\n projectionToSql,\n pruneCtes,\n registerCtes,\n subqueryBrand,\n withFragment,\n} from \"src/queries/sql/query.ts\";\nimport {\n type TableFor,\n type TableSourceMgmt,\n getTableMgmt,\n isCustomTable,\n isEntityTable,\n tableMgmt,\n tableSqlName,\n} from \"src/queries/sql/Tables.ts\";\nimport type { Column, ColumnDescriptors } from \"src/serde/columns.ts\";\nimport type { ColumnsOf, TypeMapEntry } from \"src/typeMap.ts\";\nimport { fail } from \"src/utils.ts\";\n\n/** The native command count and decoded rows from one immediate SQL statement. */\nexport interface ExecuteResult<R> {\n rowCount: number;\n rows: R[];\n}\n\n/** A mutation's RETURNING projection: one SQL expression or a named object of expressions. */\nexport type MutationReturning = (ExprLike<unknown> | Readonly<Record<string, ExprLike<unknown>>>) & {\n readonly [tableMgmt]?: never;\n readonly [subqueryBrand]?: never;\n readonly [entityQueryBrand]?: never;\n};\n\n/** SQL INSERT inputs, based on physical storage rather than entity creation options. */\nexport type InsertValues<T extends Entity> = {\n [K in RequiredInsertKey<T>]: Assignment<T, K>;\n} & {\n [K in Exclude<InsertKey<T>, RequiredInsertKey<T>>]?: Assignment<T, K> | undefined;\n};\n\n/** SQL UPDATE inputs include persisted derived columns, but never primary keys. */\nexport type UpdateValues<T extends Entity> = {\n [K in UpdateKey<T>]?: Assignment<T, K> | undefined;\n};\n\n/** A reusable INSERT POJO; use a concrete Q for annotated INSERT SELECT source checking. */\nexport type InsertStatement<\n T extends Entity,\n R extends MutationReturning | undefined = MutationReturning | undefined,\n Q extends SetOperand = Query<InsertProjection<T>, []> | Subquery<InsertSourceRow<T>, string>,\n> = {\n readonly insert: MutationTargetTable<T>;\n readonly returning?: R;\n readonly update?: never;\n readonly delete?: never;\n readonly set?: never;\n readonly where?: never;\n readonly allowAll?: never;\n readonly softDeletes?: never;\n /** CTEs to add to a `WITH` before the INSERT; see `Clauses.with`. */\n readonly with?: WithInput;\n} & NoMutationReadClauses &\n (\n | { readonly values: readonly InsertValues<T>[]; readonly from?: never }\n | { readonly from: Q & CheckInsertSource<T, Q>; readonly values?: never }\n );\n\n/** A reusable guarded UPDATE POJO. Undefined assignments leave existing columns unchanged. */\nexport type UpdateStatement<\n T extends Entity,\n R extends MutationReturning | undefined = MutationReturning | undefined,\n> = {\n readonly update: MutationTargetTable<T>;\n readonly set: UpdateValues<T>;\n readonly returning?: R;\n readonly insert?: never;\n readonly delete?: never;\n readonly values?: never;\n readonly from?: never;\n /** CTEs to add to a `WITH` before the UPDATE; see `Clauses.with`. */\n readonly with?: WithInput;\n} & MutationFilter &\n NoMutationReadClauses;\n\n/** A reusable guarded physical DELETE POJO, not an ORM soft delete. */\nexport type DeleteStatement<\n T extends Entity,\n R extends MutationReturning | undefined = MutationReturning | undefined,\n> = {\n readonly delete: MutationTargetTable<T>;\n readonly returning?: R;\n readonly insert?: never;\n readonly update?: never;\n readonly values?: never;\n readonly from?: never;\n readonly set?: never;\n /** CTEs to add to a `WITH` before the DELETE; see `Clauses.with`. */\n readonly with?: WithInput;\n} & MutationFilter &\n NoMutationReadClauses;\n\n/** Public statement annotations retain the target's physical field policy. */\nexport type MutationStatement<\n T extends Entity,\n R extends MutationReturning | undefined = MutationReturning | undefined,\n> = InsertStatement<T, R> | UpdateStatement<T, R> | DeleteStatement<T, R>;\n\n/** Inference starts with the literal POJO; CheckMutation checks its target and every supplied key. */\nexport type MutationInput = (\n | { readonly insert: TableFor<Entity>; readonly values: readonly object[]; readonly from?: never }\n | { readonly insert: TableFor<Entity>; readonly from: SetOperand; readonly values?: never }\n | { readonly update: TableFor<Entity>; readonly set: object }\n | { readonly delete: TableFor<Entity> }\n | {\n readonly insert: CustomTableFor;\n readonly values: readonly object[];\n readonly from?: never;\n }\n | { readonly insert: CustomTableFor; readonly from: SetOperand; readonly values?: never }\n | { readonly update: CustomTableFor; readonly set: object }\n | { readonly delete: CustomTableFor }\n) & { readonly returning?: MutationReturning; readonly with?: WithInput } & MutationFilter;\n\n/** Without RETURNING the row type is never; scalar expressions produce scalar rows. */\nexport type MutationRow<M> = M extends { readonly returning?: infer R }\n ? R extends MutationReturning\n ? R extends ExprLike<unknown>\n ? QueryRow<R>\n : { -readonly [K in keyof QueryRow<R>]: QueryRow<R>[K] }\n : never\n : never;\n\n/** Checks nonliteral statements as well as fresh literals without widening their inferred result. */\nexport type CheckMutation<M> = M extends unknown\n ? [CustomColumnsOf<TargetTable<M>>] extends [never]\n ? TargetEntity<M> extends infer T extends Entity\n ? TypeMapEntry<T, \"supportsEmExecute\"> extends true\n ? { readonly [K in keyof M]: K extends MutationClause<M> ? unknown : never } & {\n readonly returning?: M extends { readonly returning?: infer R }\n ? CheckReturning<R, NameOf<TargetTable<M>>>\n : never;\n } & (\n | (M extends { readonly values: infer V extends readonly unknown[] }\n ? { readonly values: CheckValues<InsertValues<T>, V> }\n : never)\n | (M extends { readonly from: infer Q extends SetOperand }\n ? { readonly from: CheckInsertSource<T, Q> }\n : never)\n | (M extends { readonly set: infer V }\n ? { readonly set: CheckAssignments<V, UpdateValues<T>, NameOf<TargetTable<M>>> }\n : never)\n | (M extends { readonly delete: unknown } ? unknown : never)\n )\n : \"SQL mutations require a supported non-inherited target and regenerated metadata\"\n : never\n : CheckCustomMutation<M>\n : never;\n\n/** Classifies mutation roots before EntityManager applies write permissions, including malformed roots. */\nexport function isMutation(arg: unknown): boolean {\n return (\n typeof arg === \"object\" &&\n arg !== null &&\n !isReadQueryValue(arg) &&\n [\"insert\", \"update\", \"delete\"].some((key) => key in arg)\n );\n}\n\n/**\n * Compiles one immediate statement using the read compiler's scopes, projections, and codecs.\n * INSERT SELECT keeps source rows in PostgreSQL; only RETURNING rows pass through JS decoders.\n * An undefined plan represents a validated standalone empty VALUES array, not DEFAULT VALUES.\n */\nexport function parseStatement(arg: unknown): Plan | undefined {\n if (!isMutation(arg)) return parseUserQuery(arg);\n const statement = arg as Record<string, unknown>;\n const roots = [\"insert\", \"update\", \"delete\"].filter((key) => key in statement);\n if (roots.length !== 1) fail(\"A mutation requires exactly one insert, update, or delete root\");\n const operation = roots[0];\n const allowed =\n operation === \"insert\"\n ? [\"insert\", \"values\", \"from\", \"returning\", \"with\"]\n : [\n operation,\n \"where\",\n \"allowAll\",\n \"softDeletes\",\n \"returning\",\n \"with\",\n ...(operation === \"update\" ? [\"set\"] : []),\n ];\n checkPojoKeys(statement, allowed, `SQL ${operation}`);\n const target = mutationTarget(statement[operation]);\n const { meta } = target;\n if (meta) {\n if (meta.inheritanceType || meta.baseType || meta.baseTypes.length || meta.subTypes.length) {\n fail(\"SQL mutations do not support CTI/STI targets or inherited table families\");\n }\n if (meta.supportsEmExecute !== true)\n fail(`SQL mutations require supported physical metadata for ${meta.type}; run codegen`);\n // Every column is checked here, so the writable-column lookups below can trust their metadata.\n for (const column of Object.values(meta.columns)) requireColumnMetadata(target, column);\n } else if (statement.softDeletes !== undefined) {\n fail(\"Custom table mutations do not support softDeletes\");\n }\n const fields = Object.entries(target.columns);\n const assigner = new AliasAssigner();\n // A CTE is in scope for the whole statement, so its scope is the parent of every other one here. It\n // deliberately holds no target alias, which is what lets INSERT VALUES cells and the INSERT SELECT\n // source read the CTEs without also seeing the row being written.\n const withCtx = new Ctx(assigner, undefined);\n const ctes = registerCtes(statement, withCtx, assigner);\n // Aliases the rest of the statement reads, so an unread CTE prunes like it does on a read query.\n const refs: string[] = [];\n const ctx = new Ctx(assigner, withCtx);\n const alias = assigner.getAlias(target.mgmt.tableName);\n ctx.register(target.mgmt, alias);\n const returning = statement.returning === undefined ? undefined : projectionToSql(statement.returning, ctx);\n if (returning) for (const select of returning.selects) refs.push(...select.refs);\n let sql = `${operation === \"delete\" ? \"DELETE FROM\" : operation.toUpperCase() + (operation === \"insert\" ? \" INTO\" : \"\")} ${tableSqlName(target.mgmt)} AS ${kq(alias)}`;\n const bindings: unknown[] = [];\n if (operation === \"insert\") {\n if (\"values\" in statement === \"from\" in statement) fail(\"INSERT requires exactly one of values or from\");\n const required = fields.filter(([, column]) => column.insert === \"required\");\n if (\"values\" in statement) {\n if (!Array.isArray(statement.values)) fail(\"INSERT values must be an array of field POJOs\");\n const rows = statement.values;\n // A VALUES cell *is* the new row, so there is no existing row for it to read: this scope skips\n // the `ctx.register(mgmt, alias)` above, so a cell naming the target fails instead of emitting a\n // `b` with no FROM clause. I.e. an UPDATE can say `set: { title: b.title }`; an INSERT cannot.\n // A value subquery still works, because it brings its own sources, and the parent here is the CTE\n // scope rather than `ctx`, so a cell can read a `with` entry but not the row being written.\n const valuesCtx = new Ctx(assigner, withCtx);\n const entries = rows.map((row) => assignments(target, row, \"insert\"));\n for (const row of entries) {\n for (const [key] of required) {\n if (!row.some((entry) => entry[0] === key)) fail(`INSERT requires ${target.name}.${key}`);\n }\n }\n if (rows.length === 0) return undefined;\n const keys = fields\n .filter(([key]) => entries.some((row) => row.some((entry) => entry[0] === key)))\n .map(([key, field]) => [key, field.columnName] as const);\n sql += ` (${keys.map(([, column]) => kq(column)).join(\", \")}) VALUES `;\n sql += entries\n .map((row) => {\n const cells = keys.map(([key]) => {\n const entry = row.find((entry) => entry[0] === key);\n if (!entry) return \"DEFAULT\";\n const cell = assignmentToSql(target, writableField(target, key, \"insert\"), entry[1], valuesCtx);\n bindings.push(...cell.bindings);\n refs.push(...cell.refs);\n return cell.sql;\n });\n return `(${cells.join(\", \")})`;\n })\n .join(\", \");\n } else {\n const source = parseNestedQuery(statement.from, withCtx, assigner);\n if (source.output.kind !== \"pojo\") fail(\"INSERT SELECT requires named POJO output columns\");\n const columns = source.output.columns;\n for (const [key] of required) {\n if (!columns.some((column) => column[0] === key)) {\n fail(`INSERT requires ${target.name}.${key}`);\n }\n }\n for (const [key, expr] of columns) {\n const field = writableField(target, key, \"insert\");\n const left = field.outputType;\n const right = expr.outputType;\n if (\n !left ||\n !right ||\n left.dbType !== right.dbType ||\n left.domain !== right.domain ||\n left.idMeta !== right.idMeta\n ) {\n fail(`INSERT SELECT ${target.name}.${key} has incompatible or unknown storage codecs`);\n }\n if (!field.sqlNullable && expr.sqlNullable === true)\n fail(`INSERT SELECT ${target.name}.${key} cannot accept a nullable output`);\n }\n const keys = fields\n .filter(([key]) => columns.some((column) => column[0] === key))\n .map(([key, field]) => [key, field.columnName] as const);\n const sourceAlias = safeKq(assigner.getLiteralAlias(\"sq\"));\n sql += ` (${keys.map(([, column]) => kq(column)).join(\", \")}) SELECT ${keys.map(([key]) => `${sourceAlias}.${safeKq(key)}`).join(\", \")} FROM (${source.sql}) AS ${sourceAlias}`;\n bindings.push(...source.bindings);\n refs.push(...source.outerRefs);\n }\n } else {\n if (statement.allowAll !== undefined && typeof statement.allowAll !== \"boolean\") fail(\"allowAll must be a boolean\");\n if (\n statement.softDeletes !== undefined &&\n statement.softDeletes !== \"include\" &&\n statement.softDeletes !== \"exclude\"\n )\n fail(\"softDeletes must be 'include' or 'exclude'\");\n const whereCondition = mutationCondition(statement.where, ctx);\n if (Object.hasOwn(statement, \"where\") && !whereCondition && statement.allowAll !== true)\n fail(\"UPDATE and DELETE require allowAll: true when a supplied where is undefined or fully pruned\");\n if (operation === \"update\") {\n const entries = assignments(target, statement.set, \"update\");\n sql +=\n \" SET \" +\n entries\n .map((entry) => {\n const [key, value] = entry;\n const field = writableField(target, key, \"update\");\n const cell = assignmentToSql(target, field, value, ctx);\n bindings.push(...cell.bindings);\n refs.push(...cell.refs);\n return `${kq(field.columnName)} = ${cell.sql}`;\n })\n .join(\", \");\n }\n const injected = meta\n ? conditionToSql({ and: injectedConditions({ meta, alias }, statement.softDeletes ?? \"exclude\") }, ctx, true)\n : undefined;\n const conditions = [whereCondition, injected].filter((condition) => condition !== undefined);\n if (conditions.length) {\n sql += ` WHERE ${conditions.map((condition) => `(${condition.sql})`).join(\" AND \")}`;\n for (const condition of conditions) {\n bindings.push(...condition.bindings);\n refs.push(...condition.refs);\n }\n }\n }\n if (returning) {\n sql += ` RETURNING ${returning.selects.map((select) => select.sql).join(\", \")}`;\n for (const select of returning.selects) bindings.push(...select.bindings);\n }\n const keptCtes = pruneCtes(ctes, new Set(refs));\n if (keptCtes.length > 0) {\n const clause = withFragment(keptCtes);\n sql = clause.sql + sql;\n bindings.unshift(...clause.bindings);\n }\n return {\n sql,\n bindings,\n outerRefs: [],\n output: returning?.output ?? { kind: \"pojo\", columns: [] },\n decodeRows: returning?.decodeRows ?? (() => []),\n };\n}\n\n/** Retains native counts even when no rows return, and propagates decoding failures after execution. */\nexport function decodeStatementResult(\n em: EntityHydrator,\n plan: Plan,\n result: DriverQueryResult,\n): ExecuteResult<unknown> {\n if (typeof result.rowCount !== \"number\" || !Number.isInteger(result.rowCount) || result.rowCount < 0)\n fail(\"The driver did not return a numeric command rowCount\");\n return { rowCount: result.rowCount, rows: plan.decodeRows(em, result.rows) };\n}\n\n/** An entity table whose generated metadata permits direct SQL mutations. */\ntype MutationTargetTable<T extends Entity> = TableFor<T> &\n (TypeMapEntry<T, \"supportsEmExecute\"> extends true ? unknown : never);\n\n/**\n * What a mutation needs from its target, an entity table or a `declareTable` table alike.\n *\n * Both kinds describe their storage with the same `Column`, so the INSERT/UPDATE/DELETE compiler reads\n * `columns` without caring which it has; `meta` is the one thing only an entity table brings.\n */\ninterface MutationTarget {\n /** The SQL identity, for the alias and the qualified table name; also the key `Ctx` registers. */\n mgmt: TableSourceMgmt;\n /** Names the target in errors: the entity type, i.e. `Book`, or the table name, i.e. `book_reviews`. */\n name: string;\n columns: ColumnDescriptors;\n /** Entity tables only; a custom table has no soft-delete, inheritance, or ID-tagging policy. */\n meta: EntityMetadata | undefined;\n}\n\n/** Shared filtering and full-table consent clauses for UPDATE and DELETE. */\ntype MutationFilter = {\n /**\n * An `{ and: [...] }` or `{ or: [...] }` group, a boolean expression, or a bare condition such as `a.age.gte(18)`.\n *\n * Arrays are shorthand for `{ and: [...] }`; undefined conditions are pruned.\n */\n readonly where?: SqlCondition | ExprLike<boolean> | readonly (SqlCondition | undefined)[];\n /** Allows a supplied where to be undefined or fully pruned; unnecessary when where is omitted. */\n readonly allowAll?: boolean;\n readonly softDeletes?: \"include\" | \"exclude\";\n};\n\n/** Read-only query clauses that mutations explicitly reject. */\ntype NoMutationReadClauses = Partial<\n Record<\n | \"select\"\n | \"join\"\n | \"groupBy\"\n | \"having\"\n | \"orderBy\"\n | \"limit\"\n | \"offset\"\n | \"distinct\"\n | \"pruneJoins\"\n | \"as\"\n | \"union\"\n | \"unionAll\"\n | \"intersect\"\n | \"intersectAll\"\n | \"except\"\n | \"exceptAll\"\n | \"ctes\"\n | \"using\"\n | \"onConflict\",\n never\n >\n>;\n\n/** Column keys allowed in INSERT, i.e. Book's optional `id` and required `authorId`. */\ntype InsertKey<T> = {\n [K in keyof ColumnsOf<T>]: ColumnsOf<T>[K] extends { insert: \"required\" | \"optional\" } ? K : never;\n}[keyof ColumnsOf<T>];\n\n/** Column keys that each INSERT row must supply, i.e. Book's `authorId` despite its ORM default. */\ntype RequiredInsertKey<T> = {\n [K in keyof ColumnsOf<T>]: ColumnsOf<T>[K] extends { insert: \"required\" } ? K : never;\n}[keyof ColumnsOf<T>];\n\n/** Column keys allowed in UPDATE SET, i.e. Book's `title` and `authorId`, but not `id`. */\ntype UpdateKey<T> = {\n [K in keyof ColumnsOf<T>]: ColumnsOf<T>[K] extends { update: true } ? K : never;\n}[keyof ColumnsOf<T>];\n\n/** A column's domain value before SQL nullability is added, i.e. Book's `id` is BookId and `authorId` is AuthorId. */\ntype DomainValue<T, K extends keyof ColumnsOf<T>> = K extends \"id\"\n ? IdOf<T>\n : ColumnsOf<T>[K] extends { entity: infer U }\n ? IdOf<U>\n : ColumnsOf<T>[K] extends { type: infer V }\n ? V\n : never;\n\n/** A modeled column's domain value with SQL nullability applied. */\ntype SqlValue<T, K extends keyof ColumnsOf<T>> =\n | DomainValue<T, K>\n | (ColumnsOf<T>[K] extends { nullable: true } ? null : never);\n\n/** A modeled-column value, entity reference, or SQL expression that produces one. */\ntype Assignment<T, K extends keyof ColumnsOf<T>> =\n | SqlValue<T, K>\n | ExprLike<SqlValue<T, K>>\n | (K extends \"id\" ? never : ColumnsOf<T>[K] extends { entity: infer U } ? U : never);\n\n/** A custom column's declared value with SQL nullability applied. */\ntype CustomSqlValue<I> = CustomColumnValue<I> | (I extends { nullable: true } ? null : never);\n\n/** A custom-column value or SQL expression that produces one. */\ntype CustomAssignment<I> = CustomSqlValue<I> | ExprLike<CustomSqlValue<I>>;\n\n/** Custom-column keys accepted by INSERT, excluding generated columns. */\ntype CustomInsertKey<C extends CustomColumnInputs> = {\n [K in keyof C]: C[K] extends { generated: true } ? never : K;\n}[keyof C];\n\n/** Custom-column keys each INSERT row must supply because they have no default and are not nullable. */\ntype CustomRequiredInsertKey<C extends CustomColumnInputs> = {\n [K in CustomInsertKey<C>]: C[K] extends { nullable: true } | { hasDefault: true } ? never : K;\n}[CustomInsertKey<C>];\n\n/** Custom-column keys accepted by UPDATE, excluding generated columns and the physical primary key. */\ntype CustomUpdateKey<C extends CustomColumnInputs> = {\n [K in keyof C]: C[K] extends { generated: true }\n ? never\n : K extends \"id\"\n ? never\n : C[K] extends { columnName: \"id\" }\n ? never\n : K;\n}[keyof C];\n\n/** Values accepted by INSERT for a custom table's declared columns. */\ntype CustomInsertValues<C extends CustomColumnInputs> = {\n [K in CustomRequiredInsertKey<C>]: CustomAssignment<C[K]>;\n} & {\n [K in Exclude<CustomInsertKey<C>, CustomRequiredInsertKey<C>>]?: CustomAssignment<C[K]> | undefined;\n};\n\n/** Assignments accepted by UPDATE for a custom table's writable columns. */\ntype CustomUpdateValues<C extends CustomColumnInputs> = {\n [K in CustomUpdateKey<C>]?: CustomAssignment<C[K]> | undefined;\n};\n\n/** Named row shape that an INSERT SELECT source must produce for a custom table. */\ntype CustomInsertSourceRow<C extends CustomColumnInputs> = {\n [K in CustomRequiredInsertKey<C>]: CustomSqlValue<C[K]>;\n} & {\n [K in Exclude<CustomInsertKey<C>, CustomRequiredInsertKey<C>>]?: CustomSqlValue<C[K]>;\n};\n\n/** Named row shape that an entity INSERT SELECT source must produce. */\ntype InsertSourceRow<T> = { [K in RequiredInsertKey<T>]: SqlValue<T, K> } & {\n [K in Exclude<InsertKey<T>, RequiredInsertKey<T>>]?: SqlValue<T, K>;\n};\n\n/** Named expression projection accepted from an entity INSERT SELECT source. */\ntype InsertProjection<T> = { [K in RequiredInsertKey<T>]: ExprLike<SqlValue<T, K>> } & {\n [K in Exclude<InsertKey<T>, RequiredInsertKey<T>>]?: ExprLike<SqlValue<T, K>>;\n};\n\n/** Collects the keys from every member of a union instead of only their shared keys. */\ntype UnionKeys<V> = V extends unknown ? keyof V : never;\n\n/** Collects every alternative before scope checking; a valid branch cannot hide an unrelated alias. */\ntype UnionValue<V, K extends PropertyKey> = V extends unknown ? (K extends keyof V ? V[K] : never) : never;\n\n/** Extracts the source names carried by a SQL expression. */\ntype ExprSource<V> = V extends { readonly [exprBrand]: ExprBrand<unknown, infer Src> } ? Src : never;\n\n/** Rejects expressions that reference tables outside the statement's allowed scope. */\ntype CheckExprScope<V, Scope> =\n string extends ExprSource<V>\n ? unknown\n : [Exclude<ExprSource<V>, Scope>] extends [never]\n ? unknown\n : \"Expression source is not in the statement scope\";\n\n/** Extracts each expression from a scalar or named RETURNING projection. */\ntype ReturningExpr<R> = R extends ExprLike<unknown> ? R : R extends undefined ? never : R[keyof R];\n\n/** Detects an empty named RETURNING projection. */\ntype EmptyReturning<R> = R extends object ? (keyof R extends never ? true : false) : false;\n\n/** Rejects empty RETURNING objects and expressions outside the target scope. */\ntype CheckReturning<R, Scope> = true extends EmptyReturning<R> ? never : CheckExprScope<ReturningExpr<R>, Scope>;\n\n/** Validates assignment keys, values, and expression sources without distributing union inputs. */\ntype CheckAssignments<V, Allowed, Scope> = [Exclude<UnionKeys<V>, keyof Allowed>] extends [never]\n ? Allowed & {\n [K in UnionKeys<V>]?: CheckExprScope<UnionValue<V, K>, Scope>;\n }\n : \"SQL assignments have unknown target fields\";\n\n/**\n * Checks every INSERT row in a readonly collection against the target's writable columns.\n *\n * `Allowed` is the target's accepted assignments, i.e. `InsertValues<T>` for an entity table and\n * `CustomInsertValues<C>` for a declared one. The scope is `never` because a VALUES cell cannot read\n * the row being written.\n */\ntype CheckValues<Allowed, V extends readonly unknown[]> = readonly CheckAssignments<V[number], Allowed, never>[];\n\n/**\n * Checks a custom-table mutation against its declared primitive columns.\n *\n * Only clauses for the selected operation are allowed, and `softDeletes` is rejected because there is no entity\n * policy. Assignments use declaration keys and honor nullability, defaults, and generated columns. INSERT VALUES\n * cannot read the target row, while UPDATE SET and RETURNING can. INSERT SELECT must be a valid named read with all\n * required columns and compatible declared value types; runtime checks also compare its SQL codecs and nullability.\n */\ntype CheckCustomMutation<M> = {\n // Reject clauses outside the selected operation, plus softDeletes because custom tables have no entity policy.\n readonly [K in keyof M]: K extends MutationClause<M> ? (K extends \"softDeletes\" ? never : unknown) : never;\n} & {\n readonly returning?: M extends { readonly returning?: infer R } ? CheckReturning<R, NameOf<TargetTable<M>>> : never;\n} &\n // INSERT VALUES checks every row against the custom table's writable columns.\n (\n | (M extends { readonly values: infer V extends readonly unknown[] }\n ? { readonly values: CheckValues<CustomInsertValues<CustomColumnsOf<TargetTable<M>>>, V> }\n : never)\n // INSERT SELECT checks the source's names, values, and expression scopes.\n | (M extends { readonly from: infer Q extends SetOperand }\n ? { readonly from: CheckCustomInsertSource<CustomColumnsOf<TargetTable<M>>, Q> }\n : never)\n // UPDATE checks assignments against writable columns and permits target-scoped expressions.\n | (M extends { readonly set: infer V }\n ? {\n readonly set: CheckAssignments<\n V,\n CustomUpdateValues<CustomColumnsOf<TargetTable<M>>>,\n NameOf<TargetTable<M>>\n >;\n }\n : never)\n // DELETE has no assignments or source that needs further type checking.\n | (M extends { readonly delete: unknown } ? unknown : never)\n );\n\n/**\n * Checks an INSERT SELECT's named outputs, required columns, values, and read source.\n *\n * `Row` is the row shape the source must produce and `Keys` the target's writable column keys, i.e.\n * `InsertSourceRow<T>` and `InsertKey<T>` for an entity table.\n */\ntype CheckInsertSourceOf<Row, Keys extends PropertyKey, Q> = SetOperand extends Q\n ? \"INSERT source type lost its select keys; use `satisfies Query` or `satisfies SetQuery` instead of a type annotation\"\n : ReadQueryRow<Q> extends Row\n ? Exclude<UnionKeys<ReadQueryRow<Q>>, Keys> extends never\n ? CheckReadQuery<Q> &\n CheckSourceScope<Q> &\n (Q extends SetQuery<readonly SetOperand[]> ? CheckSetQuery<Q> : unknown)\n : \"INSERT SELECT has unknown target fields\"\n : \"INSERT SELECT requires compatible values for all SQL-required fields\";\n\n/** Checks a custom INSERT SELECT against the table's declared writable columns. */\ntype CheckCustomInsertSource<C extends CustomColumnInputs, Q> = CheckInsertSourceOf<\n CustomInsertSourceRow<C>,\n CustomInsertKey<C>,\n Q\n>;\n\n/** Checks every SELECT expression against the tables visible within its read-query branch. */\ntype CheckSourceScope<Q> = Q extends { readonly select: infer S; readonly from: infer F }\n ? CheckScope<S, F, \"join\" extends keyof Q ? Extract<Q[keyof Q & \"join\"], QueryJoinInput> : []>\n : {\n [K in keyof Q]: K extends SetOperation\n ? Q[K] extends readonly unknown[]\n ? { [I in keyof Q[K]]: CheckSourceScope<Q[K][I]> }\n : unknown\n : unknown;\n };\n\n/** Checks an entity INSERT SELECT against the entity's writable columns. */\ntype CheckInsertSource<T, Q extends SetOperand> = CheckInsertSourceOf<InsertSourceRow<T>, InsertKey<T>, Q>;\n\n/** Extracts the entity type from any mutation target clause. */\ntype TargetEntity<M> = M extends\n | { readonly insert: TableFor<infer T> }\n | { readonly update: TableFor<infer T> }\n | { readonly delete: TableFor<infer T> }\n ? T\n : never;\n\n/** Extracts the table handle from any mutation target clause. */\ntype TargetTable<M> = M extends\n | { readonly insert: infer A }\n | { readonly update: infer A }\n | { readonly delete: infer A }\n ? A\n : never;\n\n/** Clauses permitted by the selected INSERT, UPDATE, or DELETE operation. */\ntype MutationClause<M> =\n | \"returning\"\n | \"with\"\n | (M extends { readonly insert: unknown }\n ? \"insert\" | (M extends { readonly values: unknown } ? \"values\" : \"from\")\n : \"where\" | \"allowAll\" | \"softDeletes\" | (M extends { readonly update: unknown } ? \"update\" | \"set\" : \"delete\"));\n\n/** Reads the writable columns from either kind of table handle, so the compiler has one target shape. */\nfunction mutationTarget(target: unknown): MutationTarget {\n if (isEntityTable(target)) {\n const mgmt = getTableMgmt(target);\n return { mgmt, name: mgmt.meta.type, columns: mgmt.meta.columns, meta: mgmt.meta };\n }\n if (isCustomTable(target)) {\n const mgmt = getTableMgmt(target);\n return { mgmt, name: mgmt.tableName, columns: mgmt.columns, meta: undefined };\n }\n return fail(\"A mutation target must be a table\");\n}\n\n/** SQL mutations require complete physical metadata. */\nfunction requireColumnMetadata(target: MutationTarget, column: Column): void {\n if (\n typeof column.sqlNullable !== \"boolean\" ||\n typeof column.hasDefault !== \"boolean\" ||\n typeof column.isGenerated !== \"boolean\"\n )\n fail(`Missing physical metadata for ${target.name}.${column.columnName}; run codegen`);\n}\n\n/** Validates every supplied key, including undefined fields, before pruning omitted values. */\nfunction assignments(target: MutationTarget, value: unknown, operation: \"insert\" | \"update\"): [string, unknown][] {\n if (!value || typeof value !== \"object\" || Array.isArray(value) || isExpr(value) || isEntity(value))\n fail(`${operation} assignments must be a field POJO`);\n const entries = Object.entries(value);\n for (const [key] of entries) writableField(target, key, operation);\n checkPojoKeys(value, Object.keys(target.columns), `${operation} assignments`);\n const defined = entries.filter((entry) => entry[1] !== undefined);\n if (!defined.length) fail(`${operation} requires at least one defined field; empty rows/sets are not DEFAULT VALUES`);\n return defined;\n}\n\n/**\n * Applies physical write restrictions, not ORM-derived, protected, or business-immutable flags.\n *\n * The primary-key and generated checks only sharpen the message: `Column` already denies both through\n * `insert: \"never\"` and `update: false`, for declared custom columns as well as generated ones.\n */\nfunction writableField(target: MutationTarget, key: string, operation: \"insert\" | \"update\"): Column {\n const column = Object.hasOwn(target.columns, key) ? target.columns[key] : undefined;\n if (!column) fail(`Unsupported SQL mutation field ${target.name}.${key}`);\n if (operation === \"update\" && column.columnName === \"id\") fail(\"UPDATE primary-key assignments are not supported\");\n if (column.isGenerated) fail(`Generated field ${target.name}.${key} is omit-only`);\n if (operation === \"update\" ? !column.update : column.insert === \"never\")\n fail(`Unsupported SQL mutation field ${target.name}.${key}`);\n return column;\n}\n\n/**\n * Classifies SQL expressions and SQL NULL before invoking the column's entity-independent write codec.\n * Normalizes public PK/FK ids to internal tagged ids using the target entity's idType.\n *\n * A custom table's columns never carry `idMetadata`, so they take the literal path below unchanged.\n */\nfunction assignmentToSql(target: MutationTarget, column: Column, value: unknown, ctx: Ctx): SqlFragment {\n if (isExpr(value)) return asNode(value).toSql(ctx);\n if (value === null) {\n if (!column.sqlNullable) fail(`${target.name}.${column.columnName} is physically NOT NULL`);\n return { sql: \"NULL\", bindings: [], refs: [] };\n }\n if (column.idMetadata) {\n const other = column.idMetadata();\n if (isEntity(value)) {\n if (column.columnName === \"id\" || !(value instanceof other.cstr)) fail(`Expected a ${other.type} reference`);\n if (value.isNewEntity || value.idTaggedMaybe === undefined)\n fail(`Cannot reference an unflushed ${other.type}, even with an assigned ID`);\n value = value.idTaggedMaybe;\n } else if (typeof value !== (other.idType === \"number\" ? \"number\" : \"string\")) {\n fail(`Expected a persisted ${other.type} or its ID; nested creation is not supported`);\n } else {\n // Public untagged TEXT ids may contain delimiters or start with the entity tag.\n value =\n other.idType === \"untagged-string\"\n ? keyToTaggedId(other, value as string)\n : toTaggedId(other, value as string | number);\n }\n }\n if (!column.codec.mapToDbValue)\n fail(`The codec for ${target.name}.${column.columnName} does not support SQL value writes`);\n return { sql: \"?\", bindings: [column.mapToDbValue(value)], refs: [] };\n}\n\n/** Checks the user predicate independently so metadata filters cannot turn a pruned guard into consent. */\nfunction mutationCondition(value: unknown, ctx: Ctx): SqlFragment | undefined {\n if (isExpr(value)) return asNode(value).toSql(ctx);\n if (Array.isArray(value)) return conditionToSql({ and: value }, ctx, true);\n return conditionToSql(value as SqlCondition | undefined, ctx, true);\n}\n"],"mappings":";;;;;;;;;;;AAqMA,SAAgB,WAAW,KAAuB;CAChD,OACE,OAAO,QAAQ,YACf,QAAQ,QACR,CAAC,iBAAiB,GAAG,KACrB;EAAC;EAAU;EAAU;CAAQ,CAAC,CAAC,MAAM,QAAQ,OAAO,GAAG;AAE3D;;;;;;AAOA,SAAgB,eAAe,KAAgC;CAC7D,IAAI,CAAC,WAAW,GAAG,GAAG,OAAO,eAAe,GAAG;CAC/C,MAAM,YAAY;CAClB,MAAM,QAAQ;EAAC;EAAU;EAAU;CAAQ,CAAC,CAAC,QAAQ,QAAQ,OAAO,SAAS;CAC7E,IAAI,MAAM,WAAW,GAAG,KAAK,gEAAgE;CAC7F,MAAM,YAAY,MAAM;CACxB,MAAM,UACJ,cAAc,WACV;EAAC;EAAU;EAAU;EAAQ;EAAa;CAAM,IAChD;EACE;EACA;EACA;EACA;EACA;EACA;EACA,GAAI,cAAc,WAAW,CAAC,KAAK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AQ,MAAM;EAChB,OAAO,IAAI,OAAO,WAAW,MAAM,WAAW,WAAW,WAAW,WAClE,KAAK,wBAAwB,MAAM,KAAK,6CAA6C;OAGrF,QACE,MAAM,WAAW,oBACb,cAAc,OAAO,KAAe,IACpC,WAAW,OAAO,KAAwB;CAEpD;CACA,IAAI,CAAC,OAAO,MAAM,cAChB,KAAK,iBAAiB,OAAO,KAAK,GAAG,OAAO,WAAW,mCAAmC;CAC5F,OAAO;EAAE,KAAK;EAAK,UAAU,CAAC,OAAO,aAAa,KAAK,CAAC;EAAG,MAAM,CAAC;CAAE;AACtE;;AAGA,SAAS,kBAAkB,OAAgB,KAAmC;CAC5E,IAAI,OAAO,KAAK,GAAG,OAAO,OAAO,KAAK,CAAC,CAAC,MAAM,GAAG;CACjD,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,eAAe,EAAE,KAAK,MAAM,GAAG,KAAK,IAAI;CACzE,OAAO,eAAe,OAAmC,KAAK,IAAI;AACpE"}
|
|
1
|
+
{"version":3,"file":"execute.js","names":[],"sources":["../../../src/queries/sql/execute.ts"],"sourcesContent":["import type { DriverQueryResult } from \"src/drivers/Driver.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport type { IdOf } from \"src/EntityManager.ts\";\nimport type { EntityMetadata } from \"src/EntityMetadata.ts\";\nimport { keyToTaggedId, toTaggedId } from \"src/keys.ts\";\nimport type { SqlCondition } from \"src/queries/conditions.ts\";\nimport { AliasAssigner } from \"src/queries/sql/AliasAssigner.ts\";\nimport {\n type CustomColumnInputs,\n type CustomColumnValue,\n type CustomColumnsOf,\n type CustomTableFor,\n} from \"src/queries/sql/custom.ts\";\nimport { type ExprBrand, type ExprLike, type SqlFragment, asNode, exprBrand, isExpr } from \"src/queries/sql/Expr.ts\";\nimport { kq, safeKq } from \"src/queries/sql/keywords.ts\";\nimport {\n type CheckReadQuery,\n type CheckScope,\n type CheckSetQuery,\n Ctx,\n type EntityHydrator,\n type NameOf,\n type Plan,\n type Query,\n type QueryJoinInput,\n type QueryRow,\n type ReadQueryRow,\n type SetOperand,\n type SetOperation,\n type SetQuery,\n type Subquery,\n type WithInput,\n checkPojoKeys,\n conditionToSql,\n entityQueryBrand,\n injectedConditions,\n isReadQueryValue,\n parseNestedQuery,\n parseUserQuery,\n prependCtes,\n projectionToSql,\n registerCtes,\n subqueryBrand,\n} from \"src/queries/sql/query.ts\";\nimport {\n type TableFor,\n type TableSourceMgmt,\n getTableMgmt,\n isCustomTable,\n isEntityTable,\n tableMgmt,\n tableSqlName,\n} from \"src/queries/sql/Tables.ts\";\nimport type { Column, ColumnDescriptors } from \"src/serde/columns.ts\";\nimport type { ColumnsOf, TypeMapEntry } from \"src/typeMap.ts\";\nimport { fail } from \"src/utils.ts\";\n\n/** The native command count and decoded rows from one immediate SQL statement. */\nexport interface ExecuteResult<R> {\n rowCount: number;\n rows: R[];\n}\n\n/** A mutation's RETURNING projection: one SQL expression or a named object of expressions. */\nexport type MutationReturning = (ExprLike<unknown> | Readonly<Record<string, ExprLike<unknown>>>) & {\n readonly [tableMgmt]?: never;\n readonly [subqueryBrand]?: never;\n readonly [entityQueryBrand]?: never;\n};\n\n/** SQL INSERT inputs, based on physical storage rather than entity creation options. */\nexport type InsertValues<T extends Entity> = {\n [K in RequiredInsertKey<T>]: Assignment<T, K>;\n} & {\n [K in Exclude<InsertKey<T>, RequiredInsertKey<T>>]?: Assignment<T, K> | undefined;\n};\n\n/** SQL UPDATE inputs include persisted derived columns, but never primary keys. */\nexport type UpdateValues<T extends Entity> = {\n [K in UpdateKey<T>]?: Assignment<T, K> | undefined;\n};\n\n/** A reusable INSERT POJO; use a concrete Q for annotated INSERT SELECT source checking. */\nexport type InsertStatement<\n T extends Entity,\n R extends MutationReturning | undefined = MutationReturning | undefined,\n Q extends SetOperand = Query<InsertProjection<T>, []> | Subquery<InsertSourceRow<T>, string>,\n> = {\n readonly insert: MutationTargetTable<T>;\n readonly returning?: R;\n readonly update?: never;\n readonly delete?: never;\n readonly set?: never;\n readonly where?: never;\n readonly allowAll?: never;\n readonly softDeletes?: never;\n /** CTEs to add to a `WITH` before the INSERT; see `Clauses.with`. */\n readonly with?: WithInput;\n} & NoMutationReadClauses &\n (\n | { readonly values: readonly InsertValues<T>[]; readonly from?: never }\n | { readonly from: Q & CheckInsertSource<T, Q>; readonly values?: never }\n );\n\n/** A reusable guarded UPDATE POJO. Undefined assignments leave existing columns unchanged. */\nexport type UpdateStatement<\n T extends Entity,\n R extends MutationReturning | undefined = MutationReturning | undefined,\n> = {\n readonly update: MutationTargetTable<T>;\n readonly set: UpdateValues<T>;\n readonly returning?: R;\n readonly insert?: never;\n readonly delete?: never;\n readonly values?: never;\n readonly from?: never;\n /** CTEs to add to a `WITH` before the UPDATE; see `Clauses.with`. */\n readonly with?: WithInput;\n} & MutationFilter &\n NoMutationReadClauses;\n\n/** A reusable guarded physical DELETE POJO, not an ORM soft delete. */\nexport type DeleteStatement<\n T extends Entity,\n R extends MutationReturning | undefined = MutationReturning | undefined,\n> = {\n readonly delete: MutationTargetTable<T>;\n readonly returning?: R;\n readonly insert?: never;\n readonly update?: never;\n readonly values?: never;\n readonly from?: never;\n readonly set?: never;\n /** CTEs to add to a `WITH` before the DELETE; see `Clauses.with`. */\n readonly with?: WithInput;\n} & MutationFilter &\n NoMutationReadClauses;\n\n/** Public statement annotations retain the target's physical field policy. */\nexport type MutationStatement<\n T extends Entity,\n R extends MutationReturning | undefined = MutationReturning | undefined,\n> = InsertStatement<T, R> | UpdateStatement<T, R> | DeleteStatement<T, R>;\n\n/** Inference starts with the literal POJO; CheckMutation checks its target and every supplied key. */\nexport type MutationInput = (\n | { readonly insert: TableFor<Entity>; readonly values: readonly object[]; readonly from?: never }\n | { readonly insert: TableFor<Entity>; readonly from: SetOperand; readonly values?: never }\n | { readonly update: TableFor<Entity>; readonly set: object }\n | { readonly delete: TableFor<Entity> }\n | {\n readonly insert: CustomTableFor;\n readonly values: readonly object[];\n readonly from?: never;\n }\n | { readonly insert: CustomTableFor; readonly from: SetOperand; readonly values?: never }\n | { readonly update: CustomTableFor; readonly set: object }\n | { readonly delete: CustomTableFor }\n) & { readonly returning?: MutationReturning; readonly with?: WithInput } & MutationFilter;\n\n/** Without RETURNING the row type is never; scalar expressions produce scalar rows. */\nexport type MutationRow<M> = M extends { readonly returning?: infer R }\n ? R extends MutationReturning\n ? R extends ExprLike<unknown>\n ? QueryRow<R>\n : { -readonly [K in keyof QueryRow<R>]: QueryRow<R>[K] }\n : never\n : never;\n\n/** Checks nonliteral statements as well as fresh literals without widening their inferred result. */\nexport type CheckMutation<M> = M extends unknown\n ? [CustomColumnsOf<TargetTable<M>>] extends [never]\n ? TargetEntity<M> extends infer T extends Entity\n ? TypeMapEntry<T, \"supportsEmExecute\"> extends true\n ? { readonly [K in keyof M]: K extends MutationClause<M> ? unknown : never } & {\n readonly returning?: M extends { readonly returning?: infer R }\n ? CheckReturning<R, NameOf<TargetTable<M>>>\n : never;\n } & (\n | (M extends { readonly values: infer V extends readonly unknown[] }\n ? { readonly values: CheckValues<InsertValues<T>, V> }\n : never)\n | (M extends { readonly from: infer Q extends SetOperand }\n ? { readonly from: CheckInsertSource<T, Q> }\n : never)\n | (M extends { readonly set: infer V }\n ? { readonly set: CheckAssignments<V, UpdateValues<T>, NameOf<TargetTable<M>>> }\n : never)\n | (M extends { readonly delete: unknown } ? unknown : never)\n )\n : \"SQL mutations require a supported non-inherited target and regenerated metadata\"\n : never\n : CheckCustomMutation<M>\n : never;\n\n/** Classifies mutation roots before EntityManager applies write permissions, including malformed roots. */\nexport function isMutation(arg: unknown): boolean {\n return (\n typeof arg === \"object\" &&\n arg !== null &&\n !isReadQueryValue(arg) &&\n [\"insert\", \"update\", \"delete\"].some((key) => key in arg)\n );\n}\n\n/**\n * Compiles one immediate statement using the read compiler's scopes, projections, and codecs.\n * INSERT SELECT keeps source rows in PostgreSQL; only RETURNING rows pass through JS decoders.\n * An undefined plan represents a validated standalone empty VALUES array, not DEFAULT VALUES.\n */\nexport function parseStatement(arg: unknown): Plan | undefined {\n if (!isMutation(arg)) return parseUserQuery(arg);\n const statement = arg as Record<string, unknown>;\n const roots = [\"insert\", \"update\", \"delete\"].filter((key) => key in statement);\n if (roots.length !== 1) fail(\"A mutation requires exactly one insert, update, or delete root\");\n const operation = roots[0];\n const allowed =\n operation === \"insert\"\n ? [\"insert\", \"values\", \"from\", \"returning\", \"with\"]\n : [\n operation,\n \"where\",\n \"allowAll\",\n \"softDeletes\",\n \"returning\",\n \"with\",\n ...(operation === \"update\" ? [\"set\"] : []),\n ];\n checkPojoKeys(statement, allowed, `SQL ${operation}`);\n const target = mutationTarget(statement[operation]);\n const { meta } = target;\n if (meta) {\n if (meta.inheritanceType || meta.baseType || meta.baseTypes.length || meta.subTypes.length) {\n fail(\"SQL mutations do not support CTI/STI targets or inherited table families\");\n }\n if (meta.supportsEmExecute !== true)\n fail(`SQL mutations require supported physical metadata for ${meta.type}; run codegen`);\n // Every column is checked here, so the writable-column lookups below can trust their metadata.\n for (const column of Object.values(meta.columns)) requireColumnMetadata(target, column);\n } else if (statement.softDeletes !== undefined) {\n fail(\"Custom table mutations do not support softDeletes\");\n }\n const fields = Object.entries(target.columns);\n const assigner = new AliasAssigner();\n // A CTE is in scope for the whole statement, so its scope is the parent of every other one here. It\n // deliberately holds no target alias, which is what lets INSERT VALUES cells and the INSERT SELECT\n // source read the CTEs without also seeing the row being written.\n const withCtx = new Ctx(assigner, undefined);\n const ctes = registerCtes(statement, withCtx, assigner);\n // Aliases the rest of the statement reads, so an unread CTE prunes like it does on a read query.\n const refs: string[] = [];\n const ctx = new Ctx(assigner, withCtx);\n const alias = assigner.getAlias(target.mgmt.tableName);\n ctx.register(target.mgmt, alias);\n const returning = statement.returning === undefined ? undefined : projectionToSql(statement.returning, ctx);\n if (returning) for (const select of returning.selects) refs.push(...select.refs);\n let sql = `${operation === \"delete\" ? \"DELETE FROM\" : operation.toUpperCase() + (operation === \"insert\" ? \" INTO\" : \"\")} ${tableSqlName(target.mgmt)} AS ${kq(alias)}`;\n const bindings: unknown[] = [];\n if (operation === \"insert\") {\n if (\"values\" in statement === \"from\" in statement) fail(\"INSERT requires exactly one of values or from\");\n const required = fields.filter(([, column]) => column.insert === \"required\");\n if (\"values\" in statement) {\n if (!Array.isArray(statement.values)) fail(\"INSERT values must be an array of field POJOs\");\n const rows = statement.values;\n // A VALUES cell *is* the new row, so there is no existing row for it to read: this scope skips\n // the `ctx.register(mgmt, alias)` above, so a cell naming the target fails instead of emitting a\n // `b` with no FROM clause. I.e. an UPDATE can say `set: { title: b.title }`; an INSERT cannot.\n // A value subquery still works, because it brings its own sources, and the parent here is the CTE\n // scope rather than `ctx`, so a cell can read a `with` entry but not the row being written.\n const valuesCtx = new Ctx(assigner, withCtx);\n const entries = rows.map((row) => assignments(target, row, \"insert\"));\n for (const row of entries) {\n for (const [key] of required) {\n if (!row.some((entry) => entry[0] === key)) fail(`INSERT requires ${target.name}.${key}`);\n }\n }\n if (rows.length === 0) return undefined;\n const keys = fields\n .filter(([key]) => entries.some((row) => row.some((entry) => entry[0] === key)))\n .map(([key, field]) => [key, field.columnName] as const);\n sql += ` (${keys.map(([, column]) => kq(column)).join(\", \")}) VALUES `;\n sql += entries\n .map((row) => {\n const cells = keys.map(([key]) => {\n const entry = row.find((entry) => entry[0] === key);\n if (!entry) return \"DEFAULT\";\n const cell = assignmentToSql(target, writableField(target, key, \"insert\"), entry[1], valuesCtx);\n bindings.push(...cell.bindings);\n refs.push(...cell.refs);\n return cell.sql;\n });\n return `(${cells.join(\", \")})`;\n })\n .join(\", \");\n } else {\n const source = parseNestedQuery(statement.from, withCtx, assigner);\n if (source.output.kind !== \"pojo\") fail(\"INSERT SELECT requires named POJO output columns\");\n const columns = source.output.columns;\n for (const [key] of required) {\n if (!columns.some((column) => column[0] === key)) {\n fail(`INSERT requires ${target.name}.${key}`);\n }\n }\n for (const [key, expr] of columns) {\n const field = writableField(target, key, \"insert\");\n const left = field.outputType;\n const right = expr.outputType;\n if (\n !left ||\n !right ||\n left.dbType !== right.dbType ||\n left.domain !== right.domain ||\n left.idMeta !== right.idMeta\n ) {\n fail(`INSERT SELECT ${target.name}.${key} has incompatible or unknown storage codecs`);\n }\n if (!field.sqlNullable && expr.sqlNullable === true)\n fail(`INSERT SELECT ${target.name}.${key} cannot accept a nullable output`);\n }\n const keys = fields\n .filter(([key]) => columns.some((column) => column[0] === key))\n .map(([key, field]) => [key, field.columnName] as const);\n const sourceAlias = safeKq(assigner.getLiteralAlias(\"sq\"));\n sql += ` (${keys.map(([, column]) => kq(column)).join(\", \")}) SELECT ${keys.map(([key]) => `${sourceAlias}.${safeKq(key)}`).join(\", \")} FROM (${source.sql}) AS ${sourceAlias}`;\n bindings.push(...source.bindings);\n refs.push(...source.outerRefs);\n }\n } else {\n if (statement.allowAll !== undefined && typeof statement.allowAll !== \"boolean\") fail(\"allowAll must be a boolean\");\n if (\n statement.softDeletes !== undefined &&\n statement.softDeletes !== \"include\" &&\n statement.softDeletes !== \"exclude\"\n )\n fail(\"softDeletes must be 'include' or 'exclude'\");\n const whereCondition = mutationCondition(statement.where, ctx);\n if (Object.hasOwn(statement, \"where\") && !whereCondition && statement.allowAll !== true)\n fail(\"UPDATE and DELETE require allowAll: true when a supplied where is undefined or fully pruned\");\n if (operation === \"update\") {\n const entries = assignments(target, statement.set, \"update\");\n sql +=\n \" SET \" +\n entries\n .map((entry) => {\n const [key, value] = entry;\n const field = writableField(target, key, \"update\");\n const cell = assignmentToSql(target, field, value, ctx);\n bindings.push(...cell.bindings);\n refs.push(...cell.refs);\n return `${kq(field.columnName)} = ${cell.sql}`;\n })\n .join(\", \");\n }\n const injected = meta\n ? conditionToSql({ and: injectedConditions({ meta, alias }, statement.softDeletes ?? \"exclude\") }, ctx, true)\n : undefined;\n const conditions = [whereCondition, injected].filter((condition) => condition !== undefined);\n if (conditions.length) {\n sql += ` WHERE ${conditions.map((condition) => `(${condition.sql})`).join(\" AND \")}`;\n for (const condition of conditions) {\n bindings.push(...condition.bindings);\n refs.push(...condition.refs);\n }\n }\n }\n if (returning) {\n sql += ` RETURNING ${returning.selects.map((select) => select.sql).join(\", \")}`;\n for (const select of returning.selects) bindings.push(...select.bindings);\n }\n const withCtes = prependCtes(ctes, new Set(refs), sql, bindings);\n return {\n sql: withCtes.sql,\n bindings: withCtes.bindings,\n outerRefs: [],\n output: returning?.output ?? { kind: \"pojo\", columns: [] },\n decodeRows: returning?.decodeRows ?? (() => []),\n };\n}\n\n/** Retains native counts even when no rows return, and propagates decoding failures after execution. */\nexport function decodeStatementResult(\n em: EntityHydrator,\n plan: Plan,\n result: DriverQueryResult,\n): ExecuteResult<unknown> {\n if (typeof result.rowCount !== \"number\" || !Number.isInteger(result.rowCount) || result.rowCount < 0)\n fail(\"The driver did not return a numeric command rowCount\");\n return { rowCount: result.rowCount, rows: plan.decodeRows(em, result.rows) };\n}\n\n/** An entity table whose generated metadata permits direct SQL mutations. */\ntype MutationTargetTable<T extends Entity> = TableFor<T> &\n (TypeMapEntry<T, \"supportsEmExecute\"> extends true ? unknown : never);\n\n/**\n * What a mutation needs from its target, an entity table or a `declareTable` table alike.\n *\n * Both kinds describe their storage with the same `Column`, so the INSERT/UPDATE/DELETE compiler reads\n * `columns` without caring which it has; `meta` is the one thing only an entity table brings.\n */\ninterface MutationTarget {\n /** The SQL identity, for the alias and the qualified table name; also the key `Ctx` registers. */\n mgmt: TableSourceMgmt;\n /** Names the target in errors: the entity type, i.e. `Book`, or the table name, i.e. `book_reviews`. */\n name: string;\n columns: ColumnDescriptors;\n /** Entity tables only; a custom table has no soft-delete, inheritance, or ID-tagging policy. */\n meta: EntityMetadata | undefined;\n}\n\n/** Shared filtering and full-table consent clauses for UPDATE and DELETE. */\ntype MutationFilter = {\n /**\n * An `{ and: [...] }` or `{ or: [...] }` group, a boolean expression, or a bare condition such as `a.age.gte(18)`.\n *\n * Arrays are shorthand for `{ and: [...] }`; undefined conditions are pruned.\n */\n readonly where?: SqlCondition | ExprLike<boolean> | readonly (SqlCondition | undefined)[];\n /** Allows a supplied where to be undefined or fully pruned; unnecessary when where is omitted. */\n readonly allowAll?: boolean;\n readonly softDeletes?: \"include\" | \"exclude\";\n};\n\n/** Read-only query clauses that mutations explicitly reject. */\ntype NoMutationReadClauses = Partial<\n Record<\n | \"select\"\n | \"join\"\n | \"groupBy\"\n | \"having\"\n | \"orderBy\"\n | \"limit\"\n | \"offset\"\n | \"distinct\"\n | \"pruneJoins\"\n | \"as\"\n | \"union\"\n | \"unionAll\"\n | \"intersect\"\n | \"intersectAll\"\n | \"except\"\n | \"exceptAll\"\n | \"ctes\"\n | \"using\"\n | \"onConflict\",\n never\n >\n>;\n\n/** Column keys allowed in INSERT, i.e. Book's optional `id` and required `authorId`. */\ntype InsertKey<T> = {\n [K in keyof ColumnsOf<T>]: ColumnsOf<T>[K] extends { insert: \"required\" | \"optional\" } ? K : never;\n}[keyof ColumnsOf<T>];\n\n/** Column keys that each INSERT row must supply, i.e. Book's `authorId` despite its ORM default. */\ntype RequiredInsertKey<T> = {\n [K in keyof ColumnsOf<T>]: ColumnsOf<T>[K] extends { insert: \"required\" } ? K : never;\n}[keyof ColumnsOf<T>];\n\n/** Column keys allowed in UPDATE SET, i.e. Book's `title` and `authorId`, but not `id`. */\ntype UpdateKey<T> = {\n [K in keyof ColumnsOf<T>]: ColumnsOf<T>[K] extends { update: true } ? K : never;\n}[keyof ColumnsOf<T>];\n\n/** A column's domain value before SQL nullability is added, i.e. Book's `id` is BookId and `authorId` is AuthorId. */\ntype DomainValue<T, K extends keyof ColumnsOf<T>> = K extends \"id\"\n ? IdOf<T>\n : ColumnsOf<T>[K] extends { entity: infer U }\n ? IdOf<U>\n : ColumnsOf<T>[K] extends { type: infer V }\n ? V\n : never;\n\n/** A modeled column's domain value with SQL nullability applied. */\ntype SqlValue<T, K extends keyof ColumnsOf<T>> =\n | DomainValue<T, K>\n | (ColumnsOf<T>[K] extends { nullable: true } ? null : never);\n\n/** A modeled-column value, entity reference, or SQL expression that produces one. */\ntype Assignment<T, K extends keyof ColumnsOf<T>> =\n | SqlValue<T, K>\n | ExprLike<SqlValue<T, K>>\n | (K extends \"id\" ? never : ColumnsOf<T>[K] extends { entity: infer U } ? U : never);\n\n/** A custom column's declared value with SQL nullability applied. */\ntype CustomSqlValue<I> = CustomColumnValue<I> | (I extends { nullable: true } ? null : never);\n\n/** A custom-column value or SQL expression that produces one. */\ntype CustomAssignment<I> = CustomSqlValue<I> | ExprLike<CustomSqlValue<I>>;\n\n/** Custom-column keys accepted by INSERT, excluding generated columns. */\ntype CustomInsertKey<C extends CustomColumnInputs> = {\n [K in keyof C]: C[K] extends { generated: true } ? never : K;\n}[keyof C];\n\n/** Custom-column keys each INSERT row must supply because they have no default and are not nullable. */\ntype CustomRequiredInsertKey<C extends CustomColumnInputs> = {\n [K in CustomInsertKey<C>]: C[K] extends { nullable: true } | { hasDefault: true } ? never : K;\n}[CustomInsertKey<C>];\n\n/** Custom-column keys accepted by UPDATE, excluding generated columns and the physical primary key. */\ntype CustomUpdateKey<C extends CustomColumnInputs> = {\n [K in keyof C]: C[K] extends { generated: true }\n ? never\n : K extends \"id\"\n ? never\n : C[K] extends { columnName: \"id\" }\n ? never\n : K;\n}[keyof C];\n\n/** Values accepted by INSERT for a custom table's declared columns. */\ntype CustomInsertValues<C extends CustomColumnInputs> = {\n [K in CustomRequiredInsertKey<C>]: CustomAssignment<C[K]>;\n} & {\n [K in Exclude<CustomInsertKey<C>, CustomRequiredInsertKey<C>>]?: CustomAssignment<C[K]> | undefined;\n};\n\n/** Assignments accepted by UPDATE for a custom table's writable columns. */\ntype CustomUpdateValues<C extends CustomColumnInputs> = {\n [K in CustomUpdateKey<C>]?: CustomAssignment<C[K]> | undefined;\n};\n\n/** Named row shape that an INSERT SELECT source must produce for a custom table. */\ntype CustomInsertSourceRow<C extends CustomColumnInputs> = {\n [K in CustomRequiredInsertKey<C>]: CustomSqlValue<C[K]>;\n} & {\n [K in Exclude<CustomInsertKey<C>, CustomRequiredInsertKey<C>>]?: CustomSqlValue<C[K]>;\n};\n\n/** Named row shape that an entity INSERT SELECT source must produce. */\ntype InsertSourceRow<T> = { [K in RequiredInsertKey<T>]: SqlValue<T, K> } & {\n [K in Exclude<InsertKey<T>, RequiredInsertKey<T>>]?: SqlValue<T, K>;\n};\n\n/** Named expression projection accepted from an entity INSERT SELECT source. */\ntype InsertProjection<T> = { [K in RequiredInsertKey<T>]: ExprLike<SqlValue<T, K>> } & {\n [K in Exclude<InsertKey<T>, RequiredInsertKey<T>>]?: ExprLike<SqlValue<T, K>>;\n};\n\n/** Collects the keys from every member of a union instead of only their shared keys. */\ntype UnionKeys<V> = V extends unknown ? keyof V : never;\n\n/** Collects every alternative before scope checking; a valid branch cannot hide an unrelated alias. */\ntype UnionValue<V, K extends PropertyKey> = V extends unknown ? (K extends keyof V ? V[K] : never) : never;\n\n/** Extracts the source names carried by a SQL expression. */\ntype ExprSource<V> = V extends { readonly [exprBrand]: ExprBrand<unknown, infer Src> } ? Src : never;\n\n/** Rejects expressions that reference tables outside the statement's allowed scope. */\ntype CheckExprScope<V, Scope> =\n string extends ExprSource<V>\n ? unknown\n : [Exclude<ExprSource<V>, Scope>] extends [never]\n ? unknown\n : \"Expression source is not in the statement scope\";\n\n/** Extracts each expression from a scalar or named RETURNING projection. */\ntype ReturningExpr<R> = R extends ExprLike<unknown> ? R : R extends undefined ? never : R[keyof R];\n\n/** Detects an empty named RETURNING projection. */\ntype EmptyReturning<R> = R extends object ? (keyof R extends never ? true : false) : false;\n\n/** Rejects empty RETURNING objects and expressions outside the target scope. */\ntype CheckReturning<R, Scope> = true extends EmptyReturning<R> ? never : CheckExprScope<ReturningExpr<R>, Scope>;\n\n/** Validates assignment keys, values, and expression sources without distributing union inputs. */\ntype CheckAssignments<V, Allowed, Scope> = [Exclude<UnionKeys<V>, keyof Allowed>] extends [never]\n ? Allowed & {\n [K in UnionKeys<V>]?: CheckExprScope<UnionValue<V, K>, Scope>;\n }\n : \"SQL assignments have unknown target fields\";\n\n/**\n * Checks every INSERT row in a readonly collection against the target's writable columns.\n *\n * `Allowed` is the target's accepted assignments, i.e. `InsertValues<T>` for an entity table and\n * `CustomInsertValues<C>` for a declared one. The scope is `never` because a VALUES cell cannot read\n * the row being written.\n */\ntype CheckValues<Allowed, V extends readonly unknown[]> = readonly CheckAssignments<V[number], Allowed, never>[];\n\n/**\n * Checks a custom-table mutation against its declared primitive columns.\n *\n * Only clauses for the selected operation are allowed, and `softDeletes` is rejected because there is no entity\n * policy. Assignments use declaration keys and honor nullability, defaults, and generated columns. INSERT VALUES\n * cannot read the target row, while UPDATE SET and RETURNING can. INSERT SELECT must be a valid named read with all\n * required columns and compatible declared value types; runtime checks also compare its SQL codecs and nullability.\n */\ntype CheckCustomMutation<M> = {\n // Reject clauses outside the selected operation, plus softDeletes because custom tables have no entity policy.\n readonly [K in keyof M]: K extends MutationClause<M> ? (K extends \"softDeletes\" ? never : unknown) : never;\n} & {\n readonly returning?: M extends { readonly returning?: infer R } ? CheckReturning<R, NameOf<TargetTable<M>>> : never;\n} &\n // INSERT VALUES checks every row against the custom table's writable columns.\n (\n | (M extends { readonly values: infer V extends readonly unknown[] }\n ? { readonly values: CheckValues<CustomInsertValues<CustomColumnsOf<TargetTable<M>>>, V> }\n : never)\n // INSERT SELECT checks the source's names, values, and expression scopes.\n | (M extends { readonly from: infer Q extends SetOperand }\n ? { readonly from: CheckCustomInsertSource<CustomColumnsOf<TargetTable<M>>, Q> }\n : never)\n // UPDATE checks assignments against writable columns and permits target-scoped expressions.\n | (M extends { readonly set: infer V }\n ? {\n readonly set: CheckAssignments<\n V,\n CustomUpdateValues<CustomColumnsOf<TargetTable<M>>>,\n NameOf<TargetTable<M>>\n >;\n }\n : never)\n // DELETE has no assignments or source that needs further type checking.\n | (M extends { readonly delete: unknown } ? unknown : never)\n );\n\n/**\n * Checks an INSERT SELECT's named outputs, required columns, values, and read source.\n *\n * `Row` is the row shape the source must produce and `Keys` the target's writable column keys, i.e.\n * `InsertSourceRow<T>` and `InsertKey<T>` for an entity table.\n */\ntype CheckInsertSourceOf<Row, Keys extends PropertyKey, Q> = SetOperand extends Q\n ? \"INSERT source type lost its select keys; use `satisfies Query` or `satisfies SetQuery` instead of a type annotation\"\n : ReadQueryRow<Q> extends Row\n ? Exclude<UnionKeys<ReadQueryRow<Q>>, Keys> extends never\n ? CheckReadQuery<Q> &\n CheckSourceScope<Q> &\n (Q extends SetQuery<readonly SetOperand[]> ? CheckSetQuery<Q> : unknown)\n : \"INSERT SELECT has unknown target fields\"\n : \"INSERT SELECT requires compatible values for all SQL-required fields\";\n\n/** Checks a custom INSERT SELECT against the table's declared writable columns. */\ntype CheckCustomInsertSource<C extends CustomColumnInputs, Q> = CheckInsertSourceOf<\n CustomInsertSourceRow<C>,\n CustomInsertKey<C>,\n Q\n>;\n\n/** Checks every SELECT expression against the tables visible within its read-query branch. */\ntype CheckSourceScope<Q> = Q extends { readonly select: infer S; readonly from: infer F }\n ? CheckScope<S, F, \"join\" extends keyof Q ? Extract<Q[keyof Q & \"join\"], QueryJoinInput> : []>\n : {\n [K in keyof Q]: K extends SetOperation\n ? Q[K] extends readonly unknown[]\n ? { [I in keyof Q[K]]: CheckSourceScope<Q[K][I]> }\n : unknown\n : unknown;\n };\n\n/** Checks an entity INSERT SELECT against the entity's writable columns. */\ntype CheckInsertSource<T, Q extends SetOperand> = CheckInsertSourceOf<InsertSourceRow<T>, InsertKey<T>, Q>;\n\n/** Extracts the entity type from any mutation target clause. */\ntype TargetEntity<M> = M extends\n | { readonly insert: TableFor<infer T> }\n | { readonly update: TableFor<infer T> }\n | { readonly delete: TableFor<infer T> }\n ? T\n : never;\n\n/** Extracts the table handle from any mutation target clause. */\ntype TargetTable<M> = M extends\n | { readonly insert: infer A }\n | { readonly update: infer A }\n | { readonly delete: infer A }\n ? A\n : never;\n\n/** Clauses permitted by the selected INSERT, UPDATE, or DELETE operation. */\ntype MutationClause<M> =\n | \"returning\"\n | \"with\"\n | (M extends { readonly insert: unknown }\n ? \"insert\" | (M extends { readonly values: unknown } ? \"values\" : \"from\")\n : \"where\" | \"allowAll\" | \"softDeletes\" | (M extends { readonly update: unknown } ? \"update\" | \"set\" : \"delete\"));\n\n/** Reads the writable columns from either kind of table handle, so the compiler has one target shape. */\nfunction mutationTarget(target: unknown): MutationTarget {\n if (isEntityTable(target)) {\n const mgmt = getTableMgmt(target);\n return { mgmt, name: mgmt.meta.type, columns: mgmt.meta.columns, meta: mgmt.meta };\n }\n if (isCustomTable(target)) {\n const mgmt = getTableMgmt(target);\n return { mgmt, name: mgmt.tableName, columns: mgmt.columns, meta: undefined };\n }\n return fail(\"A mutation target must be a table\");\n}\n\n/** SQL mutations require complete physical metadata. */\nfunction requireColumnMetadata(target: MutationTarget, column: Column): void {\n if (\n typeof column.sqlNullable !== \"boolean\" ||\n typeof column.hasDefault !== \"boolean\" ||\n typeof column.isGenerated !== \"boolean\"\n )\n fail(`Missing physical metadata for ${target.name}.${column.columnName}; run codegen`);\n}\n\n/** Validates every supplied key, including undefined fields, before pruning omitted values. */\nfunction assignments(target: MutationTarget, value: unknown, operation: \"insert\" | \"update\"): [string, unknown][] {\n if (!value || typeof value !== \"object\" || Array.isArray(value) || isExpr(value) || isEntity(value))\n fail(`${operation} assignments must be a field POJO`);\n const entries = Object.entries(value);\n for (const [key] of entries) writableField(target, key, operation);\n checkPojoKeys(value, Object.keys(target.columns), `${operation} assignments`);\n const defined = entries.filter((entry) => entry[1] !== undefined);\n if (!defined.length) fail(`${operation} requires at least one defined field; empty rows/sets are not DEFAULT VALUES`);\n return defined;\n}\n\n/**\n * Applies physical write restrictions, not ORM-derived, protected, or business-immutable flags.\n *\n * The primary-key and generated checks only sharpen the message: `Column` already denies both through\n * `insert: \"never\"` and `update: false`, for declared custom columns as well as generated ones.\n */\nfunction writableField(target: MutationTarget, key: string, operation: \"insert\" | \"update\"): Column {\n const column = Object.hasOwn(target.columns, key) ? target.columns[key] : undefined;\n if (!column) fail(`Unsupported SQL mutation field ${target.name}.${key}`);\n if (operation === \"update\" && column.columnName === \"id\") fail(\"UPDATE primary-key assignments are not supported\");\n if (column.isGenerated) fail(`Generated field ${target.name}.${key} is omit-only`);\n if (operation === \"update\" ? !column.update : column.insert === \"never\")\n fail(`Unsupported SQL mutation field ${target.name}.${key}`);\n return column;\n}\n\n/**\n * Classifies SQL expressions and SQL NULL before invoking the column's entity-independent write codec.\n * Normalizes public PK/FK ids to internal tagged ids using the target entity's idType.\n *\n * A custom table's columns never carry `idMetadata`, so they take the literal path below unchanged.\n */\nfunction assignmentToSql(target: MutationTarget, column: Column, value: unknown, ctx: Ctx): SqlFragment {\n if (isExpr(value)) return asNode(value).toSql(ctx);\n if (value === null) {\n if (!column.sqlNullable) fail(`${target.name}.${column.columnName} is physically NOT NULL`);\n return { sql: \"NULL\", bindings: [], refs: [] };\n }\n if (column.idMetadata) {\n const other = column.idMetadata();\n if (isEntity(value)) {\n if (column.columnName === \"id\" || !(value instanceof other.cstr)) fail(`Expected a ${other.type} reference`);\n if (value.isNewEntity || value.idTaggedMaybe === undefined)\n fail(`Cannot reference an unflushed ${other.type}, even with an assigned ID`);\n value = value.idTaggedMaybe;\n } else if (typeof value !== (other.idType === \"number\" ? \"number\" : \"string\")) {\n fail(`Expected a persisted ${other.type} or its ID; nested creation is not supported`);\n } else {\n // Public untagged TEXT ids may contain delimiters or start with the entity tag.\n value =\n other.idType === \"untagged-string\"\n ? keyToTaggedId(other, value as string)\n : toTaggedId(other, value as string | number);\n }\n }\n if (!column.codec.mapToDbValue)\n fail(`The codec for ${target.name}.${column.columnName} does not support SQL value writes`);\n return { sql: \"?\", bindings: [column.mapToDbValue(value)], refs: [] };\n}\n\n/** Checks the user predicate independently so metadata filters cannot turn a pruned guard into consent. */\nfunction mutationCondition(value: unknown, ctx: Ctx): SqlFragment | undefined {\n if (isExpr(value)) return asNode(value).toSql(ctx);\n if (Array.isArray(value)) return conditionToSql({ and: value }, ctx, true);\n return conditionToSql(value as SqlCondition | undefined, ctx, true);\n}\n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