@dbsp/adapter-pgsql 7.3.0 → 8.1.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.
@@ -12890,6 +12890,9 @@ function resolveCaseValue(value, alias, _schema, resolveColumn, state, nestedCas
12890
12890
  if (typeof expr.value === "number") {
12891
12891
  return numericLiteralNode(expr.value);
12892
12892
  }
12893
+ if (typeof expr.value === "string") {
12894
+ return stringConstNode(expr.value);
12895
+ }
12893
12896
  return bindParameter(expr.value, state);
12894
12897
  case "column":
12895
12898
  return resolveColumn?.(expr.column) ?? sqlColumnRef(queryLocal(expr.column), queryLocal(alias));
@@ -17535,8 +17538,13 @@ function createConditionCompiler(createWhereDispatcher2, buildCustomFnFilter3) {
17535
17538
  exprIntent.value
17536
17539
  );
17537
17540
  if (nullComparison) return nullComparison;
17541
+ const value = exprIntent.value;
17542
+ if (typeof value === "object" && value !== null) {
17543
+ const rightNode2 = compileExpressionValue(value, ctx, handlerCtx, true);
17544
+ if (rightNode2 !== null) return compileComparison2(leftNode, rightNode2);
17545
+ }
17538
17546
  const idx = ++ctx.paramState.paramIndex;
17539
- ctx.paramState.parameters.push(unwrapParamIntent(exprIntent.value));
17547
+ ctx.paramState.parameters.push(unwrapParamIntent(value));
17540
17548
  const rightNode = createParamRef(idx);
17541
17549
  return compileComparison2(leftNode, rightNode);
17542
17550
  }
