@dbsp/adapter-pgsql 7.3.0 → 8.0.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));
@@ -22724,7 +22727,12 @@ var PG_RESERVED = /* @__PURE__ */ new Set([
22724
22727
  // Non-reserved but used as output column alias by dbsp compiler
22725
22728
  "exists",
22726
22729
  // SQL standard function keywords that pgsql-deparser quotes in FuncCall context
22727
- "coalesce"
22730
+ "coalesce",
22731
+ // type_func_name keywords: refused as table, CTE and column names
22732
+ "authorization",
22733
+ "binary",
22734
+ "collation",
22735
+ "concurrently"
22728
22736
  ]);
22729
22737
  function quoteIdent2(name) {
22730
22738
  if (/^[a-z_][a-z0-9_]*$/.test(name) && !PG_RESERVED.has(name)) {
@@ -23129,7 +23137,7 @@ function deparseCommonTableExpr(node) {
23129
23137
  const rec = node;
23130
23138
  const cteName = String(rec.ctename ?? "");
23131
23139
  const ctequery = rec.ctequery;
23132
- const cteCols = rec.cte_cols;
23140
+ const cteCols = node.aliascolnames;
23133
23141
  const cycleClause = rec.cycle_clause;
23134
23142
  let result = `${quoteIdent2(cteName)} AS `;
23135
23143
  if (cteCols && cteCols.length > 0) {
@@ -23150,7 +23158,10 @@ function deparseCommonTableExpr(node) {
23150
23158
  return result;
23151
23159
  }
23152
23160
  function deparseWithClause(node) {
23153
- const recursive = node.recursive ? "WITH RECURSIVE " : "WITH ";
23161
+ const anyRecursiveCte = (node.ctes ?? []).some(
23162
+ (cte) => cte.CommonTableExpr?.cterecursive === true
23163
+ );
23164
+ const recursive = node.recursive || anyRecursiveCte ? "WITH RECURSIVE " : "WITH ";
23154
23165
  const ctes = (node.ctes ?? []).map(nodeToStr).join(", ");
23155
23166
  return `${recursive}${ctes}`;
23156
23167
  }
@@ -23169,6 +23180,14 @@ function deparseCTECycleClause(node) {
23169
23180
  }).join(", ");
23170
23181
  return `CYCLE ${cols2} SET ${quoteIdent2(markColumn)} USING ${quoteIdent2(pathColumn)}`;
23171
23182
  }
23183
+ function setOperandNeedsParentheses(node) {
23184
+ const op2 = node.op;
23185
+ 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);
23186
+ }
23187
+ function deparseSetOperand(node) {
23188
+ const sql = deparseSelectStmt(node);
23189
+ return setOperandNeedsParentheses(node) ? `(${sql})` : sql;
23190
+ }
23172
23191
  function deparseSelectStmt(node) {
23173
23192
  const rec = node;
23174
23193
  const op2 = rec.op;
@@ -23176,8 +23195,8 @@ function deparseSelectStmt(node) {
23176
23195
  const larg = rec.larg;
23177
23196
  const rarg = rec.rarg;
23178
23197
  const all = rec.all;
23179
- const left = larg ? deparseSelectStmt(larg) : "";
23180
- const right = rarg ? deparseSelectStmt(rarg) : "";
23198
+ const left = larg ? deparseSetOperand(larg) : "";
23199
+ const right = rarg ? deparseSetOperand(rarg) : "";
23181
23200
  let setOp;
23182
23201
  switch (op2) {
23183
23202
  case "SETOP_UNION":
@@ -23192,7 +23211,9 @@ function deparseSelectStmt(node) {
23192
23211
  default:
23193
23212
  setOp = op2;
23194
23213
  }
23195
- return `${left} ${setOp} ${right}`;
23214
+ const setWith = rec.withClause;
23215
+ const body = `${left} ${setOp} ${right}`;
23216
+ return setWith ? `${deparseWithClause(setWith)} ${body}` : body;
23196
23217
  }
23197
23218
  const valuesLists = rec.valuesLists;
23198
23219
  if (valuesLists && valuesLists.length > 0) {
@@ -23254,7 +23275,7 @@ function deparseSelectStmt(node) {
23254
23275
  return parts.join(" ");
23255
23276
  }
23256
23277
  function deparseInsertStmt(node) {
23257
- const parts = ["INSERT INTO"];
23278
+ const parts = node.withClause ? [deparseWithClause(node.withClause), "INSERT INTO"] : ["INSERT INTO"];
23258
23279
  if (node.relation) {
23259
23280
  parts.push(deparseRangeVar(node.relation));
23260
23281
  }
@@ -23293,7 +23314,7 @@ function deparseInsertStmt(node) {
23293
23314
  return parts.join(" ");
23294
23315
  }
23295
23316
  function deparseUpdateStmt(node) {
23296
- const parts = ["UPDATE"];
23317
+ const parts = node.withClause ? [deparseWithClause(node.withClause), "UPDATE"] : ["UPDATE"];
23297
23318
  if (node.relation) {
23298
23319
  parts.push(deparseRangeVar(node.relation));
23299
23320
  }
@@ -23318,7 +23339,7 @@ function deparseUpdateStmt(node) {
23318
23339
  return parts.join(" ");
23319
23340
  }
23320
23341
  function deparseDeleteStmt(node) {
23321
- const parts = ["DELETE FROM"];
23342
+ const parts = node.withClause ? [deparseWithClause(node.withClause), "DELETE FROM"] : ["DELETE FROM"];
23322
23343
  if (node.relation) {
23323
23344
  parts.push(deparseRangeVar(node.relation));
23324
23345
  }
@@ -27177,7 +27198,7 @@ import {
27177
27198
  // src/pgsql-adapter.ts
27178
27199
  import {
27179
27200
  copyDefaultFilters,
27180
- getRelationalReadPlan as getRelationalReadPlan3,
27201
+ getRelationalReadPlan as getRelationalReadPlan2,
27181
27202
  planInScope as planInScope2,
27182
27203
  resolveReportIncludes as resolveReportIncludes2,
27183
27204
  validateRecursiveSetOperation
@@ -27200,8 +27221,7 @@ import { inspectMutationRows as inspectMutationRows2 } from "@dbsp/core/internal
27200
27221
  import { convertBigintJsReadValue } from "@dbsp/types";
27201
27222
  import {
27202
27223
  assertCompiledQuery,
27203
- projectionlessCompiledQuery,
27204
- rebuildCompiledQuery
27224
+ projectionlessCompiledQuery
27205
27225
  } from "@dbsp/types/adapter-sdk";
27206
27226
  import {
27207
27227
  getNqlBindingRefName as getNqlBindingRefName2,
@@ -27662,14 +27682,10 @@ import { resolveOutputReadHandling as resolveOutputReadHandling4 } from "@dbsp/t
27662
27682
  import { compiledQueryFromProjection } from "@dbsp/types/adapter-sdk";
27663
27683
  var projectionEnvelopeBrand = /* @__PURE__ */ Symbol("projectionEnvelope");
27664
27684
  var projectionOutputMaps = /* @__PURE__ */ new WeakMap();
27685
+ var compiledStatementAsts = /* @__PURE__ */ new WeakMap();
27665
27686
  function outputKeyMapFor(query) {
27666
27687
  return query.outputKeyMap ?? projectionOutputMaps.get(query);
27667
27688
  }
27668
- function preserveOutputKeyMap(prior, next) {
27669
- const map = outputKeyMapFor(prior);
27670
- if (map !== void 0) projectionOutputMaps.set(next, map);
27671
- return next;
27672
- }
27673
27689
  var scalarOneShape = {
27674
27690
  kind: "scalar",
27675
27691
  cardinality: "one"
@@ -27770,9 +27786,11 @@ function fromCompiledQuery(compiled) {
27770
27786
  )
27771
27787
  );
27772
27788
  }
27789
+ const ast = compiledStatementAsts.get(compiled);
27773
27790
  return makeEnvelope({
27774
27791
  sql: compiled.sql,
27775
27792
  parameters: compiled.parameters,
27793
+ ...ast !== void 0 ? { ast } : {},
27776
27794
  projection: { kind: "known", outputs },
27777
27795
  ...compiled.hydrationPlan !== void 0 ? { hydrationPlan: compiled.hydrationPlan } : {}
27778
27796
  });
@@ -27939,6 +27957,7 @@ function projectNamedFields(source, options) {
27939
27957
  return makeEnvelope({
27940
27958
  sql: options.sql,
27941
27959
  parameters: options.parameters,
27960
+ ...options.ast !== void 0 ? { ast: options.ast } : {},
27942
27961
  projection: source.projection,
27943
27962
  ...hydrationPlan2 !== void 0 ? { hydrationPlan: hydrationPlan2 } : {}
27944
27963
  });
@@ -27966,6 +27985,7 @@ function projectNamedFields(source, options) {
27966
27985
  return makeEnvelope({
27967
27986
  sql: options.sql,
27968
27987
  parameters: options.parameters,
27988
+ ...options.ast !== void 0 ? { ast: options.ast } : {},
27969
27989
  projection: { kind: "known", outputs },
27970
27990
  ...hydrationPlan !== void 0 ? { hydrationPlan } : {}
27971
27991
  });
@@ -27987,6 +28007,7 @@ function preserveOneToOne(source, options) {
27987
28007
  return makeEnvelope({
27988
28008
  sql: options.sql,
27989
28009
  parameters: options.parameters,
28010
+ ...options.ast !== void 0 ? { ast: options.ast } : {},
27990
28011
  projection: source.projection,
27991
28012
  ...hydrationPlan !== void 0 ? { hydrationPlan } : {}
27992
28013
  });
@@ -27995,6 +28016,7 @@ function dropPositionalUnion(branches, options) {
27995
28016
  return makeEnvelope({
27996
28017
  sql: options.sql,
27997
28018
  parameters: options.parameters,
28019
+ ...options.ast !== void 0 ? { ast: options.ast } : {},
27998
28020
  projection: {
27999
28021
  kind: "dropped",
28000
28022
  reason: options.reason,
@@ -28033,6 +28055,7 @@ function finalizeEnvelope(env) {
28033
28055
  if (env.projection.outputKeyMap !== void 0) {
28034
28056
  projectionOutputMaps.set(compiled2, env.projection.outputKeyMap);
28035
28057
  }
28058
+ if (env.ast !== void 0) compiledStatementAsts.set(compiled2, env.ast);
28036
28059
  return compiled2;
28037
28060
  }
28038
28061
  const columnMetadata = /* @__PURE__ */ new Map();
@@ -28062,6 +28085,7 @@ function finalizeEnvelope(env) {
28062
28085
  };
28063
28086
  const compiled = compiledQueryFromProjection(fields);
28064
28087
  projectionOutputMaps.set(compiled, outputKeyMap);
28088
+ if (env.ast !== void 0) compiledStatementAsts.set(compiled, env.ast);
28065
28089
  return compiled;
28066
28090
  }
28067
28091
  function buildReturnedOutputKeyMap(outputs) {
@@ -29076,6 +29100,83 @@ function planningNodeAtPath(intent, path) {
29076
29100
  return node;
29077
29101
  }
29078
29102
 
29103
+ // src/statement-ast.ts
29104
+ var statementKinds = [
29105
+ "SelectStmt",
29106
+ "InsertStmt",
29107
+ "UpdateStmt",
29108
+ "DeleteStmt"
29109
+ ];
29110
+ function statementKindOf(node) {
29111
+ const [key] = Object.keys(node);
29112
+ return statementKinds.find((kind) => kind === key);
29113
+ }
29114
+ function requireStatementAst(envelope, context) {
29115
+ const ast = envelope.ast;
29116
+ if (ast === void 0 || statementKindOf(ast) === void 0) {
29117
+ throw new Error(
29118
+ `Cannot compose ${context}: its compiled operand carries no statement tree, and composed SQL is built from trees only (ADR 0012).`
29119
+ );
29120
+ }
29121
+ return ast;
29122
+ }
29123
+ function shiftParameters(ast, offset) {
29124
+ return renumberParamRefsInAst(ast, offset);
29125
+ }
29126
+ function selectStmtOf(ast, context) {
29127
+ const select = ast.SelectStmt;
29128
+ if (select === void 0) {
29129
+ throw new Error(
29130
+ `Cannot compose ${context}: the operand is not a SELECT statement.`
29131
+ );
29132
+ }
29133
+ return select;
29134
+ }
29135
+ var setOperationNodes = {
29136
+ union: "SETOP_UNION",
29137
+ intersect: "SETOP_INTERSECT",
29138
+ except: "SETOP_EXCEPT"
29139
+ };
29140
+ function setOperationStatement(op2, all, left, right) {
29141
+ return {
29142
+ SelectStmt: {
29143
+ op: setOperationNodes[op2],
29144
+ all,
29145
+ larg: selectStmtOf(left, `the left operand of ${op2.toUpperCase()}`),
29146
+ rarg: selectStmtOf(right, `the right operand of ${op2.toUpperCase()}`)
29147
+ }
29148
+ };
29149
+ }
29150
+ function commonTableExpression(name, query, options = {}) {
29151
+ const cte = {
29152
+ ctename: name,
29153
+ ctequery: query,
29154
+ ...options.columns !== void 0 && options.columns.length > 0 && {
29155
+ aliascolnames: options.columns.map((column2) => ({
29156
+ String: { sval: column2 }
29157
+ }))
29158
+ },
29159
+ ...options.recursive === true && { cterecursive: true }
29160
+ };
29161
+ return { CommonTableExpr: cte };
29162
+ }
29163
+ function withLeadingCtes(statement, ctes, recursive = false) {
29164
+ if (ctes.length === 0 && !recursive) return statement;
29165
+ const kind = statementKindOf(statement);
29166
+ if (kind === void 0) {
29167
+ throw new Error(
29168
+ "Cannot attach a WITH clause: the statement is not a SELECT, INSERT, UPDATE or DELETE tree."
29169
+ );
29170
+ }
29171
+ const body = statement[kind];
29172
+ const existing = body.withClause;
29173
+ const withClause = {
29174
+ ctes: [...ctes, ...existing?.ctes ?? []],
29175
+ recursive: recursive || existing?.recursive === true
29176
+ };
29177
+ return { [kind]: { ...body, withClause } };
29178
+ }
29179
+
29079
29180
  // src/adapter-compiler-mutations.ts
29080
29181
  var POSTGRESQL_PARAMETER_LIMIT = 65535;
29081
29182
  var HETEROGENEOUS_INSERT_CELL_LIMIT = 2 * POSTGRESQL_PARAMETER_LIMIT;
@@ -29101,12 +29202,6 @@ function assertParameterLimit(operation, count) {
29101
29202
  function whereIntentAsDecision(where) {
29102
29203
  return where;
29103
29204
  }
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
29205
  function compileSourceQueryCte(operation, sourceName, sourceQuery, options, deps) {
29111
29206
  const model = deps.model;
29112
29207
  if (model === void 0) {
@@ -29117,9 +29212,9 @@ function compileSourceQueryCte(operation, sourceName, sourceQuery, options, deps
29117
29212
  const sourcePlan = planFn(sourceQuery, model, {
29118
29213
  dialectCapabilities: deps.dialectCapabilities ?? POSTGRESQL_CAPABILITIES3
29119
29214
  });
29120
- const source = compileSelect(sourcePlan, options, deps);
29215
+ const source = compileSelectEnvelope(sourcePlan, options, deps);
29121
29216
  return {
29122
- sql: source.sql,
29217
+ ast: requireStatementAst(source, `the source query '${sourceName}'`),
29123
29218
  parameters: source.parameters
29124
29219
  };
29125
29220
  }
@@ -29145,12 +29240,20 @@ function prependSourceCte(query, sourceName, sourceCte) {
29145
29240
  if (sourceCte === void 0) {
29146
29241
  return finalizeEnvelope(query);
29147
29242
  }
29148
- const cteParamCount = sourceCte.parameters.length;
29149
29243
  const sourceCteName = emittedBindName(queryLocal(sourceName));
29244
+ validateIdentifier(sourceCteName, "alias");
29245
+ const ast = withLeadingCtes(
29246
+ shiftParameters(
29247
+ requireStatementAst(query, `the mutation reading '${sourceName}'`),
29248
+ sourceCte.parameters.length
29249
+ ),
29250
+ [commonTableExpression(sourceCteName, sourceCte.ast)]
29251
+ );
29150
29252
  return finalizeEnvelope(
29151
29253
  preserveOneToOne(query, {
29152
- sql: `WITH ${quoteIdent(sourceCteName, "alias")} as (${sourceCte.sql}) ${renumberSqlParams(query.sql, cteParamCount)}`,
29153
- parameters: [...sourceCte.parameters, ...query.parameters]
29254
+ sql: deparseQuoted(ast),
29255
+ parameters: [...sourceCte.parameters, ...query.parameters],
29256
+ ast
29154
29257
  })
29155
29258
  );
29156
29259
  }
@@ -30108,12 +30211,13 @@ function buildCteProjectionShape(source, select) {
30108
30211
  }
30109
30212
  return { selections, expressions, preserveOneToOne: false };
30110
30213
  }
30111
- function projectCteQueryEnvelope(source, query, sql, parameters, hydrationPlan) {
30214
+ function projectCteQueryEnvelope(source, query, sql, parameters, hydrationPlan, ast) {
30112
30215
  const shape = buildCteProjectionShape(source, query.select);
30113
30216
  if (shape.preserveOneToOne) {
30114
30217
  return preserveOneToOne(source, {
30115
30218
  sql,
30116
30219
  parameters,
30220
+ ...ast !== void 0 ? { ast } : {},
30117
30221
  ...hydrationPlan !== void 0 ? { hydrationPlan } : {},
30118
30222
  preserveHydrationPlan: false
30119
30223
  });
@@ -30121,6 +30225,7 @@ function projectCteQueryEnvelope(source, query, sql, parameters, hydrationPlan)
30121
30225
  return projectNamedFields(source, {
30122
30226
  sql,
30123
30227
  parameters,
30228
+ ...ast !== void 0 ? { ast } : {},
30124
30229
  selections: shape.selections,
30125
30230
  expressions: shape.expressions,
30126
30231
  ...hydrationPlan !== void 0 ? { hydrationPlan } : {},
@@ -30140,18 +30245,20 @@ function compileQueryEnvelope(query, options, deps, registry) {
30140
30245
  query,
30141
30246
  compiled.sql,
30142
30247
  compiled.parameters,
30143
- compiled.hydrationPlan
30248
+ compiled.hydrationPlan,
30249
+ compiled.ast
30144
30250
  );
30145
30251
  }
30146
30252
  return compiled;
30147
30253
  }
30148
- function rehomeQueryEnvelope(source, query, compiled, sql, parameters) {
30254
+ function rehomeQueryEnvelope(source, query, compiled, sql, parameters, ast) {
30149
30255
  return projectCteQueryEnvelope(
30150
30256
  source,
30151
30257
  query,
30152
30258
  sql,
30153
30259
  parameters,
30154
- compiled.hydrationPlan
30260
+ compiled.hydrationPlan,
30261
+ ast
30155
30262
  );
30156
30263
  }
30157
30264
  function compileRecursive(report, model, options, deps) {
@@ -30502,9 +30609,14 @@ function compileRecursive(report, model, options, deps) {
30502
30609
  return finalizeEnvelope(env);
30503
30610
  }
30504
30611
  function compileCteQuery(intent, options, deps, initialProjectionByName) {
30612
+ return finalizeEnvelope(
30613
+ compileCteQueryEnvelope(intent, options, deps, initialProjectionByName)
30614
+ );
30615
+ }
30616
+ function compileCteQueryEnvelope(intent, options, deps, initialProjectionByName) {
30505
30617
  const state = createCompilerState();
30506
30618
  const allCteParams = [];
30507
- const cteSqlFragments = [];
30619
+ const cteNodes = [];
30508
30620
  const cteProjectionByName = new Map(
30509
30621
  initialProjectionByName
30510
30622
  );
@@ -30523,12 +30635,11 @@ function compileCteQuery(intent, options, deps, initialProjectionByName) {
30523
30635
  const node = buildUnnestCte(cte, state);
30524
30636
  const cteParams = state.parameters.slice(beforeUnnestParamCount);
30525
30637
  allCteParams.push(...cteParams);
30526
- const cteSql = deparseQuoted(node);
30527
- cteSqlFragments.push(cteSql);
30638
+ cteNodes.push(node);
30528
30639
  cteProjectionByName.set(
30529
30640
  emittedCteName,
30530
30641
  fromOutputDescriptors({
30531
- sql: cteSql,
30642
+ sql: deparseQuoted(node),
30532
30643
  parameters: cteParams,
30533
30644
  columns: [
30534
30645
  ...Object.keys(cte.columns),
@@ -30538,7 +30649,6 @@ function compileCteQuery(intent, options, deps, initialProjectionByName) {
30538
30649
  );
30539
30650
  } else if (cte.kind === "rawCte") {
30540
30651
  isRecursive = true;
30541
- const currentParamOffset = allCteParams.length;
30542
30652
  const rawCteStepDeps = withBindingProjectionScope(
30543
30653
  visibleCteDeps,
30544
30654
  withBindingName(visibleCteDeps.bindingNames, queryLocal(cte.name)),
@@ -30552,20 +30662,9 @@ function compileCteQuery(intent, options, deps, initialProjectionByName) {
30552
30662
  cteProjectionByName
30553
30663
  );
30554
30664
  finalizeEnvelope(rawCte.projection);
30555
- const renumberedRawCteSql = currentParamOffset > 0 ? rawCte.sql.replace(
30556
- /\$([0-9]+)/g,
30557
- (_, n) => `$${parseInt(n, 10) + currentParamOffset}`
30558
- ) : rawCte.sql;
30665
+ cteNodes.push(shiftParameters(rawCte.ast, allCteParams.length));
30559
30666
  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
- );
30667
+ cteProjectionByName.set(emittedCteName, rawCte.bindingProjection);
30569
30668
  } else if (cte.kind === "simpleCte") {
30570
30669
  const innerCte = cte;
30571
30670
  const innerCompiled = compileQueryEnvelope(
@@ -30575,17 +30674,20 @@ function compileCteQuery(intent, options, deps, initialProjectionByName) {
30575
30674
  cteProjectionByName
30576
30675
  );
30577
30676
  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;
30677
+ cteNodes.push(
30678
+ commonTableExpression(
30679
+ emittedCteName,
30680
+ shiftParameters(
30681
+ requireStatementAst(innerCompiled, `CTE '${cte.name}'`),
30682
+ allCteParams.length
30683
+ )
30684
+ )
30685
+ );
30583
30686
  allCteParams.push(...innerCompiled.parameters);
30584
- cteSqlFragments.push(`"${emittedCteName}" AS (${renumberedInnerSql})`);
30585
30687
  cteProjectionByName.set(
30586
30688
  emittedCteName,
30587
30689
  preserveOneToOne(innerCompiled, {
30588
- sql: renumberedInnerSql,
30690
+ sql: innerCompiled.sql,
30589
30691
  parameters: innerCompiled.parameters,
30590
30692
  preserveHydrationPlan: false
30591
30693
  })
@@ -30618,23 +30720,24 @@ function compileCteQuery(intent, options, deps, initialProjectionByName) {
30618
30720
  relationTargetProjections: cteProjectionByName
30619
30721
  }
30620
30722
  );
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;
30723
+ const ast = withLeadingCtes(
30724
+ shiftParameters(
30725
+ requireStatementAst(outerCompiled, "the outer query of a CTE query"),
30726
+ allCteParams.length
30727
+ ),
30728
+ cteNodes,
30729
+ isRecursive
30730
+ );
30731
+ const sql = deparseQuoted(ast);
30629
30732
  const parameters = [...allCteParams, ...outerCompiled.parameters];
30630
- const env = outerRegisteredSource ? projectCteQueryEnvelope(
30733
+ return outerRegisteredSource ? projectCteQueryEnvelope(
30631
30734
  outerRegisteredSource,
30632
30735
  intent.query,
30633
30736
  sql,
30634
30737
  parameters,
30635
- outerCompiled.hydrationPlan
30636
- ) : preserveOneToOne(outerCompiled, { sql, parameters });
30637
- return finalizeEnvelope(env);
30738
+ outerCompiled.hydrationPlan,
30739
+ ast
30740
+ ) : preserveOneToOne(outerCompiled, { sql, parameters, ast });
30638
30741
  }
30639
30742
  function buildUnnestCte(cte, state) {
30640
30743
  const columns = Object.keys(cte.columns);
@@ -30717,39 +30820,52 @@ function buildRawCte(cte, anchorDeps, stepDeps, options, registry) {
30717
30820
  options,
30718
30821
  scopedStepDeps
30719
30822
  );
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;
30823
+ const baseAst = requireStatementAst(
30824
+ baseCompiled,
30825
+ `the base of recursive CTE '${cte.name}'`
30826
+ );
30827
+ const shiftedStepAst = shiftParameters(
30828
+ requireStatementAst(
30829
+ rawStepCompiled,
30830
+ `the step of recursive CTE '${cte.name}'`
30831
+ ),
30832
+ baseCompiled.parameters.length
30833
+ );
30725
30834
  const allParams = [
30726
30835
  ...baseCompiled.parameters,
30727
30836
  ...rawStepCompiled.parameters
30728
30837
  ];
30729
- let finalStepSql = renumberedStepSql;
30838
+ let stepAst = shiftedStepAst;
30730
30839
  if (cte.maxDepth !== void 0) {
30731
- const depthCol = `"${(cte.depthColumn ?? "depth").replace(/"/g, '""')}"`;
30732
- const depthParamIndex = allParams.length + 1;
30733
30840
  allParams.push(cte.maxDepth);
30734
- const hasWhere = /\bWHERE\b/i.test(finalStepSql);
30735
- finalStepSql = hasWhere ? `${finalStepSql} AND ${depthCol} < $${depthParamIndex}` : `${finalStepSql} WHERE ${depthCol} < $${depthParamIndex}`;
30841
+ stepAst = withDepthGuard(
30842
+ shiftedStepAst,
30843
+ cte.depthColumn ?? "depth",
30844
+ allParams.length,
30845
+ cte.name
30846
+ );
30736
30847
  }
30848
+ const stepSql = deparseQuoted(stepAst);
30737
30849
  const stepRegisteredSource = stepQuery.from === cte.name ? baseCompiled : getRegisteredProjection(stepProjectionRegistry, stepQuery.from);
30738
30850
  const stepCompiled = stepRegisteredSource ? rehomeQueryEnvelope(
30739
30851
  stepRegisteredSource,
30740
30852
  stepQuery,
30741
30853
  rawStepCompiled,
30742
- finalStepSql,
30743
- allParams
30854
+ stepSql,
30855
+ allParams,
30856
+ stepAst
30744
30857
  ) : preserveOneToOne(rawStepCompiled, {
30745
- sql: finalStepSql,
30746
- parameters: allParams
30858
+ sql: stepSql,
30859
+ parameters: allParams,
30860
+ ast: stepAst
30747
30861
  });
30748
- const setOp = cte.unionAll ? "UNION ALL" : "UNION";
30749
- const cteName = `"${emittedBindName(queryLocal(cte.name))}"`;
30750
- const cteSql = `${cteName} AS (${baseCompiled.sql} ${setOp} ${finalStepSql})`;
30862
+ const ast = commonTableExpression(
30863
+ emittedBindName(queryLocal(cte.name)),
30864
+ setOperationStatement("union", cte.unionAll === true, baseAst, stepAst)
30865
+ );
30866
+ const cteSql = deparseQuoted(ast);
30751
30867
  return {
30752
- sql: cteSql,
30868
+ ast,
30753
30869
  params: allParams,
30754
30870
  projection: dropPositionalUnion([baseCompiled, stepCompiled], {
30755
30871
  sql: cteSql,
@@ -30765,6 +30881,25 @@ function buildRawCte(cte, anchorDeps, stepDeps, options, registry) {
30765
30881
  })
30766
30882
  };
30767
30883
  }
30884
+ function withDepthGuard(stepAst, depthColumn, paramNumber, cteName) {
30885
+ const step = stepAst.SelectStmt;
30886
+ if (step === void 0 || step.op !== void 0 && step.op !== "SETOP_NONE") {
30887
+ throw new Error(
30888
+ `Cannot add the depth guard of recursive CTE '${cteName}': its step is not a plain SELECT.`
30889
+ );
30890
+ }
30891
+ const guard = binaryExpr(
30892
+ "<",
30893
+ { ColumnRef: { fields: [stringNode(depthColumn)] } },
30894
+ createParamRef(paramNumber)
30895
+ );
30896
+ return {
30897
+ SelectStmt: {
30898
+ ...step,
30899
+ whereClause: step.whereClause !== void 0 ? andExpr(step.whereClause, guard) : guard
30900
+ }
30901
+ };
30902
+ }
30768
30903
 
30769
30904
  // src/ddl/table-operations.ts
30770
30905
  function quoteIdentifier2(name) {
@@ -32128,52 +32263,37 @@ function normalizeMaxPreparedStatements(maxStatements) {
32128
32263
  }
32129
32264
 
32130
32265
  // 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);
32266
+ function compileSetOperationEnvelope(intent, compileLeaf) {
32267
+ const left = compileLeafOrBranch(intent.left, compileLeaf);
32149
32268
  assertRelationalOutput(left.hydrationPlan, "Set operations");
32150
- const right = compileLeafOrBranch(intent.right, compileFn);
32269
+ const right = compileLeafOrBranch(intent.right, compileLeaf);
32151
32270
  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})`;
32271
+ const opName = intent.op.toUpperCase();
32272
+ const ast = setOperationStatement(
32273
+ intent.op,
32274
+ intent.all,
32275
+ requireStatementAst(left, `the left operand of ${opName}`),
32276
+ shiftParameters(
32277
+ requireStatementAst(right, `the right operand of ${opName}`),
32278
+ left.parameters.length
32279
+ )
32280
+ );
32155
32281
  const parameters = [...left.parameters, ...right.parameters];
32156
32282
  return dropPositionalUnion([left, right], {
32157
- sql,
32283
+ sql: deparseQuoted(ast),
32158
32284
  parameters,
32285
+ ast,
32159
32286
  reason: "set-operation-positional-merge"
32160
32287
  });
32161
32288
  }
32162
- function compileLeafOrBranch(intent, compileFn) {
32289
+ function compileLeafOrBranch(intent, compileLeaf) {
32163
32290
  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 })
32291
+ return compileSetOperationEnvelope(
32292
+ intent,
32293
+ compileLeaf
32175
32294
  );
32176
- };
32295
+ }
32296
+ return compileLeaf(intent);
32177
32297
  }
32178
32298
 
32179
32299
  // src/streaming/cursor.ts
@@ -33052,12 +33172,6 @@ function protectedStatementCleanupAction(rawSqlStatement, detail2) {
33052
33172
  function raise(error) {
33053
33173
  throw error;
33054
33174
  }
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
33175
  function pgReturnedIdentifier2(identifier3) {
33062
33176
  let result = "";
33063
33177
  let byteLength = 0;
@@ -33069,16 +33183,6 @@ function pgReturnedIdentifier2(identifier3) {
33069
33183
  }
33070
33184
  return result;
33071
33185
  }
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
33186
  function isCompiledNqlQuery(input) {
33083
33187
  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
33188
  }
@@ -33375,7 +33479,48 @@ function resolveRuntimeBindingCteColumnTypes(name, binding, schemaName) {
33375
33479
  return resolvePgTypeForColumnTypeInfo(name, column2, info, schemaName);
33376
33480
  });
33377
33481
  }
33378
- function compileTypedNqlRuntimeBindingCte(name, binding, parameterOffset, cteName, columnSql, targetSchema) {
33482
+ function runtimeBindingCast(arg, pgType) {
33483
+ return {
33484
+ TypeCast: { arg, typeName: { names: [stringNode(pgType)], typemod: -1 } }
33485
+ };
33486
+ }
33487
+ function runtimeBindingCteNode(name, binding, parameterOffset, cteName, cteColumns, anchor, rowTypes) {
33488
+ const header = { columns: cteColumns };
33489
+ if (binding.rows.length === 0) {
33490
+ return {
33491
+ cte: commonTableExpression(cteName, { SelectStmt: anchor }, header),
33492
+ parameters: []
33493
+ };
33494
+ }
33495
+ assertRuntimeBindingValuesParameterCount(name, binding, parameterOffset);
33496
+ const parameters = [];
33497
+ let nextParam = parameterOffset + 1;
33498
+ const valuesLists = binding.rows.map((row) => ({
33499
+ List: {
33500
+ items: binding.columns.map((column2, columnIndex) => {
33501
+ parameters.push(row[column2]);
33502
+ const paramRef = createParamRef(nextParam++);
33503
+ const pgType = rowTypes[columnIndex];
33504
+ return pgType === void 0 ? paramRef : runtimeBindingCast(paramRef, pgType);
33505
+ })
33506
+ }
33507
+ }));
33508
+ return {
33509
+ cte: commonTableExpression(
33510
+ cteName,
33511
+ setOperationStatement(
33512
+ "union",
33513
+ true,
33514
+ { SelectStmt: anchor },
33515
+ { SelectStmt: { valuesLists } }
33516
+ ),
33517
+ header
33518
+ ),
33519
+ parameters
33520
+ };
33521
+ }
33522
+ var falseConstant = { A_Const: { boolval: { boolval: false } } };
33523
+ function compileTypedNqlRuntimeBindingCte(name, binding, parameterOffset, cteName, cteColumns, targetSchema) {
33379
33524
  const pgTypes = resolveRuntimeBindingCteColumnTypes(
33380
33525
  name,
33381
33526
  binding,
@@ -33386,39 +33531,34 @@ function compileTypedNqlRuntimeBindingCte(name, binding, parameterOffset, cteNam
33386
33531
  binding,
33387
33532
  parameterOffset,
33388
33533
  cteName,
33389
- columnSql,
33534
+ cteColumns,
33390
33535
  pgTypes
33391
33536
  );
33392
33537
  }
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++}`;
33538
+ function compileNqlRuntimeBindingCteWithPgTypes(name, binding, parameterOffset, cteName, cteColumns, pgTypes) {
33539
+ const nullConstant = { A_Const: { isnull: true } };
33540
+ const anchor = {
33541
+ targetList: binding.columns.map((column2, columnIndex) => {
33542
+ validateIdentifier(column2, "column");
33413
33543
  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
33544
+ return {
33545
+ ResTarget: {
33546
+ name: column2,
33547
+ val: pgType === void 0 ? nullConstant : runtimeBindingCast(nullConstant, pgType)
33548
+ }
33549
+ };
33550
+ }),
33551
+ whereClause: falseConstant
33421
33552
  };
33553
+ return runtimeBindingCteNode(
33554
+ name,
33555
+ binding,
33556
+ parameterOffset,
33557
+ cteName,
33558
+ cteColumns,
33559
+ anchor,
33560
+ pgTypes
33561
+ );
33422
33562
  }
33423
33563
  function compileNqlRuntimeBindingCte(name, binding, deps, parameterOffset, sourceTable, schemaName, model, returningItems) {
33424
33564
  const sourceBinding2 = sourceTable === void 0 ? void 0 : relationBindingFor(deps.scope, queryLocal(sourceTable));
@@ -33448,21 +33588,22 @@ function compileNqlRuntimeBindingCte(name, binding, deps, parameterOffset, sourc
33448
33588
  `NQL runtime binding '${name}' cannot be materialized without projected columns.`
33449
33589
  );
33450
33590
  }
33451
- const cteName = quoteIdent(emittedBindName(queryLocal(name)), "alias");
33591
+ const cteName = emittedBindName(queryLocal(name));
33592
+ validateIdentifier(cteName, "alias");
33452
33593
  const emittedColumnNames = binding.columns.map(pgReturnedIdentifier2);
33453
33594
  if (new Set(emittedColumnNames).size !== emittedColumnNames.length) {
33454
33595
  throw new Error(
33455
33596
  `NQL runtime binding '${name}' emits duplicate column names after PostgreSQL returned-label truncation.`
33456
33597
  );
33457
33598
  }
33458
- const columnSql = emittedColumnNames.map((column2) => quoteIdent(column2, "column")).join(", ");
33599
+ for (const column2 of emittedColumnNames) validateIdentifier(column2, "column");
33459
33600
  if (binding.columnTypes !== void 0) {
33460
33601
  return compileTypedNqlRuntimeBindingCte(
33461
33602
  name,
33462
33603
  binding,
33463
33604
  parameterOffset,
33464
33605
  cteName,
33465
- columnSql,
33606
+ emittedColumnNames,
33466
33607
  schemaName
33467
33608
  );
33468
33609
  }
@@ -33478,7 +33619,7 @@ function compileNqlRuntimeBindingCte(name, binding, deps, parameterOffset, sourc
33478
33619
  binding,
33479
33620
  parameterOffset,
33480
33621
  cteName,
33481
- columnSql,
33622
+ emittedColumnNames,
33482
33623
  declaredOutputPgTypes
33483
33624
  );
33484
33625
  }
@@ -33487,38 +33628,52 @@ function compileNqlRuntimeBindingCte(name, binding, deps, parameterOffset, sourc
33487
33628
  `NQL runtime binding '${name}' cannot materialize a typed relation because its source table is unavailable.`
33488
33629
  );
33489
33630
  }
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
- };
33631
+ if (sourceBinding2 === void 0 && schemaName) {
33632
+ validateIdentifier(schemaName, "schema");
33500
33633
  }
33501
- assertRuntimeBindingValuesParameterCount(name, binding, parameterOffset);
33502
- const columnTypes = resolveRuntimeBindingColumnTypes(
33634
+ const anchorTable = sourceBinding2 === void 0 ? identifierText(declaredTable(requireDeclaredNames(deps), sourceTable)) : sourceTable;
33635
+ validateIdentifier(anchorTable, "table");
33636
+ const anchor = {
33637
+ targetList: binding.columns.map((column2) => {
33638
+ const sourceColumn = sourcePhysicalColumnFor(column2);
33639
+ validateIdentifier(sourceColumn, "column");
33640
+ return {
33641
+ ResTarget: {
33642
+ val: { ColumnRef: { fields: [stringNode(sourceColumn)] } }
33643
+ }
33644
+ };
33645
+ }),
33646
+ fromClause: [
33647
+ {
33648
+ RangeVar: {
33649
+ ...sourceBinding2 === void 0 && schemaName && { schemaname: schemaName },
33650
+ relname: anchorTable,
33651
+ inh: true,
33652
+ relpersistence: "p"
33653
+ }
33654
+ }
33655
+ ],
33656
+ whereClause: falseConstant
33657
+ };
33658
+ if (binding.rows.length > 0) {
33659
+ assertRuntimeBindingValuesParameterCount(name, binding, parameterOffset);
33660
+ }
33661
+ const columnTypes = binding.rows.length === 0 ? [] : resolveRuntimeBindingColumnTypes(
33503
33662
  name,
33504
33663
  { ...binding, columns: binding.columns.map(sourceColumnFor) },
33505
33664
  model,
33506
33665
  sourceTable,
33507
33666
  schemaName
33508
33667
  );
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
- };
33668
+ return runtimeBindingCteNode(
33669
+ name,
33670
+ binding,
33671
+ parameterOffset,
33672
+ cteName,
33673
+ emittedColumnNames,
33674
+ anchor,
33675
+ columnTypes
33676
+ );
33522
33677
  }
33523
33678
  function createNqlBindingSelectPlan(query, model, defaultFilters, isLocalSource) {
33524
33679
  const resolution = resolveReportIncludes2(query, [], model, {
@@ -33660,12 +33815,13 @@ function buildNqlBindingProjectionShape(source, select) {
33660
33815
  }
33661
33816
  return { selections, expressions, preserveOneToOne: false };
33662
33817
  }
33663
- function projectNqlBindingQueryEnvelope(source, query, sql, parameters, hydrationPlan) {
33818
+ function projectNqlBindingQueryEnvelope(source, query, sql, parameters, hydrationPlan, ast) {
33664
33819
  const shape = buildNqlBindingProjectionShape(source, query.select);
33665
33820
  if (shape.preserveOneToOne) {
33666
33821
  return preserveOneToOne(source, {
33667
33822
  sql,
33668
33823
  parameters,
33824
+ ...ast !== void 0 ? { ast } : {},
33669
33825
  ...hydrationPlan !== void 0 ? { hydrationPlan } : {},
33670
33826
  preserveHydrationPlan: false
33671
33827
  });
@@ -33673,6 +33829,7 @@ function projectNqlBindingQueryEnvelope(source, query, sql, parameters, hydratio
33673
33829
  return projectNamedFields(source, {
33674
33830
  sql,
33675
33831
  parameters,
33832
+ ...ast !== void 0 ? { ast } : {},
33676
33833
  selections: shape.selections,
33677
33834
  expressions: shape.expressions,
33678
33835
  ...hydrationPlan !== void 0 ? { hydrationPlan } : {},
@@ -34041,7 +34198,8 @@ var PgAdapter = class {
34041
34198
  bundle.query,
34042
34199
  compiled.sql,
34043
34200
  compiled.parameters,
34044
- compiled.hydrationPlan
34201
+ compiled.hydrationPlan,
34202
+ compiled.ast
34045
34203
  ) : compiled;
34046
34204
  }
34047
34205
  if (bundle.cteQuery !== void 0) {
@@ -34144,17 +34302,18 @@ var PgAdapter = class {
34144
34302
  `NQL binding '${name}' has no query intent or runtime rows to materialize.`
34145
34303
  );
34146
34304
  }
34147
- const cteName = quoteIdent(emittedBindName(queryLocal(name)), "alias");
34305
+ const cteName = emittedBindName(queryLocal(name));
34306
+ validateIdentifier(cteName, "alias");
34148
34307
  const bindingBundle = bundle.mutationBindings?.has(name) ? { mutation: bundle.mutationBindings.get(name) } : { query: queryIntent };
34149
- const compiled2 = this.compileNqlBundleLeafEnvelope(
34308
+ const compiled = this.compileNqlBundleLeafEnvelope(
34150
34309
  bindingBundle,
34151
34310
  options,
34152
34311
  new Set(bindingProjections.keys()),
34153
34312
  bindingProjections
34154
34313
  );
34155
- assertRelationalOutput(compiled2.hydrationPlan, "Relational bodies");
34314
+ assertRelationalOutput(compiled.hydrationPlan, "Relational bodies");
34156
34315
  const outputSchema = bundle.bindingOutputSchemas?.get(name);
34157
- const compiledBindingOutputs = compiled2.projection.kind === "known" ? compiled2.projection.outputs : void 0;
34316
+ const compiledBindingOutputs = compiled.projection.kind === "known" ? compiled.projection.outputs : void 0;
34158
34317
  const emittedBindingOutputKeys = outputSchema?.declaredOutputs !== void 0 && compiledBindingOutputs !== void 0 ? new Map(
34159
34318
  outputSchema.columns.map((column2) => {
34160
34319
  const output = compiledBindingOutputs.get(column2) ?? [...compiledBindingOutputs.values()].find(
@@ -34164,21 +34323,27 @@ var PgAdapter = class {
34164
34323
  })
34165
34324
  ) : void 0;
34166
34325
  const bindingProjection = outputSchema?.declaredOutputs !== void 0 ? fromOutputDescriptors({
34167
- sql: compiled2.sql,
34168
- parameters: compiled2.parameters,
34326
+ sql: compiled.sql,
34327
+ parameters: compiled.parameters,
34169
34328
  columns: outputSchema.columns,
34170
34329
  declaredOutputs: outputSchema.declaredOutputs,
34171
34330
  ...emittedBindingOutputKeys !== void 0 && {
34172
34331
  emittedOutputKeys: emittedBindingOutputKeys
34173
34332
  },
34174
- ...compiled2.hydrationPlan !== void 0 && {
34175
- hydrationPlan: compiled2.hydrationPlan
34333
+ ...compiled.hydrationPlan !== void 0 && {
34334
+ hydrationPlan: compiled.hydrationPlan
34176
34335
  }
34177
- }) : compiled2;
34336
+ }) : compiled;
34178
34337
  ctes.push(
34179
- `${cteName} as (${renumberSqlParams2(compiled2.sql, parameters.length)})`
34338
+ commonTableExpression(
34339
+ cteName,
34340
+ shiftParameters(
34341
+ requireStatementAst(compiled, `NQL binding '${name}'`),
34342
+ parameters.length
34343
+ )
34344
+ )
34180
34345
  );
34181
- parameters.push(...compiled2.parameters);
34346
+ parameters.push(...compiled.parameters);
34182
34347
  bindingProjections.set(name, bindingProjection);
34183
34348
  }
34184
34349
  const leafBundle = {
@@ -34197,19 +34362,25 @@ var PgAdapter = class {
34197
34362
  bindingNames,
34198
34363
  bindingProjections
34199
34364
  );
34200
- const compiled = finalizeEnvelope(compiledEnvelope);
34201
34365
  if (ctes.length === 0) {
34202
- return guardCompiledQuery(compiled, "NQL bundle");
34366
+ return guardCompiledQuery(
34367
+ finalizeEnvelope(compiledEnvelope),
34368
+ "NQL bundle"
34369
+ );
34203
34370
  }
34371
+ const ast = withLeadingCtes(
34372
+ shiftParameters(
34373
+ requireStatementAst(compiledEnvelope, "the final NQL statement"),
34374
+ parameters.length
34375
+ ),
34376
+ ctes
34377
+ );
34204
34378
  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]
34379
+ finalizeEnvelope(
34380
+ preserveOneToOne(compiledEnvelope, {
34381
+ sql: deparseQuoted(ast),
34382
+ parameters: [...parameters, ...compiledEnvelope.parameters],
34383
+ ast
34213
34384
  })
34214
34385
  ),
34215
34386
  "NQL bundle"
@@ -34584,7 +34755,7 @@ var PgAdapter = class {
34584
34755
  );
34585
34756
  const queryFromBinding = hasBindingName(bindingNames, query.from);
34586
34757
  const isLocalSource = localSourcePredicate(bindingNames, deps.scope);
34587
- const issuedPlan = getRelationalReadPlan3(query, queryFromBinding);
34758
+ const issuedPlan = getRelationalReadPlan2(query, queryFromBinding);
34588
34759
  const planReport = issuedPlan ?? (queryFromBinding ? createNqlBindingSelectPlan(
34589
34760
  query,
34590
34761
  model,
@@ -34611,7 +34782,8 @@ var PgAdapter = class {
34611
34782
  query,
34612
34783
  compiled.sql,
34613
34784
  compiled.parameters,
34614
- compiled.hydrationPlan
34785
+ compiled.hydrationPlan,
34786
+ compiled.ast
34615
34787
  ) : compiled;
34616
34788
  };
34617
34789
  const envelope = compileSetOperationEnvelope(intent, compileFn);
@@ -59530,8 +59702,6 @@ export {
59530
59702
  generateMigrationSQL2,
59531
59703
  generateDownSQL2,
59532
59704
  introspect,
59533
- compileSetOperation,
59534
- createLeafCompileFn,
59535
59705
  buildDeclareCursor,
59536
59706
  buildFetch,
59537
59707
  buildCloseCursor,
@@ -59681,4 +59851,4 @@ export {
59681
59851
  planPgTransitionRun,
59682
59852
  applyPgTransitionRun
59683
59853
  };
59684
- //# sourceMappingURL=chunk-CQSIDXP5.js.map
59854
+ //# sourceMappingURL=chunk-GTX6FAK2.js.map