joist-core 2.3.0-next.99 → 2.4.0

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.
Files changed (131) hide show
  1. package/build/EntityManager.cjs +1 -1
  2. package/build/EntityManager.cjs.map +1 -1
  3. package/build/EntityManager.d.cts +9 -8
  4. package/build/EntityManager.d.cts.map +1 -1
  5. package/build/EntityManager.d.mts +9 -8
  6. package/build/EntityManager.d.mts.map +1 -1
  7. package/build/EntityManager.js +1 -1
  8. package/build/EntityManager.js.map +1 -1
  9. package/build/dataloaders/findCountDataLoader.cjs +2 -0
  10. package/build/dataloaders/findCountDataLoader.cjs.map +1 -1
  11. package/build/dataloaders/findCountDataLoader.d.cts.map +1 -1
  12. package/build/dataloaders/findCountDataLoader.d.mts.map +1 -1
  13. package/build/dataloaders/findCountDataLoader.js +2 -0
  14. package/build/dataloaders/findCountDataLoader.js.map +1 -1
  15. package/build/dataloaders/findDataLoader.cjs +1 -0
  16. package/build/dataloaders/findDataLoader.cjs.map +1 -1
  17. package/build/dataloaders/findDataLoader.d.cts.map +1 -1
  18. package/build/dataloaders/findDataLoader.d.mts.map +1 -1
  19. package/build/dataloaders/findDataLoader.js +2 -1
  20. package/build/dataloaders/findDataLoader.js.map +1 -1
  21. package/build/dataloaders/findIdsDataLoader.cjs +2 -0
  22. package/build/dataloaders/findIdsDataLoader.cjs.map +1 -1
  23. package/build/dataloaders/findIdsDataLoader.d.cts.map +1 -1
  24. package/build/dataloaders/findIdsDataLoader.d.mts.map +1 -1
  25. package/build/dataloaders/findIdsDataLoader.js +2 -0
  26. package/build/dataloaders/findIdsDataLoader.js.map +1 -1
  27. package/build/dataloaders/findPaginatedDataLoader.cjs +2 -0
  28. package/build/dataloaders/findPaginatedDataLoader.cjs.map +1 -1
  29. package/build/dataloaders/findPaginatedDataLoader.d.cts.map +1 -1
  30. package/build/dataloaders/findPaginatedDataLoader.d.mts.map +1 -1
  31. package/build/dataloaders/findPaginatedDataLoader.js +2 -0
  32. package/build/dataloaders/findPaginatedDataLoader.js.map +1 -1
  33. package/build/index.cjs +6 -3
  34. package/build/index.cjs.map +1 -1
  35. package/build/index.d.cts +6 -4
  36. package/build/index.d.cts.map +1 -1
  37. package/build/index.d.mts +6 -4
  38. package/build/index.d.mts.map +1 -1
  39. package/build/index.js +6 -5
  40. package/build/index.js.map +1 -1
  41. package/build/keys.cjs +6 -1
  42. package/build/keys.cjs.map +1 -1
  43. package/build/keys.d.cts +3 -1
  44. package/build/keys.d.cts.map +1 -1
  45. package/build/keys.d.mts +3 -1
  46. package/build/keys.d.mts.map +1 -1
  47. package/build/keys.js +6 -2
  48. package/build/keys.js.map +1 -1
  49. package/build/queries/find/QueryParser.cjs +1 -2
  50. package/build/queries/find/QueryParser.cjs.map +1 -1
  51. package/build/queries/find/QueryParser.d.cts.map +1 -1
  52. package/build/queries/find/QueryParser.d.mts.map +1 -1
  53. package/build/queries/find/QueryParser.js +2 -3
  54. package/build/queries/find/QueryParser.js.map +1 -1
  55. package/build/queries/find/QueryVisitor.cjs +17 -0
  56. package/build/queries/find/QueryVisitor.cjs.map +1 -1
  57. package/build/queries/find/QueryVisitor.d.cts +3 -1
  58. package/build/queries/find/QueryVisitor.d.cts.map +1 -1
  59. package/build/queries/find/QueryVisitor.d.mts +3 -1
  60. package/build/queries/find/QueryVisitor.d.mts.map +1 -1
  61. package/build/queries/find/QueryVisitor.js +17 -1
  62. package/build/queries/find/QueryVisitor.js.map +1 -1
  63. package/build/queries/sql/Expr.cjs +18 -1
  64. package/build/queries/sql/Expr.cjs.map +1 -1
  65. package/build/queries/sql/Expr.d.cts +13 -3
  66. package/build/queries/sql/Expr.d.cts.map +1 -1
  67. package/build/queries/sql/Expr.d.mts +13 -3
  68. package/build/queries/sql/Expr.d.mts.map +1 -1
  69. package/build/queries/sql/Expr.js +18 -2
  70. package/build/queries/sql/Expr.js.map +1 -1
  71. package/build/queries/sql/JoinTree.cjs +72 -0
  72. package/build/queries/sql/JoinTree.cjs.map +1 -0
  73. package/build/queries/sql/JoinTree.d.cts +107 -0
  74. package/build/queries/sql/JoinTree.d.cts.map +1 -0
  75. package/build/queries/sql/JoinTree.d.mts +107 -0
  76. package/build/queries/sql/JoinTree.d.mts.map +1 -0
  77. package/build/queries/sql/JoinTree.js +71 -0
  78. package/build/queries/sql/JoinTree.js.map +1 -0
  79. package/build/queries/sql/Tables.cjs +103 -6
  80. package/build/queries/sql/Tables.cjs.map +1 -1
  81. package/build/queries/sql/Tables.d.cts +72 -13
  82. package/build/queries/sql/Tables.d.cts.map +1 -1
  83. package/build/queries/sql/Tables.d.mts +72 -13
  84. package/build/queries/sql/Tables.d.mts.map +1 -1
  85. package/build/queries/sql/Tables.js +101 -10
  86. package/build/queries/sql/Tables.js.map +1 -1
  87. package/build/queries/sql/custom.cjs +52 -0
  88. package/build/queries/sql/custom.cjs.map +1 -0
  89. package/build/queries/sql/custom.d.cts +85 -0
  90. package/build/queries/sql/custom.d.cts.map +1 -0
  91. package/build/queries/sql/custom.d.mts +85 -0
  92. package/build/queries/sql/custom.d.mts.map +1 -0
  93. package/build/queries/sql/custom.js +49 -0
  94. package/build/queries/sql/custom.js.map +1 -0
  95. package/build/queries/sql/execute.cjs +68 -28
  96. package/build/queries/sql/execute.cjs.map +1 -1
  97. package/build/queries/sql/execute.d.cts +110 -11
  98. package/build/queries/sql/execute.d.cts.map +1 -1
  99. package/build/queries/sql/execute.d.mts +110 -11
  100. package/build/queries/sql/execute.d.mts.map +1 -1
  101. package/build/queries/sql/execute.js +69 -29
  102. package/build/queries/sql/execute.js.map +1 -1
  103. package/build/queries/sql/expressions/types.d.cts +5 -5
  104. package/build/queries/sql/expressions/types.d.cts.map +1 -1
  105. package/build/queries/sql/expressions/types.d.mts +5 -5
  106. package/build/queries/sql/expressions/types.d.mts.map +1 -1
  107. package/build/queries/sql/keywords.cjs +1 -1
  108. package/build/queries/sql/keywords.cjs.map +1 -1
  109. package/build/queries/sql/keywords.d.cts +1 -1
  110. package/build/queries/sql/keywords.d.mts +1 -1
  111. package/build/queries/sql/keywords.js +1 -1
  112. package/build/queries/sql/keywords.js.map +1 -1
  113. package/build/queries/sql/query.cjs +100 -38
  114. package/build/queries/sql/query.cjs.map +1 -1
  115. package/build/queries/sql/query.d.cts +96 -46
  116. package/build/queries/sql/query.d.cts.map +1 -1
  117. package/build/queries/sql/query.d.mts +96 -46
  118. package/build/queries/sql/query.d.mts.map +1 -1
  119. package/build/queries/sql/query.js +102 -40
  120. package/build/queries/sql/query.js.map +1 -1
  121. package/build/queries/valueFilters.cjs +28 -36
  122. package/build/queries/valueFilters.cjs.map +1 -1
  123. package/build/queries/valueFilters.d.cts +2 -4
  124. package/build/queries/valueFilters.d.cts.map +1 -1
  125. package/build/queries/valueFilters.d.mts +2 -4
  126. package/build/queries/valueFilters.d.mts.map +1 -1
  127. package/build/queries/valueFilters.js +29 -36
  128. package/build/queries/valueFilters.js.map +1 -1
  129. package/build/serde/serde.cjs.map +1 -1
  130. package/build/serde/serde.js.map +1 -1
  131. package/package.json +2 -2
@@ -3,7 +3,8 @@ import { kq, safeKq } from "./keywords.js";
3
3
  import { asNode, isExpr } from "./Expr.js";
4
4
  import { fail } from "../../utils.js";
5
5
  import { AliasAssigner } from "./AliasAssigner.js";
6
- import { getTableMgmt, isTable } from "./Tables.js";
6
+ import "./custom.js";
7
+ import { getTableMgmt, isCustomTable, isEntityTable, isTable, tableSqlName } from "./Tables.js";
7
8
  import { Ctx, conditionToSql, injectedConditions, isReadQueryValue, parseNestedQuery, parseUserQuery, projectionToSql, pruneCtes, registerCtes, withFragment } from "./query.js";