@@ -17809,37 +17817,38 @@ function createConditionCompiler(createWhereDispatcher2, buildCustomFnFilter3) {
17809
17817
  if (ctx.directRootWhere && cmpIntent.jsonPath !== void 0) return null;
17810
17818
  const v = cmpIntent.value;
17811
17819
  if (v === null || typeof v !== "object") return null;
17820
+ const rightNode = compileExpressionValue(v, ctx, handlerCtx);
17821
+ if (rightNode === null) return null;
17822
+ return compileMappedComparison(cmpIntent.operator)(
17823
+ // buildColumnRef handles dotted field names like 'table.col' by splitting them.
17824
+ buildColumnRef(cmpIntent.field, handlerCtx),
17825
+ rightNode
17826
+ );
17827
+ }
17828
+ function compileExpressionValue(v, ctx, handlerCtx, skipParam = false) {
17812
17829
  const rec = v;
17813
17830
  if (isOuterRef(v)) {
17814
- return compileMappedComparison(cmpIntent.operator)(
17815
- buildColumnRef(cmpIntent.field, handlerCtx),
17816
- compileValueOrFieldRef(
17817
- { kind: "fieldRef", scope: "outer", column: rec.column },
17818
- handlerCtx,
17819
- ctx.paramState
17820
- )
17831
+ return compileValueOrFieldRef(
17832
+ { kind: "fieldRef", scope: "outer", column: rec.column },
17833
+ handlerCtx,
17834
+ ctx.paramState
17821
17835
  );
17822
17836
  }
17823
17837
  if (EXPRESSION_BRAND2 in v && v[EXPRESSION_BRAND2] === true) {
17824
- const compileComparison2 = compileMappedComparison(cmpIntent.operator);
17825
17838
  const exprRef = v;
17826
- const leftNode = buildColumnRef(cmpIntent.field, handlerCtx);
17827
- const rightNode = compileExpressionIntent(
17839
+ if (skipParam && exprRef.intent.kind === "param") return null;
17840
+ return compileExpressionIntent(
17828
17841
  exprRef.intent,
17829
17842
  handlerCtx,
17830
17843
  ctx.paramState
17831
17844
  );
17832
- return compileComparison2(leftNode, rightNode);
17833
17845
  }
17834
17846
  if (REF_BRAND in v && v[REF_BRAND] === "ref" && typeof rec.target === "string") {
17835
- const compileComparison2 = compileMappedComparison(cmpIntent.operator);
17836
- const leftNode = buildColumnRef(cmpIntent.field, handlerCtx);
17837
- const rightNode = compileExpressionIntent(
17847
+ return compileExpressionIntent(
17838
17848
  { kind: "ref", column: rec.target },
17839
17849
  handlerCtx,
17840
17850
  ctx.paramState
17841
17851
  );
17842
- return compileComparison2(leftNode, rightNode);
17843
17852
  }
17844
17853
  return null;
17845
17854
  }
@@ -22724,7 +22733,12 @@ var PG_RESERVED = /* @__PURE__ */ new Set([
22724
22733
  // Non-reserved but used as output column alias by dbsp compiler
22725
22734
  "exists",
22726
22735
  // SQL standard function keywords that pgsql-deparser quotes in FuncCall context
22727
- "coalesce"
22736
+ "coalesce",
22737
+ // type_func_name keywords: refused as table, CTE and column names
22738
+ "authorization",
22739
+ "binary",
22740
+ "collation",
22741
+ "concurrently"
22728
22742
  ]);
22729
22743
  function quoteIdent2(name) {
22730
22744
  if (/^[a-z_][a-z0-9_]*$/.test(name) && !PG_RESERVED.has(name)) {
@@ -23129,7 +23143,7 @@ function deparseCommonTableExpr(node) {
23129
23143
  const rec = node;
23130
23144
  const cteName = String(rec.ctename ?? "");
23131
23145
  const ctequery = rec.ctequery;
23132
- const cteCols = rec.cte_cols;
23146
+ const cteCols = node.aliascolnames;
23133
23147
  const cycleClause = rec.cycle_clause;
23134
23148
  let result = `${quoteIdent2(cteName)} AS `;
23135
23149
  if (cteCols && cteCols.length > 0) {
@@ -23150,7 +23164,10 @@ function deparseCommonTableExpr(node) {
23150
23164
  return result;
23151
23165
  }
23152
23166
  function deparseWithClause(node) {
23153
- const recursive = node.recursive ? "WITH RECURSIVE " : "WITH ";
23167
+ const anyRecursiveCte = (node.ctes ?? []).some(
23168
+ (cte) => cte.CommonTableExpr?.cterecursive === true
23169
+ );
23170
+ const recursive = node.recursive || anyRecursiveCte ? "WITH RECURSIVE " : "WITH ";
23154
23171
  const ctes = (node.ctes ?? []).map(nodeToStr).join(", ");
23155
23172
  return `${recursive}${ctes}`;
23156
23173
  }
@@ -23169,6 +23186,14 @@ function deparseCTECycleClause(node) {
23169
23186
  }).join(", ");
23170
23187
  return `CYCLE ${cols2} SET ${quoteIdent2(markColumn)} USING ${quoteIdent2(pathColumn)}`;
23171
23188
  }
23189
+ function setOperandNeedsParentheses(node) {
23190
+ const op2 = node.op;
23191
+ return op2 !== void 0 && op2 !== "SETOP_NONE" || (node.sortClause?.length ?? 0) > 0 || Boolean(node.limitCount) || Boolean(node.limitOffset) || (node.lockingClause?.length ?? 0) > 0 || Boolean(node.withClause);
23192
+ }
23193
+ function deparseSetOperand(node) {
23194
+ const sql = deparseSelectStmt(node);
23195
+ return setOperandNeedsParentheses(node) ? `(${sql})` : sql;
23196
+ }
23172
23197
  function deparseSelectStmt(node) {
23173
23198
  const rec = node;
23174
23199
  const op2 = rec.op;
@@ -23176,8 +23201,8 @@ function deparseSelectStmt(node) {
23176
23201
  const larg = rec.larg;
23177
23202
  const rarg = rec.rarg;
23178
23203
  const all = rec.all;
23179
- const left = larg ? deparseSelectStmt(larg) : "";
23180
- const right = rarg ? deparseSelectStmt(rarg) : "";
23204
+ const left = larg ? deparseSetOperand(larg) : "";
23205
+ const right = rarg ? deparseSetOperand(rarg) : "";
23181
23206
  let setOp;
23182
23207
  switch (op2) {
23183
23208
  case "SETOP_UNION":
@@ -23192,7 +23217,9 @@ function deparseSelectStmt(node) {
23192
23217
  default:
23193
23218
  setOp = op2;
23194
23219
  }
23195
- return `${left} ${setOp} ${right}`;
23220
+ const setWith = rec.withClause;
23221
+ const body = `${left} ${setOp} ${right}`;
23222
+ return setWith ? `${deparseWithClause(setWith)} ${body}` : body;
23196
23223
  }
23197
23224
  const valuesLists = rec.valuesLists;
23198
23225
  if (valuesLists && valuesLists.length > 0) {
@@ -23254,7 +23281,7 @@ function deparseSelectStmt(node) {
23254
23281
  return parts.join(" ");
23255
23282
  }
23256
23283
  function deparseInsertStmt(node) {
23257
- const parts = ["INSERT INTO"];
23284
+ const parts = node.withClause ? [deparseWithClause(node.withClause), "INSERT INTO"] : ["INSERT INTO"];
23258
23285
  if (node.relation) {
23259
23286
  parts.push(deparseRangeVar(node.relation));
23260
23287
  }
@@ -23293,7 +23320,7 @@ function deparseInsertStmt(node) {
23293
23320
  return parts.join(" ");
23294
23321
  }
23295
23322
  function deparseUpdateStmt(node) {
23296
- const parts = ["UPDATE"];
23323
+ const parts = node.withClause ? [deparseWithClause(node.withClause), "UPDATE"] : ["UPDATE"];
23297
23324
  if (node.relation) {
23298
23325
  parts.push(deparseRangeVar(node.relation));
23299
23326
  }
@@ -23318,7 +23345,7 @@ function deparseUpdateStmt(node) {
23318
23345
  return parts.join(" ");
23319
23346
  }
23320
23347
  function deparseDeleteStmt(node) {
23321
- const parts = ["DELETE FROM"];
23348
+ const parts = node.withClause ? [deparseWithClause(node.withClause), "DELETE FROM"] : ["DELETE FROM"];
23322
23349
  if (node.relation) {
23323
23350
  parts.push(deparseRangeVar(node.relation));
23324
23351
  }
@@ -27177,7 +27204,7 @@ import {
27177
27204
  // src/pgsql-adapter.ts
27178
27205
  import {
27179
27206
  copyDefaultFilters,
27180
- getRelationalReadPlan as getRelationalReadPlan3,
27207
+ getRelationalReadPlan as getRelationalReadPlan2,
27181
27208
  planInScope as planInScope2,
27182
27209
  resolveReportIncludes as resolveReportIncludes2,
27183
27210
  validateRecursiveSetOperation
@@ -27200,8 +27227,7 @@ import { inspectMutationRows as inspectMutationRows2 } from "@dbsp/core/internal
27200
27227
  import { convertBigintJsReadValue } from "@dbsp/types";
27201
27228
  import {
27202
27229
  assertCompiledQuery,
27203
- projectionlessCompiledQuery,
27204
- rebuildCompiledQuery
27230
+ projectionlessCompiledQuery
27205
27231
  } from "@dbsp/types/adapter-sdk";
27206
27232
  import {
27207
27233
  getNqlBindingRefName as getNqlBindingRefName2,
@@ -27662,14 +27688,10 @@ import { resolveOutputReadHandling as resolveOutputReadHandling4 } from "@dbsp/t
27662
27688
  import { compiledQueryFromProjection } from "@dbsp/types/adapter-sdk";
27663
27689
  var projectionEnvelopeBrand = /* @__PURE__ */ Symbol("projectionEnvelope");
27664
27690
  var projectionOutputMaps = /* @__PURE__ */ new WeakMap();
27691
+ var compiledStatementAsts = /* @__PURE__ */ new WeakMap();
27665
27692
  function outputKeyMapFor(query) {
27666
27693
  return query.outputKeyMap ?? projectionOutputMaps.get(query);
27667
27694
  }
27668
- function preserveOutputKeyMap(prior, next) {
27669
- const map = outputKeyMapFor(prior);
27670
- if (map !== void 0) projectionOutputMaps.set(next, map);
27671
- return next;
27672
- }
27673
27695
  var scalarOneShape = {
27674
27696
  kind: "scalar",
27675
27697
  cardinality: "one"
@@ -27770,9 +27792,11 @@ function fromCompiledQuery(compiled) {
27770
27792
  )
27771
27793
  );
27772
27794
  }
27795
+ const ast = compiledStatementAsts.get(compiled);
27773
27796
  return makeEnvelope({
27774
27797
  sql: compiled.sql,
27775
27798
  parameters: compiled.parameters,
27799
+ ...ast !== void 0 ? { ast } : {},
27776
27800
  projection: { kind: "known", outputs },
27777
27801
  ...compiled.hydrationPlan !== void 0 ? { hydrationPlan: compiled.hydrationPlan } : {}
27778
27802
  });
@@ -27939,6 +27963,7 @@ function projectNamedFields(source, options) {
27939
27963
  return makeEnvelope({
27940
27964
  sql: options.sql,
27941
27965
  parameters: options.parameters,
27966
+ ...options.ast !== void 0 ? { ast: options.ast } : {},
27942
27967
  projection: source.projection,
27943
27968
  ...hydrationPlan2 !== void 0 ? { hydrationPlan: hydrationPlan2 } : {}
27944
27969
  });
@@ -27966,6 +27991,7 @@ function projectNamedFields(source, options) {
27966
27991
  return makeEnvelope({
27967
27992
  sql: options.sql,
27968
27993
  parameters: options.parameters,
27994
+ ...options.ast !== void 0 ? { ast: options.ast } : {},
27969
27995
  projection: { kind: "known", outputs },
27970
27996
  ...hydrationPlan !== void 0 ? { hydrationPlan } : {}
27971
27997
  });
@@ -27987,6 +28013,7 @@ function preserveOneToOne(source, options) {
27987
28013
  return makeEnvelope({
27988
28014
  sql: options.sql,
27989
28015
  parameters: options.parameters,
28016
+ ...options.ast !== void 0 ? { ast: options.ast } : {},
27990
28017
  projection: source.projection,
27991
28018
  ...hydrationPlan !== void 0 ? { hydrationPlan } : {}
27992
28019
  });
@@ -27995,6 +28022,7 @@ function dropPositionalUnion(branches, options) {
27995
28022
  return makeEnvelope({
27996
28023
  sql: options.sql,
27997
28024
  parameters: options.parameters,
28025
+ ...options.ast !== void 0 ? { ast: options.ast } : {},
27998
28026
  projection: {
27999
28027
  kind: "dropped",
28000
28028
  reason: options.reason,
@@ -28033,6 +28061,7 @@ function finalizeEnvelope(env) {
28033
28061
  if (env.projection.outputKeyMap !== void 0) {
28034
28062
  projectionOutputMaps.set(compiled2, env.projection.outputKeyMap);
28035
28063
  }
28064
+ if (env.ast !== void 0) compiledStatementAsts.set(compiled2, env.ast);
28036
28065
  return compiled2;
28037
28066
  }
28038
28067
  const columnMetadata = /* @__PURE__ */ new Map();
@@ -28062,6 +28091,7 @@ function finalizeEnvelope(env) {
28062
28091
  };
28063
28092
  const compiled = compiledQueryFromProjection(fields);
28064
28093
  projectionOutputMaps.set(compiled, outputKeyMap);
28094
+ if (env.ast !== void 0) compiledStatementAsts.set(compiled, env.ast);
28065
28095
  return compiled;
28066
28096
  }
28067
28097
  function buildReturnedOutputKeyMap(outputs) {
@@ -29076,6 +29106,83 @@ function planningNodeAtPath(intent, path) {
29076
29106
  return node;
29077
29107
  }
29078
29108
 
29109
+ // src/statement-ast.ts
29110
+ var statementKinds = [
29111
+ "SelectStmt",
29112
+ "InsertStmt",
29113
+ "UpdateStmt",
29114
+ "DeleteStmt"
29115
+ ];
29116
+ function statementKindOf(node) {
29117
+ const [key] = Object.keys(node);
29118
+ return statementKinds.find((kind) => kind === key);
29119
+ }
29120
+ function requireStatementAst(envelope, context) {
29121
+ const ast = envelope.ast;
29122
+ if (ast === void 0 || statementKindOf(ast) === void 0) {
29123
+ throw new Error(
29124
+ `Cannot compose ${context}: its compiled operand carries no statement tree, and composed SQL is built from trees only (ADR 0012).`
29125
+ );
29126
+ }
29127
+ return ast;
29128
+ }
29129
+ function shiftParameters(ast, offset) {
29130
+ return renumberParamRefsInAst(ast, offset);
29131
+ }
29132
+ function selectStmtOf(ast, context) {
29133
+ const select = ast.SelectStmt;
29134
+ if (select === void 0) {
29135
+ throw new Error(
29136
+ `Cannot compose ${context}: the operand is not a SELECT statement.`
29137
+ );
29138
+ }
29139
+ return select;
29140
+ }
29141
+ var setOperationNodes = {
29142
+ union: "SETOP_UNION",
29143
+ intersect: "SETOP_INTERSECT",
29144
+ except: "SETOP_EXCEPT"
29145
+ };
29146
+ function setOperationStatement(op2, all, left, right) {
29147
+ return {
29148
+ SelectStmt: {
29149
+ op: setOperationNodes[op2],
29150
+ all,
29151
+ larg: selectStmtOf(left, `the left operand of ${op2.toUpperCase()}`),
29152
+ rarg: selectStmtOf(right, `the right operand of ${op2.toUpperCase()}`)
29153
+ }
29154
+ };
29155
+ }
29156
+ function commonTableExpression(name, query, options = {}) {
29157
+ const cte = {
29158
+ ctename: name,
29159
+ ctequery: query,
29160
+ ...options.columns !== void 0 && options.columns.length > 0 && {
29161
+ aliascolnames: options.columns.map((column2) => ({
29162
+ String: { sval: column2 }
29163
+ }))
29164
+ },
29165
+ ...options.recursive === true && { cterecursive: true }
29166
+ };
29167
+ return { CommonTableExpr: cte };
29168
+ }
29169
+ function withLeadingCtes(statement, ctes, recursive = false) {
29170
+ if (ctes.length === 0 && !recursive) return statement;
29171
+ const kind = statementKindOf(statement);
29172
+ if (kind === void 0) {
29173
+ throw new Error(
29174
+ "Cannot attach a WITH clause: the statement is not a SELECT, INSERT, UPDATE or DELETE tree."
29175
+ );
29176
+ }
29177
+ const body = statement[kind];
29178
+ const existing = body.withClause;
29179
+ const withClause = {
29180
+ ctes: [...ctes, ...existing?.ctes ?? []],
29181
+ recursive: recursive || existing?.recursive === true
29182
+ };
29183
+ return { [kind]: { ...body, withClause } };
29184
+ }
29185
+
29079
29186
  // src/adapter-compiler-mutations.ts
29080
29187
  var POSTGRESQL_PARAMETER_LIMIT = 65535;
29081
29188
  var HETEROGENEOUS_INSERT_CELL_LIMIT = 2 * POSTGRESQL_PARAMETER_LIMIT;
@@ -29101,12 +29208,6 @@ function assertParameterLimit(operation, count) {
29101
29208
  function whereIntentAsDecision(where) {
29102
29209
  return where;
29103
29210
  }
29104
- function renumberSqlParams(sql, offset) {
29105
- if (offset === 0) return sql;
29106
- return sql.replace(/\$(\d+)/g, (_match, num) => {
29107
- return `$${Number.parseInt(num, 10) + offset}`;
29108
- });
29109
- }
29110
29211
  function compileSourceQueryCte(operation, sourceName, sourceQuery, options, deps) {
29111
29212
  const model = deps.model;
29112
29213
  if (model === void 0) {
@@ -29117,9 +29218,9 @@ function compileSourceQueryCte(operation, sourceName, sourceQuery, options, deps
29117
29218
  const sourcePlan = planFn(sourceQuery, model, {
29118
29219
  dialectCapabilities: deps.dialectCapabilities ?? POSTGRESQL_CAPABILITIES3
29119
29220
  });
29120
- const source = compileSelect(sourcePlan, options, deps);
29221
+ const source = compileSelectEnvelope(sourcePlan, options, deps);
29121
29222
  return {
29122
- sql: source.sql,
29223
+ ast: requireStatementAst(source, `the source query '${sourceName}'`),
29123
29224
  parameters: source.parameters
29124
29225
  };
29125
29226
  }
@@ -29145,12 +29246,20 @@ function prependSourceCte(query, sourceName, sourceCte) {
29145
29246
  if (sourceCte === void 0) {
29146
29247
  return finalizeEnvelope(query);
29147
29248
  }
29148
- const cteParamCount = sourceCte.parameters.length;
29149
29249
  const sourceCteName = emittedBindName(queryLocal(sourceName));
29250
+ validateIdentifier(sourceCteName, "alias");
29251
+ const ast = withLeadingCtes(
29252
+ shiftParameters(
29253
+ requireStatementAst(query, `the mutation reading '${sourceName}'`),
29254
+ sourceCte.parameters.length
29255
+ ),
29256
+ [commonTableExpression(sourceCteName, sourceCte.ast)]
29257
+ );
29150
29258
  return finalizeEnvelope(
29151
29259
  preserveOneToOne(query, {
29152
- sql: `WITH ${quoteIdent(sourceCteName, "alias")} as (${sourceCte.sql}) ${renumberSqlParams(query.sql, cteParamCount)}`,
29153
- parameters: [...sourceCte.parameters, ...query.parameters]
29260
+ sql: deparseQuoted(ast),
29261
+ parameters: [...sourceCte.parameters, ...query.parameters],
29262
+ ast
29154
29263
  })
29155
29264
  );
29156
29265
  }
@@ -30108,12 +30217,13 @@ function buildCteProjectionShape(source, select) {
30108
30217
  }
30109
30218
  return { selections, expressions, preserveOneToOne: false };
30110
30219
  }
30111
- function projectCteQueryEnvelope(source, query, sql, parameters, hydrationPlan) {
30220
+ function projectCteQueryEnvelope(source, query, sql, parameters, hydrationPlan, ast) {
30112
30221
  const shape = buildCteProjectionShape(source, query.select);
30113
30222
  if (shape.preserveOneToOne) {
30114
30223
  return preserveOneToOne(source, {
30115
30224
  sql,
30116
30225
  parameters,
30226
+ ...ast !== void 0 ? { ast } : {},
30117
30227
  ...hydrationPlan !== void 0 ? { hydrationPlan } : {},
30118
30228
  preserveHydrationPlan: false
30119
30229
  });
@@ -30121,6 +30231,7 @@ function projectCteQueryEnvelope(source, query, sql, parameters, hydrationPlan)
30121
30231
  return projectNamedFields(source, {
30122
30232
  sql,
30123
30233
  parameters,
30234
+ ...ast !== void 0 ? { ast } : {},
30124
30235
  selections: shape.selections,
30125
30236
  expressions: shape.expressions,
30126
30237
  ...hydrationPlan !== void 0 ? { hydrationPlan } : {},
@@ -30140,18 +30251,20 @@ function compileQueryEnvelope(query, options, deps, registry) {
30140
30251
  query,
30141
30252
  compiled.sql,
30142
30253
  compiled.parameters,
30143
- compiled.hydrationPlan
30254
+ compiled.hydrationPlan,
30255
+ compiled.ast
30144
30256
  );
30145
30257
  }
30146
30258
  return compiled;
30147
30259
  }
30148
- function rehomeQueryEnvelope(source, query, compiled, sql, parameters) {
30260
+ function rehomeQueryEnvelope(source, query, compiled, sql, parameters, ast) {
30149
30261
  return projectCteQueryEnvelope(
30150
30262
  source,
30151
30263
  query,
30152
30264
  sql,
30153
30265
  parameters,
30154
- compiled.hydrationPlan
30266
+ compiled.hydrationPlan,
30267
+ ast
30155
30268
  );
30156
30269
  }
30157
30270
  function compileRecursive(report, model, options, deps) {
@@ -30502,9 +30615,14 @@ function compileRecursive(report, model, options, deps) {
30502
30615
  return finalizeEnvelope(env);
30503
30616
  }
30504
30617
  function compileCteQuery(intent, options, deps, initialProjectionByName) {
30618
+ return finalizeEnvelope(
30619
+ compileCteQueryEnvelope(intent, options, deps, initialProjectionByName)
30620
+ );
30621
+ }
30622
+ function compileCteQueryEnvelope(intent, options, deps, initialProjectionByName) {
30505
30623
  const state = createCompilerState();
30506
30624
  const allCteParams = [];
30507
- const cteSqlFragments = [];
30625
+ const cteNodes = [];
30508
30626
  const cteProjectionByName = new Map(
30509
30627
  initialProjectionByName
30510
30628
  );
@@ -30523,12 +30641,11 @@ function compileCteQuery(intent, options, deps, initialProjectionByName) {
30523
30641
  const node = buildUnnestCte(cte, state);
30524
30642
  const cteParams = state.parameters.slice(beforeUnnestParamCount);
30525
30643
  allCteParams.push(...cteParams);
30526
- const cteSql = deparseQuoted(node);
30527
- cteSqlFragments.push(cteSql);
30644
+ cteNodes.push(node);
30528
30645
  cteProjectionByName.set(
30529
30646
  emittedCteName,
30530
30647
  fromOutputDescriptors({
30531
- sql: cteSql,
30648
+ sql: deparseQuoted(node),
30532
30649
  parameters: cteParams,
30533
30650
  columns: [
30534
30651
  ...Object.keys(cte.columns),
@@ -30538,7 +30655,6 @@ function compileCteQuery(intent, options, deps, initialProjectionByName) {
30538
30655
  );
30539
30656
  } else if (cte.kind === "rawCte") {
30540
30657
  isRecursive = true;
30541
- const currentParamOffset = allCteParams.length;
30542
30658
  const rawCteStepDeps = withBindingProjectionScope(
30543
30659
  visibleCteDeps,
30544
30660
  withBindingName(visibleCteDeps.bindingNames, queryLocal(cte.name)),
@@ -30552,20 +30668,9 @@ function compileCteQuery(intent, options, deps, initialProjectionByName) {
30552
30668
  cteProjectionByName
30553
30669
  );
30554
30670
  finalizeEnvelope(rawCte.projection);
30555
- const renumberedRawCteSql = currentParamOffset > 0 ? rawCte.sql.replace(
30556
- /\$([0-9]+)/g,
30557
- (_, n) => `$${parseInt(n, 10) + currentParamOffset}`
30558
- ) : rawCte.sql;
30671
+ cteNodes.push(shiftParameters(rawCte.ast, allCteParams.length));
30559
30672
  allCteParams.push(...rawCte.params);
30560
- cteSqlFragments.push(renumberedRawCteSql);
30561
- cteProjectionByName.set(
30562
- emittedCteName,
30563
- preserveOneToOne(rawCte.bindingProjection, {
30564
- sql: renumberedRawCteSql,
30565
- parameters: rawCte.params,
30566
- preserveHydrationPlan: false
30567
- })
30568
- );
30673
+ cteProjectionByName.set(emittedCteName, rawCte.bindingProjection);
30569
30674
  } else if (cte.kind === "simpleCte") {
30570
30675
  const innerCte = cte;
30571
30676
  const innerCompiled = compileQueryEnvelope(
@@ -30575,17 +30680,20 @@ function compileCteQuery(intent, options, deps, initialProjectionByName) {
30575
30680
  cteProjectionByName
30576
30681
  );
30577
30682
  assertRelationalOutput(innerCompiled.hydrationPlan, "Relational bodies");
30578
- const currentParamOffset = allCteParams.length;
30579
- const renumberedInnerSql = currentParamOffset > 0 ? innerCompiled.sql.replace(
30580
- /\$([0-9]+)/g,
30581
- (_, n) => `$${parseInt(n, 10) + currentParamOffset}`
30582
- ) : innerCompiled.sql;
30683
+ cteNodes.push(
30684
+ commonTableExpression(
30685
+ emittedCteName,
30686
+ shiftParameters(
30687
+ requireStatementAst(innerCompiled, `CTE '${cte.name}'`),
30688
+ allCteParams.length
30689
+ )
30690
+ )
30691
+ );
30583
30692
  allCteParams.push(...innerCompiled.parameters);
30584
- cteSqlFragments.push(`"${emittedCteName}" AS (${renumberedInnerSql})`);
30585
30693
  cteProjectionByName.set(
30586
30694
  emittedCteName,
30587
30695
  preserveOneToOne(innerCompiled, {
30588
- sql: renumberedInnerSql,
30696
+ sql: innerCompiled.sql,
30589
30697
  parameters: innerCompiled.parameters,
30590
30698
  preserveHydrationPlan: false
30591
30699
  })
@@ -30618,23 +30726,24 @@ function compileCteQuery(intent, options, deps, initialProjectionByName) {
30618
30726
  relationTargetProjections: cteProjectionByName
30619
30727
  }
30620
30728
  );
30621
- const cteParamCount = allCteParams.length;
30622
- const renumberedOuterSql = cteParamCount > 0 ? outerCompiled.sql.replace(
30623
- /\$([0-9]+)/g,
30624
- (_, n) => `$${parseInt(n, 10) + cteParamCount}`
30625
- ) : outerCompiled.sql;
30626
- const withClause = cteSqlFragments.join(", ");
30627
- const withKeyword = isRecursive ? "WITH RECURSIVE" : "WITH";
30628
- const sql = withClause.length > 0 ? `${withKeyword} ${withClause} ${renumberedOuterSql}` : renumberedOuterSql;
30729
+ const ast = withLeadingCtes(
30730
+ shiftParameters(
30731
+ requireStatementAst(outerCompiled, "the outer query of a CTE query"),
30732
+ allCteParams.length
30733
+ ),
30734
+ cteNodes,
30735
+ isRecursive
30736
+ );
30737
+ const sql = deparseQuoted(ast);
30629
30738
  const parameters = [...allCteParams, ...outerCompiled.parameters];
30630
- const env = outerRegisteredSource ? projectCteQueryEnvelope(
30739
+ return outerRegisteredSource ? projectCteQueryEnvelope(
30631
30740
  outerRegisteredSource,
30632
30741
  intent.query,
30633
30742
  sql,
30634
30743
  parameters,
30635
- outerCompiled.hydrationPlan
30636
- ) : preserveOneToOne(outerCompiled, { sql, parameters });
30637
- return finalizeEnvelope(env);
30744
+ outerCompiled.hydrationPlan,
30745
+ ast
30746
+ ) : preserveOneToOne(outerCompiled, { sql, parameters, ast });
30638
30747
  }
30639
30748
  function buildUnnestCte(cte, state) {
30640
30749
  const columns = Object.keys(cte.columns);
@@ -30717,39 +30826,52 @@ function buildRawCte(cte, anchorDeps, stepDeps, options, registry) {
30717
30826
  options,
30718
30827
  scopedStepDeps
30719
30828
  );
30720
- const baseParamCount = baseCompiled.parameters.length;
30721
- const renumberedStepSql = baseParamCount > 0 ? rawStepCompiled.sql.replace(
30722
- /\$([0-9]+)/g,
30723
- (_, n) => `$${parseInt(n, 10) + baseParamCount}`
30724
- ) : rawStepCompiled.sql;
30829
+ const baseAst = requireStatementAst(
30830
+ baseCompiled,
30831
+ `the base of recursive CTE '${cte.name}'`
30832
+ );
30833
+ const shiftedStepAst = shiftParameters(
30834
+ requireStatementAst(
30835
+ rawStepCompiled,
30836
+ `the step of recursive CTE '${cte.name}'`
30837
+ ),
30838
+ baseCompiled.parameters.length
30839
+ );
30725
30840
  const allParams = [
30726
30841
  ...baseCompiled.parameters,
30727
30842
  ...rawStepCompiled.parameters
30728
30843
  ];
30729
- let finalStepSql = renumberedStepSql;
30844
+ let stepAst = shiftedStepAst;
30730
30845
  if (cte.maxDepth !== void 0) {
30731
- const depthCol = `"${(cte.depthColumn ?? "depth").replace(/"/g, '""')}"`;
30732
- const depthParamIndex = allParams.length + 1;
30733
30846
  allParams.push(cte.maxDepth);
30734
- const hasWhere = /\bWHERE\b/i.test(finalStepSql);
30735
- finalStepSql = hasWhere ? `${finalStepSql} AND ${depthCol} < $${depthParamIndex}` : `${finalStepSql} WHERE ${depthCol} < $${depthParamIndex}`;
30847
+ stepAst = withDepthGuard(
30848
+ shiftedStepAst,
30849
+ cte.depthColumn ?? "depth",
30850
+ allParams.length,
30851
+ cte.name
30852
+ );
30736
30853
  }
30854
+ const stepSql = deparseQuoted(stepAst);
30737
30855
  const stepRegisteredSource = stepQuery.from === cte.name ? baseCompiled : getRegisteredProjection(stepProjectionRegistry, stepQuery.from);
30738
30856
  const stepCompiled = stepRegisteredSource ? rehomeQueryEnvelope(
30739
30857
  stepRegisteredSource,
30740
30858
  stepQuery,
30741
30859
  rawStepCompiled,
30742
- finalStepSql,
30743
- allParams
30860
+ stepSql,
30861
+ allParams,
30862
+ stepAst
30744
30863
  ) : preserveOneToOne(rawStepCompiled, {
30745
- sql: finalStepSql,
30746
- parameters: allParams
30864
+ sql: stepSql,
30865
+ parameters: allParams,
30866
+ ast: stepAst
30747
30867
  });
30748
- const setOp = cte.unionAll ? "UNION ALL" : "UNION";
30749
- const cteName = `"${emittedBindName(queryLocal(cte.name))}"`;
30750
- const cteSql = `${cteName} AS (${baseCompiled.sql} ${setOp} ${finalStepSql})`;
30868
+ const ast = commonTableExpression(
30869
+ emittedBindName(queryLocal(cte.name)),
30870
+ setOperationStatement("union", cte.unionAll === true, baseAst, stepAst)
30871
+ );
30872
+ const cteSql = deparseQuoted(ast);
30751
30873
  return {
30752
- sql: cteSql,
30874
+ ast,
30753
30875
  params: allParams,
30754
30876
  projection: dropPositionalUnion([baseCompiled, stepCompiled], {
30755
30877
  sql: cteSql,
@@ -30765,6 +30887,25 @@ function buildRawCte(cte, anchorDeps, stepDeps, options, registry) {
30765
30887
  })
30766
30888
  };
30767
30889
  }
30890
+ function withDepthGuard(stepAst, depthColumn, paramNumber, cteName) {
30891
+ const step = stepAst.SelectStmt;
30892
+ if (step === void 0 || step.op !== void 0 && step.op !== "SETOP_NONE") {
30893
+ throw new Error(
30894
+ `Cannot add the depth guard of recursive CTE '${cteName}': its step is not a plain SELECT.`
30895
+ );
30896
+ }
30897
+ const guard = binaryExpr(
30898
+ "<",
30899
+ { ColumnRef: { fields: [stringNode(depthColumn)] } },
30900
+ createParamRef(paramNumber)
30901
+ );
30902
+ return {
30903
+ SelectStmt: {
30904
+ ...step,
30905
+ whereClause: step.whereClause !== void 0 ? andExpr(step.whereClause, guard) : guard
30906
+ }
30907
+ };
30908
+ }
30768
30909
 
30769
30910
  // src/ddl/table-operations.ts
30770
30911
  function quoteIdentifier2(name) {
@@ -32128,52 +32269,37 @@ function normalizeMaxPreparedStatements(maxStatements) {
32128
32269
  }
32129
32270
 
32130
32271
  // src/set-operation.ts
32131
- import { getRelationalReadPlan as getRelationalReadPlan2 } from "@dbsp/core/internal";
32132
- function isProjectionEnvelope(result) {
32133
- return "projection" in result;
32134
- }
32135
- function toProjectionEnvelope(result) {
32136
- return isProjectionEnvelope(result) ? result : fromCompiledQuery(result);
32137
- }
32138
- function renumberParams(sql, offset) {
32139
- if (offset === 0) return sql;
32140
- return sql.replace(/\$(\d+)/g, (_match, num) => {
32141
- return `$${Number.parseInt(num, 10) + offset}`;
32142
- });
32143
- }
32144
- function compileSetOperation(intent, compileFn) {
32145
- return finalizeEnvelope(compileSetOperationEnvelope(intent, compileFn));
32146
- }
32147
- function compileSetOperationEnvelope(intent, compileFn) {
32148
- const left = compileLeafOrBranch(intent.left, compileFn);
32272
+ function compileSetOperationEnvelope(intent, compileLeaf) {
32273
+ const left = compileLeafOrBranch(intent.left, compileLeaf);
32149
32274
  assertRelationalOutput(left.hydrationPlan, "Set operations");
32150
- const right = compileLeafOrBranch(intent.right, compileFn);
32275
+ const right = compileLeafOrBranch(intent.right, compileLeaf);
32151
32276
  assertRelationalOutput(right.hydrationPlan, "Set operations");
32152
- const rightSQL = renumberParams(right.sql, left.parameters.length);
32153
- const opKeyword = intent.op.toUpperCase() + (intent.all ? " ALL" : "");
32154
- const sql = `(${left.sql}) ${opKeyword} (${rightSQL})`;
32277
+ const opName = intent.op.toUpperCase();
32278
+ const ast = setOperationStatement(
32279
+ intent.op,
32280
+ intent.all,
32281
+ requireStatementAst(left, `the left operand of ${opName}`),
32282
+ shiftParameters(
32283
+ requireStatementAst(right, `the right operand of ${opName}`),
32284
+ left.parameters.length
32285
+ )
32286
+ );
32155
32287
  const parameters = [...left.parameters, ...right.parameters];
32156
32288
  return dropPositionalUnion([left, right], {
32157
- sql,
32289
+ sql: deparseQuoted(ast),
32158
32290
  parameters,
32291
+ ast,
32159
32292
  reason: "set-operation-positional-merge"
32160
32293
  });
32161
32294
  }
32162
- function compileLeafOrBranch(intent, compileFn) {
32295
+ function compileLeafOrBranch(intent, compileLeaf) {
32163
32296
  if ("kind" in intent && intent.kind === "setOperation") {
32164
- return compileSetOperationEnvelope(intent, compileFn);
32165
- }
32166
- return toProjectionEnvelope(compileFn(intent));
32167
- }
32168
- function createLeafCompileFn(adapter, model, planFn3, options) {
32169
- return (query) => {
32170
- const planReport = getRelationalReadPlan2(query) ?? planFn3(query, model, {
32171
- dialectCapabilities: adapter.dialectCapabilities
32172
- });
32173
- return fromCompiledQuery(
32174
- adapter.compile(planReport, { ...options, model })
32297
+ return compileSetOperationEnvelope(
32298
+ intent,
32299
+ compileLeaf
32175
32300
  );
32176
- };
32301
+ }
32302
+ return compileLeaf(intent);
32177
32303
  }
32178
32304
 
32179
32305
  // src/streaming/cursor.ts
@@ -33052,12 +33178,6 @@ function protectedStatementCleanupAction(rawSqlStatement, detail2) {
33052
33178
  function raise(error) {
33053
33179
  throw error;
33054
33180
  }
33055
- function renumberSqlParams2(sql, offset) {
33056
- if (offset === 0) return sql;
33057
- return sql.replace(/\$(\d+)/g, (_match, num) => {
33058
- return `$${Number.parseInt(num, 10) + offset}`;
33059
- });
33060
- }
33061
33181
  function pgReturnedIdentifier2(identifier3) {
33062
33182
  let result = "";
33063
33183
  let byteLength = 0;
@@ -33069,16 +33189,6 @@ function pgReturnedIdentifier2(identifier3) {
33069
33189
  }
33070
33190
  return result;
33071
33191
  }
33072
- function prefixNqlBindingCtes(bindingCtes, sql) {
33073
- if (bindingCtes.length === 0) return sql;
33074
- const withMatch = /^(WITH\s+RECURSIVE\s+|WITH\s+)/i.exec(sql);
33075
- if (!withMatch) {
33076
- return `WITH ${bindingCtes.join(", ")} ${sql}`;
33077
- }
33078
- const [prefix] = withMatch;
33079
- const withKeyword = /^WITH\s+RECURSIVE\s+/i.test(prefix) ? "WITH RECURSIVE" : "WITH";
33080
- return `${withKeyword} ${bindingCtes.join(", ")}, ${sql.slice(prefix.length)}`;
33081
- }
33082
33192
  function isCompiledNqlQuery(input) {
33083
33193
  return !("rootTable" in input) && !("intent" in input) && ("query" in input || "cteQuery" in input || "mutation" in input || "setOperation" in input || "bindings" in input || "mutationBindings" in input || "runtimeBindings" in input);
33084
33194
  }
@@ -33375,7 +33485,48 @@ function resolveRuntimeBindingCteColumnTypes(name, binding, schemaName) {
33375
33485
  return resolvePgTypeForColumnTypeInfo(name, column2, info, schemaName);
33376
33486
  });
33377
33487
  }
33378
- function compileTypedNqlRuntimeBindingCte(name, binding, parameterOffset, cteName, columnSql, targetSchema) {
33488
+ function runtimeBindingCast(arg, pgType) {
33489
+ return {
33490
+ TypeCast: { arg, typeName: { names: [stringNode(pgType)], typemod: -1 } }
33491
+ };
33492
+ }
33493
+ function runtimeBindingCteNode(name, binding, parameterOffset, cteName, cteColumns, anchor, rowTypes) {
33494
+ const header = { columns: cteColumns };
33495
+ if (binding.rows.length === 0) {
33496
+ return {
33497
+ cte: commonTableExpression(cteName, { SelectStmt: anchor }, header),
33498
+ parameters: []
33499
+ };
33500
+ }
33501
+ assertRuntimeBindingValuesParameterCount(name, binding, parameterOffset);
33502
+ const parameters = [];
33503
+ let nextParam = parameterOffset + 1;
33504
+ const valuesLists = binding.rows.map((row) => ({
33505
+ List: {
33506
+ items: binding.columns.map((column2, columnIndex) => {
33507
+ parameters.push(row[column2]);
33508
+ const paramRef = createParamRef(nextParam++);
33509
+ const pgType = rowTypes[columnIndex];
33510
+ return pgType === void 0 ? paramRef : runtimeBindingCast(paramRef, pgType);
33511
+ })
33512
+ }
33513
+ }));
33514
+ return {
33515
+ cte: commonTableExpression(
33516
+ cteName,
33517
+ setOperationStatement(
33518
+ "union",
33519
+ true,
33520
+ { SelectStmt: anchor },
33521
+ { SelectStmt: { valuesLists } }
33522
+ ),
33523
+ header
33524
+ ),
33525
+ parameters
33526
+ };
33527
+ }
33528
+ var falseConstant = { A_Const: { boolval: { boolval: false } } };
33529
+ function compileTypedNqlRuntimeBindingCte(name, binding, parameterOffset, cteName, cteColumns, targetSchema) {
33379
33530
  const pgTypes = resolveRuntimeBindingCteColumnTypes(
33380
33531
  name,
33381
33532
  binding,
@@ -33386,39 +33537,34 @@ function compileTypedNqlRuntimeBindingCte(name, binding, parameterOffset, cteNam
33386
33537
  binding,
33387
33538
  parameterOffset,
33388
33539
  cteName,
33389
- columnSql,
33540
+ cteColumns,
33390
33541
  pgTypes
33391
33542
  );
33392
33543
  }
33393
- function compileNqlRuntimeBindingCteWithPgTypes(name, binding, parameterOffset, cteName, columnSql, pgTypes) {
33394
- const anchorColumns = binding.columns.map((column2, columnIndex) => {
33395
- const columnAlias = quoteIdent(column2, "column");
33396
- const pgType = pgTypes[columnIndex];
33397
- return pgType === void 0 ? `NULL AS ${columnAlias}` : `CAST(NULL AS ${pgType}) AS ${columnAlias}`;
33398
- }).join(", ");
33399
- const sourceAnchorSql = `SELECT ${anchorColumns} WHERE false`;
33400
- if (binding.rows.length === 0) {
33401
- return {
33402
- cte: `${cteName} (${columnSql}) as (${sourceAnchorSql})`,
33403
- parameters: []
33404
- };
33405
- }
33406
- assertRuntimeBindingValuesParameterCount(name, binding, parameterOffset);
33407
- const parameters = [];
33408
- let nextParam = parameterOffset + 1;
33409
- const valuesSql = binding.rows.map((row) => {
33410
- const placeholders = binding.columns.map((column2, columnIndex) => {
33411
- parameters.push(row[column2]);
33412
- const paramRef = `$${nextParam++}`;
33544
+ function compileNqlRuntimeBindingCteWithPgTypes(name, binding, parameterOffset, cteName, cteColumns, pgTypes) {
33545
+ const nullConstant = { A_Const: { isnull: true } };
33546
+ const anchor = {
33547
+ targetList: binding.columns.map((column2, columnIndex) => {
33548
+ validateIdentifier(column2, "column");
33413
33549
  const pgType = pgTypes[columnIndex];
33414
- return pgType === void 0 ? paramRef : `${paramRef}::${pgType}`;
33415
- });
33416
- return `(${placeholders.join(", ")})`;
33417
- }).join(", ");
33418
- return {
33419
- cte: `${cteName} (${columnSql}) as (${sourceAnchorSql} UNION ALL VALUES ${valuesSql})`,
33420
- parameters
33550
+ return {
33551
+ ResTarget: {
33552
+ name: column2,
33553
+ val: pgType === void 0 ? nullConstant : runtimeBindingCast(nullConstant, pgType)
33554
+ }
33555
+ };
33556
+ }),
33557
+ whereClause: falseConstant
33421
33558
  };
33559
+ return runtimeBindingCteNode(
33560
+ name,
33561
+ binding,
33562
+ parameterOffset,
33563
+ cteName,
33564
+ cteColumns,
33565
+ anchor,
33566
+ pgTypes
33567
+ );
33422
33568
  }
33423
33569
  function compileNqlRuntimeBindingCte(name, binding, deps, parameterOffset, sourceTable, schemaName, model, returningItems) {
33424
33570
  const sourceBinding2 = sourceTable === void 0 ? void 0 : relationBindingFor(deps.scope, queryLocal(sourceTable));
@@ -33448,21 +33594,22 @@ function compileNqlRuntimeBindingCte(name, binding, deps, parameterOffset, sourc
33448
33594
  `NQL runtime binding '${name}' cannot be materialized without projected columns.`
33449
33595
  );
33450
33596
  }
33451
- const cteName = quoteIdent(emittedBindName(queryLocal(name)), "alias");
33597
+ const cteName = emittedBindName(queryLocal(name));
33598
+ validateIdentifier(cteName, "alias");
33452
33599
  const emittedColumnNames = binding.columns.map(pgReturnedIdentifier2);
33453
33600
  if (new Set(emittedColumnNames).size !== emittedColumnNames.length) {
33454
33601
  throw new Error(
33455
33602
  `NQL runtime binding '${name}' emits duplicate column names after PostgreSQL returned-label truncation.`
33456
33603
  );
33457
33604
  }
33458
- const columnSql = emittedColumnNames.map((column2) => quoteIdent(column2, "column")).join(", ");
33605
+ for (const column2 of emittedColumnNames) validateIdentifier(column2, "column");
33459
33606
  if (binding.columnTypes !== void 0) {
33460
33607
  return compileTypedNqlRuntimeBindingCte(
33461
33608
  name,
33462
33609
  binding,
33463
33610
  parameterOffset,
33464
33611
  cteName,
33465
- columnSql,
33612
+ emittedColumnNames,
33466
33613
  schemaName
33467
33614
  );
33468
33615
  }
@@ -33478,7 +33625,7 @@ function compileNqlRuntimeBindingCte(name, binding, deps, parameterOffset, sourc
33478
33625
  binding,
33479
33626
  parameterOffset,
33480
33627
  cteName,
33481
- columnSql,
33628
+ emittedColumnNames,
33482
33629
  declaredOutputPgTypes
33483
33630
  );
33484
33631
  }
@@ -33487,38 +33634,52 @@ function compileNqlRuntimeBindingCte(name, binding, deps, parameterOffset, sourc
33487
33634
  `NQL runtime binding '${name}' cannot materialize a typed relation because its source table is unavailable.`
33488
33635
  );
33489
33636
  }
33490
- const projectedColumns = binding.columns.map((column2) => quoteIdent(sourcePhysicalColumnFor(column2), "column")).join(", ");
33491
- const sourceAnchorSql = `SELECT ${projectedColumns} FROM ${sourceBinding2 === void 0 && schemaName ? `${quoteIdent(schemaName, "schema")}.` : ""}${quoteIdent(
33492
- sourceBinding2 === void 0 ? identifierText(declaredTable(requireDeclaredNames(deps), sourceTable)) : sourceTable,
33493
- "table"
33494
- )} WHERE false`;
33495
- if (binding.rows.length === 0) {
33496
- return {
33497
- cte: `${cteName} (${columnSql}) as (${sourceAnchorSql})`,
33498
- parameters: []
33499
- };
33637
+ if (sourceBinding2 === void 0 && schemaName) {
33638
+ validateIdentifier(schemaName, "schema");
33500
33639
  }
33501
- assertRuntimeBindingValuesParameterCount(name, binding, parameterOffset);
33502
- const columnTypes = resolveRuntimeBindingColumnTypes(
33640
+ const anchorTable = sourceBinding2 === void 0 ? identifierText(declaredTable(requireDeclaredNames(deps), sourceTable)) : sourceTable;
33641
+ validateIdentifier(anchorTable, "table");
33642
+ const anchor = {
33643
+ targetList: binding.columns.map((column2) => {
33644
+ const sourceColumn = sourcePhysicalColumnFor(column2);
33645
+ validateIdentifier(sourceColumn, "column");
33646
+ return {
33647
+ ResTarget: {
33648
+ val: { ColumnRef: { fields: [stringNode(sourceColumn)] } }
33649
+ }
33650
+ };
33651
+ }),
33652
+ fromClause: [
33653
+ {
33654
+ RangeVar: {
33655
+ ...sourceBinding2 === void 0 && schemaName && { schemaname: schemaName },
33656
+ relname: anchorTable,
33657
+ inh: true,
33658
+ relpersistence: "p"
33659
+ }
33660
+ }
33661
+ ],
33662
+ whereClause: falseConstant
33663
+ };
33664
+ if (binding.rows.length > 0) {
33665
+ assertRuntimeBindingValuesParameterCount(name, binding, parameterOffset);
33666
+ }
33667
+ const columnTypes = binding.rows.length === 0 ? [] : resolveRuntimeBindingColumnTypes(
33503
33668
  name,
33504
33669
  { ...binding, columns: binding.columns.map(sourceColumnFor) },
33505
33670
  model,
33506
33671
  sourceTable,
33507
33672
  schemaName
33508
33673
  );
33509
- const parameters = [];
33510
- let nextParam = parameterOffset + 1;
33511
- const valuesSql = binding.rows.map((row) => {
33512
- const placeholders = binding.columns.map((column2, columnIndex) => {
33513
- parameters.push(row[column2]);
33514
- return `$${nextParam++}::${columnTypes[columnIndex]}`;
33515
- });
33516
- return `(${placeholders.join(", ")})`;
33517
- }).join(", ");
33518
- return {
33519
- cte: `${cteName} (${columnSql}) as (${sourceAnchorSql} UNION ALL VALUES ${valuesSql})`,
33520
- parameters
33521
- };
33674
+ return runtimeBindingCteNode(
33675
+ name,
33676
+ binding,
33677
+ parameterOffset,
33678
+ cteName,
33679
+ emittedColumnNames,
33680
+ anchor,
33681
+ columnTypes
33682
+ );
33522
33683
  }
33523
33684
  function createNqlBindingSelectPlan(query, model, defaultFilters, isLocalSource) {
33524
33685
  const resolution = resolveReportIncludes2(query, [], model, {
@@ -33660,12 +33821,13 @@ function buildNqlBindingProjectionShape(source, select) {
33660
33821
  }
33661
33822
  return { selections, expressions, preserveOneToOne: false };
33662
33823
  }
33663
- function projectNqlBindingQueryEnvelope(source, query, sql, parameters, hydrationPlan) {
33824
+ function projectNqlBindingQueryEnvelope(source, query, sql, parameters, hydrationPlan, ast) {
33664
33825
  const shape = buildNqlBindingProjectionShape(source, query.select);
33665
33826
  if (shape.preserveOneToOne) {
33666
33827
  return preserveOneToOne(source, {
33667
33828
  sql,
33668
33829
  parameters,
33830
+ ...ast !== void 0 ? { ast } : {},
33669
33831
  ...hydrationPlan !== void 0 ? { hydrationPlan } : {},
33670
33832
  preserveHydrationPlan: false
33671
33833
  });
@@ -33673,6 +33835,7 @@ function projectNqlBindingQueryEnvelope(source, query, sql, parameters, hydratio
33673
33835
  return projectNamedFields(source, {
33674
33836
  sql,
33675
33837
  parameters,
33838
+ ...ast !== void 0 ? { ast } : {},
33676
33839
  selections: shape.selections,
33677
33840
  expressions: shape.expressions,
33678
33841
  ...hydrationPlan !== void 0 ? { hydrationPlan } : {},
@@ -34041,7 +34204,8 @@ var PgAdapter = class {
34041
34204
  bundle.query,
34042
34205
  compiled.sql,
34043
34206
  compiled.parameters,
34044
- compiled.hydrationPlan
34207
+ compiled.hydrationPlan,
34208
+ compiled.ast
34045
34209
  ) : compiled;
34046
34210
  }
34047
34211
  if (bundle.cteQuery !== void 0) {
@@ -34144,17 +34308,18 @@ var PgAdapter = class {
34144
34308
  `NQL binding '${name}' has no query intent or runtime rows to materialize.`
34145
34309
  );
34146
34310
  }
34147
- const cteName = quoteIdent(emittedBindName(queryLocal(name)), "alias");
34311
+ const cteName = emittedBindName(queryLocal(name));
34312
+ validateIdentifier(cteName, "alias");
34148
34313
  const bindingBundle = bundle.mutationBindings?.has(name) ? { mutation: bundle.mutationBindings.get(name) } : { query: queryIntent };
34149
- const compiled2 = this.compileNqlBundleLeafEnvelope(
34314
+ const compiled = this.compileNqlBundleLeafEnvelope(
34150
34315
  bindingBundle,
34151
34316
  options,
34152
34317
  new Set(bindingProjections.keys()),
34153
34318
  bindingProjections
34154
34319
  );
34155
- assertRelationalOutput(compiled2.hydrationPlan, "Relational bodies");
34320
+ assertRelationalOutput(compiled.hydrationPlan, "Relational bodies");
34156
34321
  const outputSchema = bundle.bindingOutputSchemas?.get(name);
34157
- const compiledBindingOutputs = compiled2.projection.kind === "known" ? compiled2.projection.outputs : void 0;
34322
+ const compiledBindingOutputs = compiled.projection.kind === "known" ? compiled.projection.outputs : void 0;
34158
34323
  const emittedBindingOutputKeys = outputSchema?.declaredOutputs !== void 0 && compiledBindingOutputs !== void 0 ? new Map(
34159
34324
  outputSchema.columns.map((column2) => {
34160
34325
  const output = compiledBindingOutputs.get(column2) ?? [...compiledBindingOutputs.values()].find(
@@ -34164,21 +34329,27 @@ var PgAdapter = class {
34164
34329
  })
34165
34330
  ) : void 0;
34166
34331
  const bindingProjection = outputSchema?.declaredOutputs !== void 0 ? fromOutputDescriptors({
34167
- sql: compiled2.sql,
34168
- parameters: compiled2.parameters,
34332
+ sql: compiled.sql,
34333
+ parameters: compiled.parameters,
34169
34334
  columns: outputSchema.columns,
34170
34335
  declaredOutputs: outputSchema.declaredOutputs,
34171
34336
  ...emittedBindingOutputKeys !== void 0 && {
34172
34337
  emittedOutputKeys: emittedBindingOutputKeys
34173
34338
  },
34174
- ...compiled2.hydrationPlan !== void 0 && {
34175
- hydrationPlan: compiled2.hydrationPlan
34339
+ ...compiled.hydrationPlan !== void 0 && {
34340
+ hydrationPlan: compiled.hydrationPlan
34176
34341
  }
34177
- }) : compiled2;
34342
+ }) : compiled;
34178
34343
  ctes.push(
34179
- `${cteName} as (${renumberSqlParams2(compiled2.sql, parameters.length)})`
34344
+ commonTableExpression(
34345
+ cteName,
34346
+ shiftParameters(
34347
+ requireStatementAst(compiled, `NQL binding '${name}'`),
34348
+ parameters.length
34349
+ )
34350
+ )
34180
34351
  );
34181
- parameters.push(...compiled2.parameters);
34352
+ parameters.push(...compiled.parameters);
34182
34353
  bindingProjections.set(name, bindingProjection);
34183
34354
  }
34184
34355
  const leafBundle = {
@@ -34197,19 +34368,25 @@ var PgAdapter = class {
34197
34368
  bindingNames,
34198
34369
  bindingProjections
34199
34370
  );
34200
- const compiled = finalizeEnvelope(compiledEnvelope);
34201
34371
  if (ctes.length === 0) {
34202
- return guardCompiledQuery(compiled, "NQL bundle");
34372
+ return guardCompiledQuery(
34373
+ finalizeEnvelope(compiledEnvelope),
34374
+ "NQL bundle"
34375
+ );
34203
34376
  }
34377
+ const ast = withLeadingCtes(
34378
+ shiftParameters(
34379
+ requireStatementAst(compiledEnvelope, "the final NQL statement"),
34380
+ parameters.length
34381
+ ),
34382
+ ctes
34383
+ );
34204
34384
  return guardCompiledQuery(
34205
- preserveOutputKeyMap(
34206
- compiled,
34207
- rebuildCompiledQuery(compiled, {
34208
- sql: prefixNqlBindingCtes(
34209
- ctes,
34210
- renumberSqlParams2(compiled.sql, parameters.length)
34211
- ),
34212
- parameters: [...parameters, ...compiled.parameters]
34385
+ finalizeEnvelope(
34386
+ preserveOneToOne(compiledEnvelope, {
34387
+ sql: deparseQuoted(ast),
34388
+ parameters: [...parameters, ...compiledEnvelope.parameters],
34389
+ ast
34213
34390
  })
34214
34391
  ),
34215
34392
  "NQL bundle"
@@ -34584,7 +34761,7 @@ var PgAdapter = class {
34584
34761
  );
34585
34762
  const queryFromBinding = hasBindingName(bindingNames, query.from);
34586
34763
  const isLocalSource = localSourcePredicate(bindingNames, deps.scope);
34587
- const issuedPlan = getRelationalReadPlan3(query, queryFromBinding);
34764
+ const issuedPlan = getRelationalReadPlan2(query, queryFromBinding);
34588
34765
  const planReport = issuedPlan ?? (queryFromBinding ? createNqlBindingSelectPlan(
34589
34766
  query,
34590
34767
  model,
@@ -34611,7 +34788,8 @@ var PgAdapter = class {
34611
34788
  query,
34612
34789
  compiled.sql,
34613
34790
  compiled.parameters,
34614
- compiled.hydrationPlan
34791
+ compiled.hydrationPlan,
34792
+ compiled.ast
34615
34793
  ) : compiled;
34616
34794
  };
34617
34795
  const envelope = compileSetOperationEnvelope(intent, compileFn);
@@ -59530,8 +59708,6 @@ export {
59530
59708
  generateMigrationSQL2,
59531
59709
  generateDownSQL2,
59532
59710
  introspect,
59533
- compileSetOperation,
59534
- createLeafCompileFn,
59535
59711
  buildDeclareCursor,
59536
59712
  buildFetch,
59537
59713
  buildCloseCursor,
@@ -59681,4 +59857,4 @@ export {
59681
59857
  planPgTransitionRun,
59682
59858
  applyPgTransitionRun
59683
59859
  };
59684
- //# sourceMappingURL=chunk-CQSIDXP5.js.map
59860
+ //# sourceMappingURL=chunk-PCACNA4G.js.map