8
9
  import { isEntity } from "../../Entity.js";
9
10
  //#region src/queries/sql/execute.ts
@@ -46,40 +47,44 @@ function parseStatement(arg) {
46
47
  ...operation === "update" ? ["set"] : []
47
48
  ], `SQL ${operation}`);
48
49
  const target = statement[operation];
49
- if (!isTable(target)) fail("A mutation target must be an entity table");
50
+ if (!isTable(target)) fail("A mutation target must be a table");
50
51
  const mgmt = getTableMgmt(target);
51
- const meta = mgmt.meta;
52
- if (meta.inheritanceType || meta.baseType || meta.baseTypes.length || meta.subTypes.length) fail("SQL mutations do not support CTI/STI targets or inherited table families");
53
- if (meta.supportsEmExecute !== true) fail(`SQL mutations require supported physical metadata for ${meta.type}; run codegen`);
54
- const fields = Object.entries(meta.columns);
55
- for (const [, field] of fields) requireColumnMetadata(meta, field);
52
+ const meta = isEntityTable(target) ? getTableMgmt(target).meta : void 0;
53
+ const custom = isCustomTable(target) ? getTableMgmt(target) : void 0;
54
+ if (meta) {
55
+ if (meta.inheritanceType || meta.baseType || meta.baseTypes.length || meta.subTypes.length) fail("SQL mutations do not support CTI/STI targets or inherited table families");
56
+ if (meta.supportsEmExecute !== true) fail(`SQL mutations require supported physical metadata for ${meta.type}; run codegen`);
57
+ for (const field of Object.values(meta.columns)) requireColumnMetadata(meta, field);
58
+ } else if (statement.softDeletes !== void 0) fail("Custom table mutations do not support softDeletes");
59
+ const fields = Object.entries(meta?.columns ?? custom.columns);
56
60
  const assigner = new AliasAssigner();
57
61
  const withCtx = new Ctx(assigner, void 0);
58
62
  const ctes = registerCtes(statement, withCtx, assigner);
59
63
  const refs = [];
60
64
  const ctx = new Ctx(assigner, withCtx);
61
- const alias = assigner.getAlias(meta.tableName);
65
+ const alias = assigner.getAlias(mgmt.tableName);
62
66
  ctx.register(mgmt, alias);
63
67
  const returning = statement.returning === void 0 ? void 0 : projectionToSql(statement.returning, ctx);
64
68
  if (returning) for (const select of returning.selects) refs.push(...select.refs);
65
- let sql = `${operation === "delete" ? "DELETE FROM" : operation.toUpperCase() + (operation === "insert" ? " INTO" : "")} ${kq(meta.tableName)} AS ${kq(alias)}`;
69
+ let sql = `${operation === "delete" ? "DELETE FROM" : operation.toUpperCase() + (operation === "insert" ? " INTO" : "")} ${tableSqlName(mgmt)} AS ${kq(alias)}`;
66
70
  const bindings = [];
67
71
  if (operation === "insert") {
68
72
  if ("values" in statement === "from" in statement) fail("INSERT requires exactly one of values or from");
69
73
  const required = fields.filter(([, column]) => column.insert === "required");
70
74
  if ("values" in statement) {
71
- const rows = Array.isArray(statement.values) ? statement.values : [statement.values];
75
+ if (!Array.isArray(statement.values)) fail("INSERT values must be an array of field POJOs");
76
+ const rows = statement.values;
72
77
  const valuesCtx = new Ctx(assigner, withCtx);
73
- const entries = rows.map((row) => assignments(meta, row, "insert"));
74
- for (const row of entries) for (const [key] of required) if (!row.some((entry) => entry[0] === key)) fail(`INSERT requires ${meta.type}.${key}`);
78
+ const entries = rows.map((row) => meta ? assignments(meta, row, "insert") : customAssignments(custom, row, "insert"));
79
+ for (const row of entries) for (const [key] of required) if (!row.some((entry) => entry[0] === key)) fail(`INSERT requires ${meta?.type ?? custom.tableName}.${key}`);
75
80
  if (rows.length === 0) return void 0;
76
- const keys = fields.filter(([key]) => entries.some((row) => row.some((entry) => entry[0] === key)));
77
- sql += ` (${keys.map(([, field]) => kq(field.columnName)).join(", ")}) VALUES `;
81
+ const keys = fields.filter(([key]) => entries.some((row) => row.some((entry) => entry[0] === key))).map(([key, field]) => [key, field.columnName]);
82
+ sql += ` (${keys.map(([, column]) => kq(column)).join(", ")}) VALUES `;
78
83
  sql += entries.map((row) => {
79
- return `(${keys.map(([key, field]) => {
84
+ return `(${keys.map(([key]) => {
80
85
  const entry = row.find((entry) => entry[0] === key);
81
86
  if (!entry) return "DEFAULT";
82
- const cell = assignmentToSql(meta, field, entry[1], valuesCtx);
87
+ const cell = meta ? assignmentToSql(meta, writableField(meta, key, "insert"), entry[1], valuesCtx) : customAssignmentToSql(custom, customWritableField(custom, key, "insert"), entry[1], valuesCtx);
83
88
  bindings.push(...cell.bindings);
84
89
  refs.push(...cell.refs);
85
90
  return cell.sql;
@@ -89,40 +94,40 @@ function parseStatement(arg) {
89
94
  const source = parseNestedQuery(statement.from, withCtx, assigner);
90
95
  if (source.output.kind !== "pojo") fail("INSERT SELECT requires named POJO output columns");
91
96
  const columns = source.output.columns;
92
- for (const [key] of required) if (!columns.some((column) => column[0] === key)) fail(`INSERT requires ${meta.type}.${key}`);
97
+ for (const [key] of required) if (!columns.some((column) => column[0] === key)) fail(`INSERT requires ${meta?.type ?? custom.tableName}.${key}`);
93
98
  for (const [key, expr] of columns) {
94
- const field = writableField(meta, key, "insert");
99
+ const field = meta ? writableField(meta, key, "insert") : customWritableField(custom, key, "insert");
95
100
  const left = field.outputType;
96
101
  const right = expr.outputType;
97
- if (!left || !right || left.dbType !== right.dbType || left.domain !== right.domain || left.idMeta !== right.idMeta) fail(`INSERT SELECT ${meta.type}.${key} has incompatible or unknown storage codecs`);
98
- if (!field.sqlNullable && expr.sqlNullable === true) fail(`INSERT SELECT ${meta.type}.${key} cannot accept a nullable output`);
102
+ if (!left || !right || left.dbType !== right.dbType || left.domain !== right.domain || left.idMeta !== right.idMeta) fail(`INSERT SELECT ${meta?.type ?? custom.tableName}.${key} has incompatible or unknown storage codecs`);
103
+ if (!field.sqlNullable && expr.sqlNullable === true) fail(`INSERT SELECT ${meta?.type ?? custom.tableName}.${key} cannot accept a nullable output`);
99
104
  }
100
- const keys = fields.filter(([key]) => columns.some((column) => column[0] === key));
105
+ const keys = fields.filter(([key]) => columns.some((column) => column[0] === key)).map(([key, field]) => [key, field.columnName]);
101
106
  const sourceAlias = safeKq(assigner.getLiteralAlias("sq"));
102
- sql += ` (${keys.map(([, field]) => kq(field.columnName)).join(", ")}) SELECT ${keys.map(([key]) => `${sourceAlias}.${safeKq(key)}`).join(", ")} FROM (${source.sql}) AS ${sourceAlias}`;
107
+ sql += ` (${keys.map(([, column]) => kq(column)).join(", ")}) SELECT ${keys.map(([key]) => `${sourceAlias}.${safeKq(key)}`).join(", ")} FROM (${source.sql}) AS ${sourceAlias}`;
103
108
  bindings.push(...source.bindings);
104
109
  refs.push(...source.outerRefs);
105
110
  }
106
111
  } else {
107
112
  if (statement.allowAll !== void 0 && typeof statement.allowAll !== "boolean") fail("allowAll must be a boolean");
108
113
  if (statement.softDeletes !== void 0 && statement.softDeletes !== "include" && statement.softDeletes !== "exclude") fail("softDeletes must be 'include' or 'exclude'");
109
- const user = mutationCondition(statement.where, ctx);
110
- if (!user && statement.allowAll !== true) fail("UPDATE and DELETE require a nonempty user where or allowAll: true");
114
+ const whereCondition = mutationCondition(statement.where, ctx);
115
+ if (Object.hasOwn(statement, "where") && !whereCondition && statement.allowAll !== true) fail("UPDATE and DELETE require allowAll: true when a supplied where is undefined or fully pruned");
111
116
  if (operation === "update") {
112
- const entries = assignments(meta, statement.set, "update");
117
+ const entries = meta ? assignments(meta, statement.set, "update") : customAssignments(custom, statement.set, "update");
113
118
  sql += " SET " + entries.map((entry) => {
114
119
  const [key, value] = entry;
115
- const field = writableField(meta, key, "update");
116
- const cell = assignmentToSql(meta, field, value, ctx);
120
+ const field = meta ? writableField(meta, key, "update") : customWritableField(custom, key, "update");
121
+ const cell = meta ? assignmentToSql(meta, field, value, ctx) : customAssignmentToSql(custom, field, value, ctx);
117
122
  bindings.push(...cell.bindings);
118
123
  refs.push(...cell.refs);
119
124
  return `${kq(field.columnName)} = ${cell.sql}`;
120
125
  }).join(", ");
121
126
  }
122
- const conditions = [user, conditionToSql({ and: injectedConditions({
127
+ const conditions = [whereCondition, meta ? conditionToSql({ and: injectedConditions({
123
128
  meta,
124
129
  alias
125
- }, statement.softDeletes ?? "exclude") }, ctx, true)].filter((condition) => condition !== void 0);
130
+ }, statement.softDeletes ?? "exclude") }, ctx, true) : void 0].filter((condition) => condition !== void 0);
126
131
  if (conditions.length) {
127
132
  sql += ` WHERE ${conditions.map((condition) => `(${condition.sql})`).join(" AND ")}`;
128
133
  for (const condition of conditions) {
@@ -174,6 +179,23 @@ function assignments(meta, value, operation) {
174
179
  if (!defined.length) fail(`${operation} requires at least one defined field; empty rows/sets are not DEFAULT VALUES`);
175
180
  return defined;
176
181
  }
182
+ /** Validates assignment keys against a custom table's declared writable columns. */
183
+ function customAssignments(table, value, operation) {
184
+ if (!value || typeof value !== "object" || Array.isArray(value) || isExpr(value) || isEntity(value)) fail(`${operation} assignments must be a field POJO`);
185
+ const entries = Object.entries(value);
186
+ for (const [key] of entries) customWritableField(table, key, operation);
187
+ checkPojo(value, Object.keys(table.columns), `${operation} assignments`);
188
+ const defined = entries.filter((entry) => entry[1] !== void 0);
189
+ if (!defined.length) fail(`${operation} requires at least one defined field; empty rows/sets are not DEFAULT VALUES`);
190
+ return defined;
191
+ }
192
+ /** Applies physical write restrictions declared by `declareTable`. */
193
+ function customWritableField(table, key, operation) {
194
+ const column = Object.hasOwn(table.columns, key) ? table.columns[key] : void 0;
195
+ if (!column) fail(`Unsupported SQL mutation field ${table.tableName}.${key}`);
196
+ if (operation === "update" ? !column.update : column.insert === "never") fail(`Unsupported SQL mutation field ${table.tableName}.${key}`);
197
+ return column;
198
+ }
177
199
  /** Applies physical write restrictions, not ORM-derived, protected, or business-immutable flags. */
178
200
  function writableField(meta, key, operation) {
179
201
  const column = Object.hasOwn(meta.columns, key) ? meta.columns[key] : void 0;
@@ -214,9 +236,27 @@ function assignmentToSql(meta, column, value, ctx) {
214
236
  refs: []
215
237
  };
216
238
  }
239
+ /** Encodes a custom-table literal through its declared primitive codec. */
240
+ function customAssignmentToSql(table, column, value, ctx) {
241
+ if (isExpr(value)) return asNode(value).toSql(ctx);
242
+ if (value === null) {
243
+ if (!column.sqlNullable) fail(`${table.tableName}.${column.columnName} is physically NOT NULL`);
244
+ return {
245
+ sql: "NULL",
246
+ bindings: [],
247
+ refs: []
248
+ };
249
+ }
250
+ return {
251
+ sql: "?",
252
+ bindings: [column.mapToDbValue(value)],
253
+ refs: []
254
+ };
255
+ }
217
256
  /** Checks the user predicate independently so metadata filters cannot turn a pruned guard into consent. */
218
257
  function mutationCondition(value, ctx) {
219
258
  if (isExpr(value)) return asNode(value).toSql(ctx);
259
+ if (Array.isArray(value)) return conditionToSql({ and: value }, ctx, true);
220
260
  return conditionToSql(value, ctx, true);
221
261
  }
222
262
  /** Only own enumerable POJO clauses count as input or explicit full-table consent. */
@@ -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 { 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 QueryJoins,\n type QueryRow,\n type ReadQueryRow,\n type SetOperand,\n type SetOperation,\n type SetQuery,\n type Subquery,\n type WithInput,\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 { type TableFor, getTableMgmt, isTable, tableMgmt } from \"src/queries/sql/Tables.ts\";\nimport type { Column } 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: MutationTarget<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: InsertValues<T> | 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: MutationTarget<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: MutationTarget<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: object | 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) & { 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 ? 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 } ? { readonly values: CheckValues<T, V> } : 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 : 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 checkPojo(statement, allowed, `SQL ${operation}`);\n const target = statement[operation];\n if (!isTable(target)) fail(\"A mutation target must be an entity table\");\n const mgmt = getTableMgmt(target);\n const meta = mgmt.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 const fields = Object.entries(meta.columns);\n for (const [, field] of fields) {\n requireColumnMetadata(meta, field);\n }\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(meta.tableName);\n ctx.register(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\" : \"\")} ${kq(meta.tableName)} 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 const rows = Array.isArray(statement.values) ? statement.values : [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(meta, 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 ${meta.type}.${key}`);\n }\n }\n if (rows.length === 0) return undefined;\n const keys = fields.filter(([key]) => entries.some((row) => row.some((entry) => entry[0] === key)));\n sql += ` (${keys.map(([, field]) => kq(field.columnName)).join(\", \")}) VALUES `;\n sql += entries\n .map((row) => {\n const cells = keys.map(([key, field]) => {\n const entry = row.find((entry) => entry[0] === key);\n if (!entry) return \"DEFAULT\";\n const cell = assignmentToSql(meta, field, 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)) fail(`INSERT requires ${meta.type}.${key}`);\n }\n for (const [key, expr] of columns) {\n const field = writableField(meta, 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 ${meta.type}.${key} has incompatible or unknown storage codecs`);\n }\n if (!field.sqlNullable && expr.sqlNullable === true)\n fail(`INSERT SELECT ${meta.type}.${key} cannot accept a nullable output`);\n }\n const keys = fields.filter(([key]) => columns.some((column) => column[0] === key));\n const sourceAlias = safeKq(assigner.getLiteralAlias(\"sq\"));\n sql += ` (${keys.map(([, field]) => kq(field.columnName)).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 user = mutationCondition(statement.where, ctx);\n if (!user && statement.allowAll !== true) fail(\"UPDATE and DELETE require a nonempty user where or allowAll: true\");\n if (operation === \"update\") {\n const entries = assignments(meta, statement.set, \"update\");\n sql +=\n \" SET \" +\n entries\n .map((entry) => {\n const [key, value] = entry;\n const field = writableField(meta, key, \"update\");\n const cell = assignmentToSql(meta, 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 = conditionToSql(\n { and: injectedConditions({ meta, alias }, statement.softDeletes ?? \"exclude\") },\n ctx,\n true,\n );\n const conditions = [user, 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\ntype MutationTarget<T extends Entity> = TableFor<T> &\n (TypeMapEntry<T, \"supportsEmExecute\"> extends true ? unknown : never);\ntype MutationFilter = {\n readonly where?: SqlCondition | ExprLike<boolean>;\n readonly allowAll?: boolean;\n readonly softDeletes?: \"include\" | \"exclude\";\n};\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/** 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/** 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/** 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/** 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;\ntype SqlValue<T, K extends keyof ColumnsOf<T>> =\n | DomainValue<T, K>\n | (ColumnsOf<T>[K] extends { nullable: true } ? null : never);\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);\ntype InsertSourceRow<T> = { [K in RequiredInsertKey<T>]: SqlValue<T, K> } & {\n [K in Exclude<InsertKey<T>, RequiredInsertKey<T>>]?: SqlValue<T, K>;\n};\ntype InsertProjection<T> = { [K in RequiredInsertKey<T>]: ExprLike<SqlValue<T, K>> } & {\n [K in Exclude<InsertKey<T>, RequiredInsertKey<T>>]?: ExprLike<SqlValue<T, K>>;\n};\ntype UnionKeys<V> = V extends unknown ? keyof V : never;\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;\ntype ExprSource<V> = V extends { readonly [exprBrand]: ExprBrand<unknown, infer Src> } ? Src : never;\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\";\ntype ReturningExpr<R> = R extends ExprLike<unknown> ? R : R extends undefined ? never : R[keyof R];\ntype EmptyReturning<R> = R extends object ? (keyof R extends never ? true : false) : false;\ntype CheckReturning<R, Scope> = true extends EmptyReturning<R> ? never : CheckExprScope<ReturningExpr<R>, Scope>;\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\";\ntype CheckValues<T extends Entity, V> =\n | ([Extract<V, readonly unknown[]>] extends [never]\n ? never\n : readonly CheckAssignments<Extract<V, readonly unknown[]>[number], InsertValues<T>, never>[])\n | ([Exclude<V, readonly unknown[]>] extends [never]\n ? never\n : CheckAssignments<Exclude<V, readonly unknown[]>, InsertValues<T>, never>);\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\"], QueryJoins> : []>\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 };\ntype CheckInsertSource<T, Q extends SetOperand> = SetOperand extends Q\n ? \"INSERT source was typed too generically; retain its named output fields\"\n : ReadQueryRow<Q> extends InsertSourceRow<T>\n ? Exclude<UnionKeys<ReadQueryRow<Q>>, InsertKey<T>> 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\";\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;\ntype TargetTable<M> = M extends\n | { readonly insert: infer A }\n | { readonly update: infer A }\n | { readonly delete: infer A }\n ? A\n : never;\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/** SQL mutations require complete physical metadata. */\nfunction requireColumnMetadata(meta: EntityMetadata, 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 ${meta.type}.${column.columnName}; run codegen`);\n}\n\n/** Validates every supplied key, including undefined fields, before pruning omitted values. */\nfunction assignments(meta: EntityMetadata, 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(meta, key, operation);\n checkPojo(value, Object.keys(meta.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/** Applies physical write restrictions, not ORM-derived, protected, or business-immutable flags. */\nfunction writableField(meta: EntityMetadata, key: string, operation: \"insert\" | \"update\"): Column {\n const column = Object.hasOwn(meta.columns, key) ? meta.columns[key] : undefined;\n if (!column) fail(`Unsupported SQL mutation field ${meta.type}.${key}`);\n requireColumnMetadata(meta, column);\n if (operation === \"update\" && key === \"id\") fail(\"UPDATE primary-key assignments are not supported\");\n if (column.isGenerated) fail(`Generated field ${meta.type}.${key} is omit-only`);\n if (operation === \"update\" ? !column.update : column.insert === \"never\")\n fail(`Unsupported SQL mutation field ${meta.type}.${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 */\nfunction assignmentToSql(meta: EntityMetadata, 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(`${meta.type}.${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 ${meta.type}.${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 return conditionToSql(value as SqlCondition | undefined, ctx, true);\n}\n\n/** Only own enumerable POJO clauses count as input or explicit full-table consent. */\nfunction checkPojo(value: object, allowed: readonly PropertyKey[], description: string): void {\n if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)\n fail(`${description} must be a plain POJO`);\n for (const key of Reflect.ownKeys(value)) {\n if (!allowed.includes(key)) fail(`${description} does not support '${String(key)}'`);\n if (typeof key === \"string\" && !Object.prototype.propertyIsEnumerable.call(value, key))\n fail(`${description} requires enumerable fields`);\n }\n}\n"],"mappings":";;;;;;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AW,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,KAAK,KAAK,GAAG,OAAO,WAAW,mCAAmC;CAC1F,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,OAAO,eAAe,OAAmC,KAAK,IAAI;AACpE;;AAGA,SAAS,UAAU,OAAe,SAAiC,aAA2B;CAC5F,IAAI,OAAO,eAAe,KAAK,MAAM,OAAO,aAAa,OAAO,eAAe,KAAK,MAAM,MACxF,KAAK,GAAG,YAAY,sBAAsB;CAC5C,KAAK,MAAM,OAAO,QAAQ,QAAQ,KAAK,GAAG;EACxC,IAAI,CAAC,QAAQ,SAAS,GAAG,GAAG,KAAK,GAAG,YAAY,qBAAqB,OAAO,GAAG,EAAE,EAAE;EACnF,IAAI,OAAO,QAAQ,YAAY,CAAC,OAAO,UAAU,qBAAqB,KAAK,OAAO,GAAG,GACnF,KAAK,GAAG,YAAY,4BAA4B;CACpD;AACF"}
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 type CustomTableMgmt,\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 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 getTableMgmt,\n isCustomTable,\n isEntityTable,\n isTable,\n tableMgmt,\n tableSqlName,\n} from \"src/queries/sql/Tables.ts\";\nimport type { Column } 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: MutationTarget<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: MutationTarget<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: MutationTarget<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<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 checkPojo(statement, allowed, `SQL ${operation}`);\n const target = statement[operation];\n if (!isTable(target)) fail(\"A mutation target must be a table\");\n const mgmt = getTableMgmt(target);\n const meta = isEntityTable(target) ? getTableMgmt(target).meta : undefined;\n const custom = isCustomTable(target) ? getTableMgmt(target) : undefined;\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 for (const field of Object.values(meta.columns)) requireColumnMetadata(meta, field);\n } else if (statement.softDeletes !== undefined) {\n fail(\"Custom table mutations do not support softDeletes\");\n }\n const fields = Object.entries(meta?.columns ?? custom!.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(mgmt.tableName);\n ctx.register(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(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) =>\n meta ? assignments(meta, row, \"insert\") : customAssignments(custom!, row, \"insert\"),\n );\n for (const row of entries) {\n for (const [key] of required) {\n if (!row.some((entry) => entry[0] === key)) fail(`INSERT requires ${meta?.type ?? custom!.tableName}.${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 = meta\n ? assignmentToSql(meta, writableField(meta, key, \"insert\"), entry[1], valuesCtx)\n : customAssignmentToSql(custom!, customWritableField(custom!, 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 ${meta?.type ?? custom!.tableName}.${key}`);\n }\n }\n for (const [key, expr] of columns) {\n const field = meta ? writableField(meta, key, \"insert\") : customWritableField(custom!, 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 ${meta?.type ?? custom!.tableName}.${key} has incompatible or unknown storage codecs`);\n }\n if (!field.sqlNullable && expr.sqlNullable === true)\n fail(`INSERT SELECT ${meta?.type ?? custom!.tableName}.${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 = meta\n ? assignments(meta, statement.set, \"update\")\n : customAssignments(custom!, statement.set, \"update\");\n sql +=\n \" SET \" +\n entries\n .map((entry) => {\n const [key, value] = entry;\n const field = meta ? writableField(meta, key, \"update\") : customWritableField(custom!, key, \"update\");\n const cell = meta\n ? assignmentToSql(meta, field, value, ctx)\n : customAssignmentToSql(custom!, 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 MutationTarget<T extends Entity> = TableFor<T> &\n (TypeMapEntry<T, \"supportsEmExecute\"> extends true ? unknown : never);\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/** Checks every entity INSERT row in a readonly collection against writable columns. */\ntype CheckValues<T extends Entity, V extends readonly unknown[]> = readonly CheckAssignments<\n V[number],\n InsertValues<T>,\n never\n>[];\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: CheckCustomValues<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/** Checks every custom INSERT row in a readonly collection against declared writable columns. */\ntype CheckCustomValues<C extends CustomColumnInputs, V extends readonly unknown[]> = readonly CheckAssignments<\n V[number],\n CustomInsertValues<C>,\n never\n>[];\n\n/** Checks a custom INSERT SELECT's named outputs, required columns, values, and read source. */\ntype CheckCustomInsertSource<C extends CustomColumnInputs, 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 CustomInsertSourceRow<C>\n ? Exclude<UnionKeys<ReadQueryRow<Q>>, CustomInsertKey<C>> 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 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's named outputs, required columns, values, and read source. */\ntype CheckInsertSource<T, Q extends SetOperand> = 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 InsertSourceRow<T>\n ? Exclude<UnionKeys<ReadQueryRow<Q>>, InsertKey<T>> 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/** 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/** SQL mutations require complete physical metadata. */\nfunction requireColumnMetadata(meta: EntityMetadata, 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 ${meta.type}.${column.columnName}; run codegen`);\n}\n\n/** Validates every supplied key, including undefined fields, before pruning omitted values. */\nfunction assignments(meta: EntityMetadata, 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(meta, key, operation);\n checkPojo(value, Object.keys(meta.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/** Validates assignment keys against a custom table's declared writable columns. */\nfunction customAssignments(\n table: CustomTableMgmt,\n value: unknown,\n operation: \"insert\" | \"update\",\n): [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 }\n const entries = Object.entries(value);\n for (const [key] of entries) customWritableField(table, key, operation);\n checkPojo(value, Object.keys(table.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/** Applies physical write restrictions declared by `declareTable`. */\nfunction customWritableField(table: CustomTableMgmt, key: string, operation: \"insert\" | \"update\"): Column {\n const column = Object.hasOwn(table.columns, key) ? table.columns[key] : undefined;\n if (!column) fail(`Unsupported SQL mutation field ${table.tableName}.${key}`);\n if (operation === \"update\" ? !column.update : column.insert === \"never\") {\n fail(`Unsupported SQL mutation field ${table.tableName}.${key}`);\n }\n return column;\n}\n\n/** Applies physical write restrictions, not ORM-derived, protected, or business-immutable flags. */\nfunction writableField(meta: EntityMetadata, key: string, operation: \"insert\" | \"update\"): Column {\n const column = Object.hasOwn(meta.columns, key) ? meta.columns[key] : undefined;\n if (!column) fail(`Unsupported SQL mutation field ${meta.type}.${key}`);\n requireColumnMetadata(meta, column);\n if (operation === \"update\" && key === \"id\") fail(\"UPDATE primary-key assignments are not supported\");\n if (column.isGenerated) fail(`Generated field ${meta.type}.${key} is omit-only`);\n if (operation === \"update\" ? !column.update : column.insert === \"never\")\n fail(`Unsupported SQL mutation field ${meta.type}.${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 */\nfunction assignmentToSql(meta: EntityMetadata, 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(`${meta.type}.${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 ${meta.type}.${column.columnName} does not support SQL value writes`);\n return { sql: \"?\", bindings: [column.mapToDbValue(value)], refs: [] };\n}\n\n/** Encodes a custom-table literal through its declared primitive codec. */\nfunction customAssignmentToSql(table: CustomTableMgmt, 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(`${table.tableName}.${column.columnName} is physically NOT NULL`);\n return { sql: \"NULL\", bindings: [], refs: [] };\n }\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\n/** Only own enumerable POJO clauses count as input or explicit full-table consent. */\nfunction checkPojo(value: object, allowed: readonly PropertyKey[], description: string): void {\n if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)\n fail(`${description} must be a plain POJO`);\n for (const key of Reflect.ownKeys(value)) {\n if (!allowed.includes(key)) fail(`${description} does not support '${String(key)}'`);\n if (typeof key === \"string\" && !Object.prototype.propertyIsEnumerable.call(value, key))\n fail(`${description} requires enumerable fields`);\n }\n}\n"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AI;CACzE,OAAO,eAAe,OAAmC,KAAK,IAAI;AACpE;;AAGA,SAAS,UAAU,OAAe,SAAiC,aAA2B;CAC5F,IAAI,OAAO,eAAe,KAAK,MAAM,OAAO,aAAa,OAAO,eAAe,KAAK,MAAM,MACxF,KAAK,GAAG,YAAY,sBAAsB;CAC5C,KAAK,MAAM,OAAO,QAAQ,QAAQ,KAAK,GAAG;EACxC,IAAI,CAAC,QAAQ,SAAS,GAAG,GAAG,KAAK,GAAG,YAAY,qBAAqB,OAAO,GAAG,EAAE,EAAE;EACnF,IAAI,OAAO,QAAQ,YAAY,CAAC,OAAO,UAAU,qBAAqB,KAAK,OAAO,GAAG,GACnF,KAAK,GAAG,YAAY,4BAA4B;CACpD;AACF"}
@@ -4,7 +4,7 @@ import { CoalesceInput, ParsedCoalesceExpression } from "./coalesce.cjs";
4
4
  import { GreatestInput, ParsedGreatestExpression } from "./greatest.cjs";
5
5
  import { LeastInput, ParsedLeastExpression } from "./least.cjs";
6
6
  import { NullIfInput, ParsedNullIfExpression } from "./nullIf.cjs";
7
- import { CompatibleValue, MaybeNull, QueryJoins } from "../query.cjs";
7
+ import { CompatibleValue, MaybeNull, QueryJoinList } from "../query.cjs";
8
8
  import { BaseExpr, Expr, ExprBrand, ExprLike, exprBrand } from "../Expr.cjs";
9
9
  //#region src/queries/sql/expressions/types.d.ts
10
10
  /** Each operation owns its input fields; the combined input permits exactly one operation. */
@@ -27,10 +27,10 @@ type ExprFromInput<I> = Expr<InputResult<I, []>, ExpressionSources<I>> & {
27
27
  readonly [inputBrand]: I;
28
28
  };
29
29
  /**
30
- * Computes the TypeScript result type, including null from LEFT joins.
30
+ * Computes the SQL expression type, including null from LEFT joins.
31
31
  * I.e. Book.title is string | null when Book is LEFT-joined; COALESCE(Book.title, "Unknown") is string.
32
32
  */
33
- type ExpressionValue<V, J extends QueryJoins> = unknown extends V ? V : V extends {
33
+ type ExpressionValue<V, J extends QueryJoinList> = unknown extends V ? V : V extends {
34
34
  readonly [inputBrand]: infer I;
35
35
  } ? InputResult<I, J> : V extends {
36
36
  readonly [exprBrand]: ExprBrand<infer R, infer S>;
@@ -51,7 +51,7 @@ type WidenLiteral<V> = V extends string ? string : V extends number ? number : V
51
51
  * Uses existing expressions' result types for their literal fallbacks, just as their codecs do at runtime.
52
52
  * I.e. COALESCE(Book.id, "b:9") returns BookId rather than string. ExpressionValue supplies the nullability.
53
53
  */
54
- type InputResult<I, J extends QueryJoins> = [Exclude<BranchResult<I>, null>] extends [never] ? ExpressionValue<I, J> : Exclude<BranchResult<I>, null> | (null extends ExpressionValue<I, J> ? null : never);
54
+ type InputResult<I, J extends QueryJoinList> = [Exclude<BranchResult<I>, null>] extends [never] ? ExpressionValue<I, J> : Exclude<BranchResult<I>, null> | (null extends ExpressionValue<I, J> ? null : never);
55
55
  /** Collects the types supplied by columns and existing expressions, excluding plain literal fallbacks. */
56
56
  type BranchResult<V> = unknown extends V ? never : V extends ExprLike<infer R> ? R : V extends {
57
57
  readonly arrayAgg: infer A;
@@ -61,7 +61,7 @@ type BranchResult<V> = unknown extends V ? never : V extends ExprLike<infer R> ?
61
61
  readonly case: infer A;
62
62
  } ? BranchResult<CaseArmValue<A>> : never;
63
63
  /** A fixed non-null candidate guarantees a result; a possibly empty candidate array does not. */
64
- type CoalesceValue<A extends readonly unknown[], J extends QueryJoins> = A extends readonly [infer H, ...infer T] ? Exclude<ExpressionValue<H, J>, null> | (null extends ExpressionValue<H, J> ? CoalesceValue<T, J> : never) : A extends readonly [...infer Before, infer Last] ? Exclude<ExpressionValue<A[number], J>, null> | (null extends ExpressionValue<Last, J> ? (null extends CoalesceValue<Before, J> ? null : never) : never) : ExpressionValue<A[number], J> | null;
64
+ type CoalesceValue<A extends readonly unknown[], J extends QueryJoinList> = A extends readonly [infer H, ...infer T] ? Exclude<ExpressionValue<H, J>, null> | (null extends ExpressionValue<H, J> ? CoalesceValue<T, J> : never) : A extends readonly [...infer Before, infer Last] ? Exclude<ExpressionValue<A[number], J>, null> | (null extends ExpressionValue<Last, J> ? (null extends CoalesceValue<Before, J> ? null : never) : never) : ExpressionValue<A[number], J> | null;
65
65
  /** Conditions affect which value is chosen, but do not make that value nullable through a LEFT join. */
66
66
  type ExpressionSources<V> = unknown extends V ? string : V extends ExprLike<unknown> ? V[typeof exprBrand]["__source"] : V extends {
67
67
  readonly arrayAgg: infer A;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.cts","names":[],"sources":["../../../../src/queries/sql/expressions/types.ts"],"mappings":";;;;;;;;;;UAcU;EACR,MAAM;EACN,UAAU;EACV,UAAU;EACV,QAAQ;EACR,UAAU;EACV,OAAO;;KAIG,WAAW,cAAc;KAChC,mBAAmB,KAAK,uBAAuB,KAAK,6BAA2B;KAC/E,SAAS,KAAK,QAAQ,QAAQ,IAAI;;KAG3B,eACT,WAAW,aAAa,WAAW,iBAAiB,KAAK,cAAc,qBAAqB,wBACvF;cAEM;;KAGF,cAAc,KAAK,KAAK,YAAY,QAAQ,kBAAkB;YAC9D,aAAa;;;;;;KAOb,gBAAgB,GAAG,UAAU,8BAA8B,IACnE,IACA;YAAsB,mBAAmB;IACvC,YAAY,GAAG,KACf;YAAsB,YAAY,gBAAgB,SAAS;IACzD,UAAU,GAAG,GAAG,KAChB;WAAqB,gBAAgB;IACnC,gBAAgB,cAAc,IAAI,cAClC,UAAU,gBACR;WAAqB;IACnB,gBAAgB,SAAS,OAAO,YAChC;WAAqB;IACnB,cAAc,SAAS,IAAI,KAEvB,QAAQ,gBAAgB,SAAS,YAAY,0BAC/B,cAAc,SAAS,IAAI,qBACjD;WAAqB,YAAY;IAE3B,gBAAgB,aAAa,IAAI,MAChC;WAA6C;qBAClD,aAAa;;KAGtB,aAAa,KAAK,4BAEnB,4BAEE,8BAEE,4BAEE,0BAA0B,OACxB,aAAa,OACb;;;;;KAMP,YAAY,GAAG,UAAU,eAAe,QAAQ,aAAa,6BAC9D,gBAAgB,GAAG,KACnB,QAAQ,aAAa,0BAA0B,gBAAgB,GAAG;;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G9E,WAAW,MAAM,YAAY,gBAAgB,GAAG,QAAQ,aAAa,wBAE7E,gBAAgB,GAAG,QAAQ,aAAa;;;;;;KAOhC,mBACR,WACA,0BACA,2BACA,2BACA,yBACA,2BACA,wBACA;;UAGa;EACf;EACA;;;KAIU,cAAc,KAAK;;KAG1B,cAAc,KAAK;WAAqB,aAAa;IAAM,IAAI;;KAG/D,cAAc,GAAG,KAAK;WAAqB;IAC5C,UAAU,wCAEI,WAAW,IAAI,oBACrB,gBAAgB,EAAE,IAAI,KACtB,gBAAgB,4BACd,EAAE,wBAIZ,gBAAgB,GAAG"}
@@ -4,7 +4,7 @@ import { CoalesceInput, ParsedCoalesceExpression } from "./coalesce.mjs";
4
4
  import { GreatestInput, ParsedGreatestExpression } from "./greatest.mjs";
5
5
  import { LeastInput, ParsedLeastExpression } from "./least.mjs";
6
6
  import { NullIfInput, ParsedNullIfExpression } from "./nullIf.mjs";
7
- import { CompatibleValue, MaybeNull, QueryJoins } from "../query.mjs";
7
+ import { CompatibleValue, MaybeNull, QueryJoinList } from "../query.mjs";
8
8
  import { BaseExpr, Expr, ExprBrand, ExprLike, exprBrand } from "../Expr.mjs";
9
9
  //#region src/queries/sql/expressions/types.d.ts
10
10
  /** Each operation owns its input fields; the combined input permits exactly one operation. */
@@ -27,10 +27,10 @@ type ExprFromInput<I> = Expr<InputResult<I, []>, ExpressionSources<I>> & {
27
27
  readonly [inputBrand]: I;
28
28
  };
29
29
  /**
30
- * Computes the TypeScript result type, including null from LEFT joins.
30
+ * Computes the SQL expression type, including null from LEFT joins.
31
31
  * I.e. Book.title is string | null when Book is LEFT-joined; COALESCE(Book.title, "Unknown") is string.
32
32
  */
33
- type ExpressionValue<V, J extends QueryJoins> = unknown extends V ? V : V extends {
33
+ type ExpressionValue<V, J extends QueryJoinList> = unknown extends V ? V : V extends {
34
34
  readonly [inputBrand]: infer I;
35
35
  } ? InputResult<I, J> : V extends {
36
36
  readonly [exprBrand]: ExprBrand<infer R, infer S>;
@@ -51,7 +51,7 @@ type WidenLiteral<V> = V extends string ? string : V extends number ? number : V
51
51
  * Uses existing expressions' result types for their literal fallbacks, just as their codecs do at runtime.
52
52
  * I.e. COALESCE(Book.id, "b:9") returns BookId rather than string. ExpressionValue supplies the nullability.
53
53
  */
54
- type InputResult<I, J extends QueryJoins> = [Exclude<BranchResult<I>, null>] extends [never] ? ExpressionValue<I, J> : Exclude<BranchResult<I>, null> | (null extends ExpressionValue<I, J> ? null : never);
54
+ type InputResult<I, J extends QueryJoinList> = [Exclude<BranchResult<I>, null>] extends [never] ? ExpressionValue<I, J> : Exclude<BranchResult<I>, null> | (null extends ExpressionValue<I, J> ? null : never);
55
55
  /** Collects the types supplied by columns and existing expressions, excluding plain literal fallbacks. */
56
56
  type BranchResult<V> = unknown extends V ? never : V extends ExprLike<infer R> ? R : V extends {
57
57
  readonly arrayAgg: infer A;
@@ -61,7 +61,7 @@ type BranchResult<V> = unknown extends V ? never : V extends ExprLike<infer R> ?
61
61
  readonly case: infer A;
62
62
  } ? BranchResult<CaseArmValue<A>> : never;
63
63
  /** A fixed non-null candidate guarantees a result; a possibly empty candidate array does not. */
64
- type CoalesceValue<A extends readonly unknown[], J extends QueryJoins> = A extends readonly [infer H, ...infer T] ? Exclude<ExpressionValue<H, J>, null> | (null extends ExpressionValue<H, J> ? CoalesceValue<T, J> : never) : A extends readonly [...infer Before, infer Last] ? Exclude<ExpressionValue<A[number], J>, null> | (null extends ExpressionValue<Last, J> ? (null extends CoalesceValue<Before, J> ? null : never) : never) : ExpressionValue<A[number], J> | null;
64
+ type CoalesceValue<A extends readonly unknown[], J extends QueryJoinList> = A extends readonly [infer H, ...infer T] ? Exclude<ExpressionValue<H, J>, null> | (null extends ExpressionValue<H, J> ? CoalesceValue<T, J> : never) : A extends readonly [...infer Before, infer Last] ? Exclude<ExpressionValue<A[number], J>, null> | (null extends ExpressionValue<Last, J> ? (null extends CoalesceValue<Before, J> ? null : never) : never) : ExpressionValue<A[number], J> | null;
65
65
  /** Conditions affect which value is chosen, but do not make that value nullable through a LEFT join. */
66
66
  type ExpressionSources<V> = unknown extends V ? string : V extends ExprLike<unknown> ? V[typeof exprBrand]["__source"] : V extends {
67
67
  readonly arrayAgg: infer A;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../../../../src/queries/sql/expressions/types.ts"],"mappings":";;;;;;;;;;UAcU;EACR,MAAM;EACN,UAAU;EACV,UAAU;EACV,QAAQ;EACR,UAAU;EACV,OAAO;;KAIG,WAAW,cAAc;KAChC,mBAAmB,KAAK,uBAAuB,KAAK,6BAA2B;KAC/E,SAAS,KAAK,QAAQ,QAAQ,IAAI;;KAG3B,eACT,WAAW,aAAa,WAAW,iBAAiB,KAAK,cAAc,qBAAqB,wBACvF;cAEM;;KAGF,cAAc,KAAK,KAAK,YAAY,QAAQ,kBAAkB;YAC9D,aAAa;;;;;;KAOb,gBAAgB,GAAG,UAAU,8BAA8B,IACnE,IACA;YAAsB,mBAAmB;IACvC,YAAY,GAAG,KACf;YAAsB,YAAY,gBAAgB,SAAS;IACzD,UAAU,GAAG,GAAG,KAChB;WAAqB,gBAAgB;IACnC,gBAAgB,cAAc,IAAI,cAClC,UAAU,gBACR;WAAqB;IACnB,gBAAgB,SAAS,OAAO,YAChC;WAAqB;IACnB,cAAc,SAAS,IAAI,KAEvB,QAAQ,gBAAgB,SAAS,YAAY,0BAC/B,cAAc,SAAS,IAAI,qBACjD;WAAqB,YAAY;IAE3B,gBAAgB,aAAa,IAAI,MAChC;WAA6C;qBAClD,aAAa;;KAGtB,aAAa,KAAK,4BAEnB,4BAEE,8BAEE,4BAEE,0BAA0B,OACxB,aAAa,OACb;;;;;KAMP,YAAY,GAAG,UAAU,eAAe,QAAQ,aAAa,6BAC9D,gBAAgB,GAAG,KACnB,QAAQ,aAAa,0BAA0B,gBAAgB,GAAG;;KAGjE,aAAa,qBAAqB,YAEnC,UAAU,eAAe,KACvB,IACA;WAAqB,gBAAgB;IACnC,aAAa,cAAc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a;;;;;;KAOhC,mBACR,WACA,0BACA,2BACA,2BACA,yBACA,2BACA,wBACA;;UAGa;EACf;EACA;;;KAIU,cAAc,KAAK;;KAG1B,cAAc,KAAK;WAAqB,aAAa;IAAM,IAAI;;KAG/D,cAAc,GAAG,KAAK;WAAqB;IAC5C,UAAU,wCAEI,WAAW,IAAI,oBACrB,gBAAgB,EAAE,IAAI,KACtB,gBAAgB,4BACd,EAAE,wBAIZ,gBAAgB,GAAG"}
@@ -109,7 +109,7 @@ function kq(ident) {
109
109
  }
110
110
  /**
111
111
  * Quotes a possibly-untrusted identifier, i.e. an em.query select key, subquery `as` name, or
112
- * `sql.ref` column.
112
+ * `a.column` column.
113
113
  *
114
114
  * `kq`'s inputs are trusted metadata (codegen'd table/column names), and its quoting assumes that;
115
115
  * these idents are user strings, so embedded quotes are escaped like PG's own quote_ident, which
@@ -1 +1 @@
1
- {"version":3,"file":"keywords.cjs","names":[],"sources":["../../../src/queries/sql/keywords.ts"],"sourcesContent":["// select word from pg_get_keywords() where catdesc = 'reserved' order by word;\nconst keywords = [\n \"all\",\n \"alter\",\n \"analyse\",\n \"analyze\",\n \"and\",\n \"any\",\n \"array\",\n \"as\",\n \"asc\",\n \"avg\",\n \"between\",\n \"by\",\n \"asymmetric\",\n \"both\",\n \"case\",\n \"count\",\n \"cast\",\n \"check\",\n \"collate\",\n \"column\",\n \"constraint\",\n \"create\",\n \"delete\",\n \"current_catalog\",\n \"current_date\",\n \"current_role\",\n \"current_time\",\n \"current_timestamp\",\n \"current_user\",\n \"default\",\n \"deferrable\",\n \"desc\",\n \"distinct\",\n \"drop\",\n \"do\",\n \"else\",\n \"end\",\n \"from\",\n \"except\",\n \"false\",\n \"fetch\",\n \"for\",\n \"foreign\",\n \"from\",\n \"grant\",\n \"group\",\n \"having\",\n \"in\",\n \"inner\",\n \"insert\",\n \"initially\",\n \"intersect\",\n \"into\",\n \"is\",\n \"join\",\n \"left\",\n \"like\",\n \"max\",\n \"min\",\n \"lateral\",\n \"leading\",\n \"limit\",\n \"localtime\",\n \"localtimestamp\",\n \"not\",\n \"null\",\n \"offset\",\n \"on\",\n \"only\",\n \"or\",\n \"order\",\n \"outer\",\n \"right\",\n \"placing\",\n \"primary\",\n \"references\",\n \"returning\",\n \"select\",\n \"set\",\n \"sum\",\n \"session_user\",\n \"some\",\n \"symmetric\",\n \"table\",\n \"then\",\n \"to\",\n \"trailing\",\n \"true\",\n \"union\",\n \"update\",\n \"values\",\n \"unique\",\n \"user\",\n \"using\",\n \"variadic\",\n \"when\",\n \"where\",\n \"window\",\n \"with\",\n];\n\n// Cache all keywords => their escaped equivalent\nconst escapeMapped = new Map(keywords.map((k) => [k, `\"${k}\"`]));\nconst allLower = /^[a-z0-9_]+$/;\n\n/** Conditionally quotes `identifier` if it's a SQL keyword or not snake cased; for trusted idents only. */\nexport function kq(ident: string): string {\n // All camel-cased identifiers/column names need to be quoted\n if (!allLower.test(ident)) return `\"${ident}\"`;\n return escapeMapped.get(ident) ?? ident;\n}\n\n/**\n * Quotes a possibly-untrusted identifier, i.e. an em.query select key, subquery `as` name, or\n * `sql.ref` column.\n *\n * `kq`'s inputs are trusted metadata (codegen'd table/column names), and its quoting assumes that;\n * these idents are user strings, so embedded quotes are escaped like PG's own quote_ident, which\n * keeps display-name keys (`select: { \"Book Count\": ... }`) working. Names longer than PG's 63-byte\n * identifier limit are still rejected: PG would silently truncate them and break row decoding.\n */\nexport function safeKq(ident: string): string {\n if (ident.length > 63) throw new Error(`Identifier '${ident}' is longer than PG's 63-byte limit`);\n if (!ident.includes('\"')) return kq(ident);\n return `\"${ident.replaceAll('\"', '\"\"')}\"`;\n}\n\nexport function kqDot(alias: string, column: string): string {\n return `${kq(alias)}.${kq(column)}`;\n}\n\nexport function kqStar(alias: string): string {\n return `${kq(alias)}.*`;\n}\n"],"mappings":";;AAwGA,MAAM,eAAe,IAAI,IAAI;CAtG3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AAIkC,CAAC,CAAC,KAAK,MAAM,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,CAAC;AAC/D,MAAM,WAAW;;AAGjB,SAAgB,GAAG,OAAuB;CAExC,IAAI,CAAC,SAAS,KAAK,KAAK,GAAG,OAAO,IAAI,MAAM;CAC5C,OAAO,aAAa,IAAI,KAAK,KAAK;AACpC;;;;;;;;;;AAWA,SAAgB,OAAO,OAAuB;CAC5C,IAAI,MAAM,SAAS,IAAI,MAAM,IAAI,MAAM,eAAe,MAAM,oCAAoC;CAChG,IAAI,CAAC,MAAM,SAAS,IAAG,GAAG,OAAO,GAAG,KAAK;CACzC,OAAO,IAAI,MAAM,WAAW,MAAK,MAAI,EAAE;AACzC;AAEA,SAAgB,MAAM,OAAe,QAAwB;CAC3D,OAAO,GAAG,GAAG,KAAK,EAAE,GAAG,GAAG,MAAM;AAClC;AAEA,SAAgB,OAAO,OAAuB;CAC5C,OAAO,GAAG,GAAG,KAAK,EAAE;AACtB"}
1
+ {"version":3,"file":"keywords.cjs","names":[],"sources":["../../../src/queries/sql/keywords.ts"],"sourcesContent":["// select word from pg_get_keywords() where catdesc = 'reserved' order by word;\nconst keywords = [\n \"all\",\n \"alter\",\n \"analyse\",\n \"analyze\",\n \"and\",\n \"any\",\n \"array\",\n \"as\",\n \"asc\",\n \"avg\",\n \"between\",\n \"by\",\n \"asymmetric\",\n \"both\",\n \"case\",\n \"count\",\n \"cast\",\n \"check\",\n \"collate\",\n \"column\",\n \"constraint\",\n \"create\",\n \"delete\",\n \"current_catalog\",\n \"current_date\",\n \"current_role\",\n \"current_time\",\n \"current_timestamp\",\n \"current_user\",\n \"default\",\n \"deferrable\",\n \"desc\",\n \"distinct\",\n \"drop\",\n \"do\",\n \"else\",\n \"end\",\n \"from\",\n \"except\",\n \"false\",\n \"fetch\",\n \"for\",\n \"foreign\",\n \"from\",\n \"grant\",\n \"group\",\n \"having\",\n \"in\",\n \"inner\",\n \"insert\",\n \"initially\",\n \"intersect\",\n \"into\",\n \"is\",\n \"join\",\n \"left\",\n \"like\",\n \"max\",\n \"min\",\n \"lateral\",\n \"leading\",\n \"limit\",\n \"localtime\",\n \"localtimestamp\",\n \"not\",\n \"null\",\n \"offset\",\n \"on\",\n \"only\",\n \"or\",\n \"order\",\n \"outer\",\n \"right\",\n \"placing\",\n \"primary\",\n \"references\",\n \"returning\",\n \"select\",\n \"set\",\n \"sum\",\n \"session_user\",\n \"some\",\n \"symmetric\",\n \"table\",\n \"then\",\n \"to\",\n \"trailing\",\n \"true\",\n \"union\",\n \"update\",\n \"values\",\n \"unique\",\n \"user\",\n \"using\",\n \"variadic\",\n \"when\",\n \"where\",\n \"window\",\n \"with\",\n];\n\n// Cache all keywords => their escaped equivalent\nconst escapeMapped = new Map(keywords.map((k) => [k, `\"${k}\"`]));\nconst allLower = /^[a-z0-9_]+$/;\n\n/** Conditionally quotes `identifier` if it's a SQL keyword or not snake cased; for trusted idents only. */\nexport function kq(ident: string): string {\n // All camel-cased identifiers/column names need to be quoted\n if (!allLower.test(ident)) return `\"${ident}\"`;\n return escapeMapped.get(ident) ?? ident;\n}\n\n/**\n * Quotes a possibly-untrusted identifier, i.e. an em.query select key, subquery `as` name, or\n * `a.column` column.\n *\n * `kq`'s inputs are trusted metadata (codegen'd table/column names), and its quoting assumes that;\n * these idents are user strings, so embedded quotes are escaped like PG's own quote_ident, which\n * keeps display-name keys (`select: { \"Book Count\": ... }`) working. Names longer than PG's 63-byte\n * identifier limit are still rejected: PG would silently truncate them and break row decoding.\n */\nexport function safeKq(ident: string): string {\n if (ident.length > 63) throw new Error(`Identifier '${ident}' is longer than PG's 63-byte limit`);\n if (!ident.includes('\"')) return kq(ident);\n return `\"${ident.replaceAll('\"', '\"\"')}\"`;\n}\n\nexport function kqDot(alias: string, column: string): string {\n return `${kq(alias)}.${kq(column)}`;\n}\n\nexport function kqStar(alias: string): string {\n return `${kq(alias)}.*`;\n}\n"],"mappings":";;AAwGA,MAAM,eAAe,IAAI,IAAI;CAtG3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AAIkC,CAAC,CAAC,KAAK,MAAM,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,CAAC;AAC/D,MAAM,WAAW;;AAGjB,SAAgB,GAAG,OAAuB;CAExC,IAAI,CAAC,SAAS,KAAK,KAAK,GAAG,OAAO,IAAI,MAAM;CAC5C,OAAO,aAAa,IAAI,KAAK,KAAK;AACpC;;;;;;;;;;AAWA,SAAgB,OAAO,OAAuB;CAC5C,IAAI,MAAM,SAAS,IAAI,MAAM,IAAI,MAAM,eAAe,MAAM,oCAAoC;CAChG,IAAI,CAAC,MAAM,SAAS,IAAG,GAAG,OAAO,GAAG,KAAK;CACzC,OAAO,IAAI,MAAM,WAAW,MAAK,MAAI,EAAE;AACzC;AAEA,SAAgB,MAAM,OAAe,QAAwB;CAC3D,OAAO,GAAG,GAAG,KAAK,EAAE,GAAG,GAAG,MAAM;AAClC;AAEA,SAAgB,OAAO,OAAuB;CAC5C,OAAO,GAAG,GAAG,KAAK,EAAE;AACtB"}
@@ -3,7 +3,7 @@
3
3
  declare function kq(ident: string): string;
4
4
  /**
5
5
  * Quotes a possibly-untrusted identifier, i.e. an em.query select key, subquery `as` name, or
6
- * `sql.ref` column.
6
+ * `a.column` column.
7
7
  *
8
8
  * `kq`'s inputs are trusted metadata (codegen'd table/column names), and its quoting assumes that;
9
9
  * these idents are user strings, so embedded quotes are escaped like PG's own quote_ident, which
@@ -3,7 +3,7 @@
3
3
  declare function kq(ident: string): string;
4
4
  /**
5
5
  * Quotes a possibly-untrusted identifier, i.e. an em.query select key, subquery `as` name, or
6
- * `sql.ref` column.
6
+ * `a.column` column.
7
7
  *
8
8
  * `kq`'s inputs are trusted metadata (codegen'd table/column names), and its quoting assumes that;
9
9
  * these idents are user strings, so embedded quotes are escaped like PG's own quote_ident, which
@@ -108,7 +108,7 @@ function kq(ident) {
108
108
  }
109
109
  /**
110
110
  * Quotes a possibly-untrusted identifier, i.e. an em.query select key, subquery `as` name, or
111
- * `sql.ref` column.
111
+ * `a.column` column.
112
112
  *
113
113
  * `kq`'s inputs are trusted metadata (codegen'd table/column names), and its quoting assumes that;
114
114
  * these idents are user strings, so embedded quotes are escaped like PG's own quote_ident, which
@@ -1 +1 @@
1
- {"version":3,"file":"keywords.js","names":[],"sources":["../../../src/queries/sql/keywords.ts"],"sourcesContent":["// select word from pg_get_keywords() where catdesc = 'reserved' order by word;\nconst keywords = [\n \"all\",\n \"alter\",\n \"analyse\",\n \"analyze\",\n \"and\",\n \"any\",\n \"array\",\n \"as\",\n \"asc\",\n \"avg\",\n \"between\",\n \"by\",\n \"asymmetric\",\n \"both\",\n \"case\",\n \"count\",\n \"cast\",\n \"check\",\n \"collate\",\n \"column\",\n \"constraint\",\n \"create\",\n \"delete\",\n \"current_catalog\",\n \"current_date\",\n \"current_role\",\n \"current_time\",\n \"current_timestamp\",\n \"current_user\",\n \"default\",\n \"deferrable\",\n \"desc\",\n \"distinct\",\n \"drop\",\n \"do\",\n \"else\",\n \"end\",\n \"from\",\n \"except\",\n \"false\",\n \"fetch\",\n \"for\",\n \"foreign\",\n \"from\",\n \"grant\",\n \"group\",\n \"having\",\n \"in\",\n \"inner\",\n \"insert\",\n \"initially\",\n \"intersect\",\n \"into\",\n \"is\",\n \"join\",\n \"left\",\n \"like\",\n \"max\",\n \"min\",\n \"lateral\",\n \"leading\",\n \"limit\",\n \"localtime\",\n \"localtimestamp\",\n \"not\",\n \"null\",\n \"offset\",\n \"on\",\n \"only\",\n \"or\",\n \"order\",\n \"outer\",\n \"right\",\n \"placing\",\n \"primary\",\n \"references\",\n \"returning\",\n \"select\",\n \"set\",\n \"sum\",\n \"session_user\",\n \"some\",\n \"symmetric\",\n \"table\",\n \"then\",\n \"to\",\n \"trailing\",\n \"true\",\n \"union\",\n \"update\",\n \"values\",\n \"unique\",\n \"user\",\n \"using\",\n \"variadic\",\n \"when\",\n \"where\",\n \"window\",\n \"with\",\n];\n\n// Cache all keywords => their escaped equivalent\nconst escapeMapped = new Map(keywords.map((k) => [k, `\"${k}\"`]));\nconst allLower = /^[a-z0-9_]+$/;\n\n/** Conditionally quotes `identifier` if it's a SQL keyword or not snake cased; for trusted idents only. */\nexport function kq(ident: string): string {\n // All camel-cased identifiers/column names need to be quoted\n if (!allLower.test(ident)) return `\"${ident}\"`;\n return escapeMapped.get(ident) ?? ident;\n}\n\n/**\n * Quotes a possibly-untrusted identifier, i.e. an em.query select key, subquery `as` name, or\n * `sql.ref` column.\n *\n * `kq`'s inputs are trusted metadata (codegen'd table/column names), and its quoting assumes that;\n * these idents are user strings, so embedded quotes are escaped like PG's own quote_ident, which\n * keeps display-name keys (`select: { \"Book Count\": ... }`) working. Names longer than PG's 63-byte\n * identifier limit are still rejected: PG would silently truncate them and break row decoding.\n */\nexport function safeKq(ident: string): string {\n if (ident.length > 63) throw new Error(`Identifier '${ident}' is longer than PG's 63-byte limit`);\n if (!ident.includes('\"')) return kq(ident);\n return `\"${ident.replaceAll('\"', '\"\"')}\"`;\n}\n\nexport function kqDot(alias: string, column: string): string {\n return `${kq(alias)}.${kq(column)}`;\n}\n\nexport function kqStar(alias: string): string {\n return `${kq(alias)}.*`;\n}\n"],"mappings":";AAwGA,MAAM,eAAe,IAAI,IAAI;CAtG3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AAIkC,CAAC,CAAC,KAAK,MAAM,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,CAAC;AAC/D,MAAM,WAAW;;AAGjB,SAAgB,GAAG,OAAuB;CAExC,IAAI,CAAC,SAAS,KAAK,KAAK,GAAG,OAAO,IAAI,MAAM;CAC5C,OAAO,aAAa,IAAI,KAAK,KAAK;AACpC;;;;;;;;;;AAWA,SAAgB,OAAO,OAAuB;CAC5C,IAAI,MAAM,SAAS,IAAI,MAAM,IAAI,MAAM,eAAe,MAAM,oCAAoC;CAChG,IAAI,CAAC,MAAM,SAAS,IAAG,GAAG,OAAO,GAAG,KAAK;CACzC,OAAO,IAAI,MAAM,WAAW,MAAK,MAAI,EAAE;AACzC;AAEA,SAAgB,MAAM,OAAe,QAAwB;CAC3D,OAAO,GAAG,GAAG,KAAK,EAAE,GAAG,GAAG,MAAM;AAClC;AAEA,SAAgB,OAAO,OAAuB;CAC5C,OAAO,GAAG,GAAG,KAAK,EAAE;AACtB"}
1
+ {"version":3,"file":"keywords.js","names":[],"sources":["../../../src/queries/sql/keywords.ts"],"sourcesContent":["// select word from pg_get_keywords() where catdesc = 'reserved' order by word;\nconst keywords = [\n \"all\",\n \"alter\",\n \"analyse\",\n \"analyze\",\n \"and\",\n \"any\",\n \"array\",\n \"as\",\n \"asc\",\n \"avg\",\n \"between\",\n \"by\",\n \"asymmetric\",\n \"both\",\n \"case\",\n \"count\",\n \"cast\",\n \"check\",\n \"collate\",\n \"column\",\n \"constraint\",\n \"create\",\n \"delete\",\n \"current_catalog\",\n \"current_date\",\n \"current_role\",\n \"current_time\",\n \"current_timestamp\",\n \"current_user\",\n \"default\",\n \"deferrable\",\n \"desc\",\n \"distinct\",\n \"drop\",\n \"do\",\n \"else\",\n \"end\",\n \"from\",\n \"except\",\n \"false\",\n \"fetch\",\n \"for\",\n \"foreign\",\n \"from\",\n \"grant\",\n \"group\",\n \"having\",\n \"in\",\n \"inner\",\n \"insert\",\n \"initially\",\n \"intersect\",\n \"into\",\n \"is\",\n \"join\",\n \"left\",\n \"like\",\n \"max\",\n \"min\",\n \"lateral\",\n \"leading\",\n \"limit\",\n \"localtime\",\n \"localtimestamp\",\n \"not\",\n \"null\",\n \"offset\",\n \"on\",\n \"only\",\n \"or\",\n \"order\",\n \"outer\",\n \"right\",\n \"placing\",\n \"primary\",\n \"references\",\n \"returning\",\n \"select\",\n \"set\",\n \"sum\",\n \"session_user\",\n \"some\",\n \"symmetric\",\n \"table\",\n \"then\",\n \"to\",\n \"trailing\",\n \"true\",\n \"union\",\n \"update\",\n \"values\",\n \"unique\",\n \"user\",\n \"using\",\n \"variadic\",\n \"when\",\n \"where\",\n \"window\",\n \"with\",\n];\n\n// Cache all keywords => their escaped equivalent\nconst escapeMapped = new Map(keywords.map((k) => [k, `\"${k}\"`]));\nconst allLower = /^[a-z0-9_]+$/;\n\n/** Conditionally quotes `identifier` if it's a SQL keyword or not snake cased; for trusted idents only. */\nexport function kq(ident: string): string {\n // All camel-cased identifiers/column names need to be quoted\n if (!allLower.test(ident)) return `\"${ident}\"`;\n return escapeMapped.get(ident) ?? ident;\n}\n\n/**\n * Quotes a possibly-untrusted identifier, i.e. an em.query select key, subquery `as` name, or\n * `a.column` column.\n *\n * `kq`'s inputs are trusted metadata (codegen'd table/column names), and its quoting assumes that;\n * these idents are user strings, so embedded quotes are escaped like PG's own quote_ident, which\n * keeps display-name keys (`select: { \"Book Count\": ... }`) working. Names longer than PG's 63-byte\n * identifier limit are still rejected: PG would silently truncate them and break row decoding.\n */\nexport function safeKq(ident: string): string {\n if (ident.length > 63) throw new Error(`Identifier '${ident}' is longer than PG's 63-byte limit`);\n if (!ident.includes('\"')) return kq(ident);\n return `\"${ident.replaceAll('\"', '\"\"')}\"`;\n}\n\nexport function kqDot(alias: string, column: string): string {\n return `${kq(alias)}.${kq(column)}`;\n}\n\nexport function kqStar(alias: string): string {\n return `${kq(alias)}.*`;\n}\n"],"mappings":";AAwGA,MAAM,eAAe,IAAI,IAAI;CAtG3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AAIkC,CAAC,CAAC,KAAK,MAAM,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,CAAC;AAC/D,MAAM,WAAW;;AAGjB,SAAgB,GAAG,OAAuB;CAExC,IAAI,CAAC,SAAS,KAAK,KAAK,GAAG,OAAO,IAAI,MAAM;CAC5C,OAAO,aAAa,IAAI,KAAK,KAAK;AACpC;;;;;;;;;;AAWA,SAAgB,OAAO,OAAuB;CAC5C,IAAI,MAAM,SAAS,IAAI,MAAM,IAAI,MAAM,eAAe,MAAM,oCAAoC;CAChG,IAAI,CAAC,MAAM,SAAS,IAAG,GAAG,OAAO,GAAG,KAAK;CACzC,OAAO,IAAI,MAAM,WAAW,MAAK,MAAI,EAAE;AACzC;AAEA,SAAgB,MAAM,OAAe,QAAwB;CAC3D,OAAO,GAAG,GAAG,KAAK,EAAE,GAAG,GAAG,MAAM;AAClC;AAEA,SAAgB,OAAO,OAAuB;CAC5C,OAAO,GAAG,GAAG,KAAK,EAAE;AACtB"}