@dbsp/adapter-pgsql 7.2.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.
@@ -12019,6 +12019,29 @@ function collectAndValidateParamRefs(node) {
12019
12019
  return { paramRefs, validationResults, allValid };
12020
12020
  }
12021
12021
 
12022
+ // src/param-renumber.ts
12023
+ function renumberParamRefsInAst(node, offset) {
12024
+ if (offset === 0) return node;
12025
+ return renumberNode(node, offset);
12026
+ }
12027
+ function renumberNode(value, offset) {
12028
+ if (value === null || value === void 0) return value;
12029
+ if (Array.isArray(value)) {
12030
+ return value.map((item) => renumberNode(item, offset));
12031
+ }
12032
+ if (typeof value !== "object") return value;
12033
+ const obj = value;
12034
+ if ("ParamRef" in obj && obj.ParamRef !== null && typeof obj.ParamRef === "object") {
12035
+ const pr = obj.ParamRef;
12036
+ return { ParamRef: { ...pr, number: pr.number + offset } };
12037
+ }
12038
+ const result = {};
12039
+ for (const key of Object.keys(obj)) {
12040
+ result[key] = renumberNode(obj[key], offset);
12041
+ }
12042
+ return result;
12043
+ }
12044
+
12022
12045
  // src/resolved-condition-compiler.ts
12023
12046
  import { escapeDiagnosticText as escapeDiagnosticText2, validateTypeName as validateTypeName2 } from "@dbsp/core/internal";
12024
12047
 
@@ -12087,6 +12110,13 @@ function hasBindingName(scope, name) {
12087
12110
  const binding = scope?.bindings.get(name);
12088
12111
  return binding?.kind === "cte-bind";
12089
12112
  }
12113
+ function localSourcePredicate(bindingNames, scope) {
12114
+ return (name) => {
12115
+ const local = queryLocal(name);
12116
+ const binding = relationBindingFor(scope, local);
12117
+ return hasBindingName(bindingNames, local) || binding?.kind === "cte-bind" || binding?.kind === "batch-values";
12118
+ };
12119
+ }
12090
12120
  function schemaForFromName(schemaName, fromName, scope) {
12091
12121
  return hasBindingName(scope, fromName) ? void 0 : schemaName;
12092
12122
  }
@@ -12860,6 +12890,9 @@ function resolveCaseValue(value, alias, _schema, resolveColumn, state, nestedCas
12860
12890
  if (typeof expr.value === "number") {
12861
12891
  return numericLiteralNode(expr.value);
12862
12892
  }
12893
+ if (typeof expr.value === "string") {
12894
+ return stringConstNode(expr.value);
12895
+ }
12863
12896
  return bindParameter(expr.value, state);
12864
12897
  case "column":
12865
12898
  return resolveColumn?.(expr.column) ?? sqlColumnRef(queryLocal(expr.column), queryLocal(alias));
@@ -14133,7 +14166,7 @@ function validateOperators(input) {
14133
14166
  }
14134
14167
  }
14135
14168
  function address(operand, ctx, correlationRelation) {
14136
- const alias = operand.range.table === ctx.rootTable && operand.range.alias === ctx.rootTable ? ctx.currentAlias ?? operand.range.alias : operand.range.alias;
14169
+ const alias = operand.kind === "outerRef" && ctx.enclosingQualifiers !== void 0 ? ctx.enclosingQualifiers.get(operand.range.alias) ?? operand.range.alias : operand.range.table === ctx.rootTable && operand.range.alias === ctx.rootTable ? ctx.currentAlias ?? operand.range.alias : operand.range.alias;
14137
14170
  return resolveAddressedColumn(
14138
14171
  { ...operand, range: { ...operand.range, alias } },
14139
14172
  ctx,
@@ -14262,6 +14295,17 @@ function compileResolvedSubqueryBodyUnchecked(body, ctx, state) {
14262
14295
  }
14263
14296
  return { SelectStmt: stmt };
14264
14297
  }
14298
+ function nestedSelect(select, ctx, state) {
14299
+ if (!ctx.compileNestedSelect)
14300
+ throw new Error(
14301
+ "An expression subquery reached the adapter without its nested select."
14302
+ );
14303
+ const compiled = ctx.compileNestedSelect(select, ctx);
14304
+ const ast = renumberParamRefsInAst(compiled.ast, state.paramIndex);
14305
+ state.parameters.push(...compiled.parameters);
14306
+ state.paramIndex += compiled.parameters.length;
14307
+ return ast;
14308
+ }
14265
14309
  function compileResolvedExpressionUnchecked(expr, ctx, state) {
14266
14310
  const compile = (e) => compileResolvedExpressionUnchecked(e, ctx, state);
14267
14311
  switch (expr.kind) {
@@ -14323,11 +14367,7 @@ function compileResolvedExpressionUnchecked(expr, ctx, state) {
14323
14367
  return {
14324
14368
  SubLink: {
14325
14369
  subLinkType: "EXPR_SUBLINK",
14326
- subselect: compileResolvedSubqueryBodyUnchecked(
14327
- expr.body,
14328
- ctx,
14329
- state
14330
- )
14370
+ subselect: "select" in expr ? nestedSelect(expr.select, ctx, state) : compileResolvedSubqueryBodyUnchecked(expr.body, ctx, state)
14331
14371
  }
14332
14372
  };
14333
14373
  case "operator": {
@@ -14653,10 +14693,6 @@ function compileResolvedCondition(tree, ctx, state) {
14653
14693
  validateOperators(tree);
14654
14694
  return compileResolvedConditionUnchecked(tree, ctx, state);
14655
14695
  }
14656
- function compileResolvedSubqueryBody(body, ctx, state) {
14657
- validateOperators(body);
14658
- return compileResolvedSubqueryBodyUnchecked(body, ctx, state);
14659
- }
14660
14696
 
14661
14697
  // src/compiler.ts
14662
14698
  import { InvalidOperationError as InvalidOperationError2 } from "@dbsp/core";
@@ -16398,6 +16434,15 @@ function buildCustomFnFilter(filterIntent, ctx, state, conditionCompiler) {
16398
16434
  deriveFkColumnName: ctx.deriveFkColumnName
16399
16435
  },
16400
16436
  compileExpressionSubquery: ctx.compileSubquery,
16437
+ ...ctx.compileNestedSelect !== void 0 && {
16438
+ compileNestedSelect: ctx.compileNestedSelect
16439
+ },
16440
+ ...ctx.enclosingQualifiers !== void 0 && {
16441
+ enclosingQualifiers: ctx.enclosingQualifiers
16442
+ },
16443
+ ...ctx.rootRangeAlias !== void 0 && {
16444
+ rootRangeAlias: ctx.rootRangeAlias
16445
+ },
16401
16446
  paramState: state,
16402
16447
  ...ctx.model !== void 0 && { model: ctx.model },
16403
16448
  ...ctx.declaredNames !== void 0 && {
@@ -17385,6 +17430,15 @@ function createConditionCompiler(createWhereDispatcher2, buildCustomFnFilter3) {
17385
17430
  defaultPkColumnName: ctx.defaultPkColumnName,
17386
17431
  deriveFkColumnName: ctx.deriveFkColumnName,
17387
17432
  compileSubquery: ctx.compileExpressionSubquery,
17433
+ ...ctx.compileNestedSelect !== void 0 && {
17434
+ compileNestedSelect: ctx.compileNestedSelect
17435
+ },
17436
+ ...ctx.enclosingQualifiers !== void 0 && {
17437
+ enclosingQualifiers: ctx.enclosingQualifiers
17438
+ },
17439
+ ...ctx.rootRangeAlias !== void 0 && {
17440
+ rootRangeAlias: ctx.rootRangeAlias
17441
+ },
17388
17442
  ...ctx.resolvedConditions && {
17389
17443
  resolvedConditions: ctx.resolvedConditions
17390
17444
  },
@@ -22673,7 +22727,12 @@ var PG_RESERVED = /* @__PURE__ */ new Set([
22673
22727
  // Non-reserved but used as output column alias by dbsp compiler
22674
22728
  "exists",
22675
22729
  // SQL standard function keywords that pgsql-deparser quotes in FuncCall context
22676
- "coalesce"
22730
+ "coalesce",
22731
+ // type_func_name keywords: refused as table, CTE and column names
22732
+ "authorization",
22733
+ "binary",
22734
+ "collation",
22735
+ "concurrently"
22677
22736
  ]);
22678
22737
  function quoteIdent2(name) {
22679
22738
  if (/^[a-z_][a-z0-9_]*$/.test(name) && !PG_RESERVED.has(name)) {
@@ -23078,7 +23137,7 @@ function deparseCommonTableExpr(node) {
23078
23137
  const rec = node;
23079
23138
  const cteName = String(rec.ctename ?? "");
23080
23139
  const ctequery = rec.ctequery;
23081
- const cteCols = rec.cte_cols;
23140
+ const cteCols = node.aliascolnames;
23082
23141
  const cycleClause = rec.cycle_clause;
23083
23142
  let result = `${quoteIdent2(cteName)} AS `;
23084
23143
  if (cteCols && cteCols.length > 0) {
@@ -23099,7 +23158,10 @@ function deparseCommonTableExpr(node) {
23099
23158
  return result;
23100
23159
  }
23101
23160
  function deparseWithClause(node) {
23102
- 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 ";
23103
23165
  const ctes = (node.ctes ?? []).map(nodeToStr).join(", ");
23104
23166
  return `${recursive}${ctes}`;
23105
23167
  }
@@ -23118,6 +23180,14 @@ function deparseCTECycleClause(node) {
23118
23180
  }).join(", ");
23119
23181
  return `CYCLE ${cols2} SET ${quoteIdent2(markColumn)} USING ${quoteIdent2(pathColumn)}`;
23120
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
+ }
23121
23191
  function deparseSelectStmt(node) {
23122
23192
  const rec = node;
23123
23193
  const op2 = rec.op;
@@ -23125,8 +23195,8 @@ function deparseSelectStmt(node) {
23125
23195
  const larg = rec.larg;
23126
23196
  const rarg = rec.rarg;
23127
23197
  const all = rec.all;
23128
- const left = larg ? deparseSelectStmt(larg) : "";
23129
- const right = rarg ? deparseSelectStmt(rarg) : "";
23198
+ const left = larg ? deparseSetOperand(larg) : "";
23199
+ const right = rarg ? deparseSetOperand(rarg) : "";
23130
23200
  let setOp;
23131
23201
  switch (op2) {
23132
23202
  case "SETOP_UNION":
@@ -23141,7 +23211,9 @@ function deparseSelectStmt(node) {
23141
23211
  default:
23142
23212
  setOp = op2;
23143
23213
  }
23144
- return `${left} ${setOp} ${right}`;
23214
+ const setWith = rec.withClause;
23215
+ const body = `${left} ${setOp} ${right}`;
23216
+ return setWith ? `${deparseWithClause(setWith)} ${body}` : body;
23145
23217
  }
23146
23218
  const valuesLists = rec.valuesLists;
23147
23219
  if (valuesLists && valuesLists.length > 0) {
@@ -23203,7 +23275,7 @@ function deparseSelectStmt(node) {
23203
23275
  return parts.join(" ");
23204
23276
  }
23205
23277
  function deparseInsertStmt(node) {
23206
- const parts = ["INSERT INTO"];
23278
+ const parts = node.withClause ? [deparseWithClause(node.withClause), "INSERT INTO"] : ["INSERT INTO"];
23207
23279
  if (node.relation) {
23208
23280
  parts.push(deparseRangeVar(node.relation));
23209
23281
  }
@@ -23242,7 +23314,7 @@ function deparseInsertStmt(node) {
23242
23314
  return parts.join(" ");
23243
23315
  }
23244
23316
  function deparseUpdateStmt(node) {
23245
- const parts = ["UPDATE"];
23317
+ const parts = node.withClause ? [deparseWithClause(node.withClause), "UPDATE"] : ["UPDATE"];
23246
23318
  if (node.relation) {
23247
23319
  parts.push(deparseRangeVar(node.relation));
23248
23320
  }
@@ -23267,7 +23339,7 @@ function deparseUpdateStmt(node) {
23267
23339
  return parts.join(" ");
23268
23340
  }
23269
23341
  function deparseDeleteStmt(node) {
23270
- const parts = ["DELETE FROM"];
23342
+ const parts = node.withClause ? [deparseWithClause(node.withClause), "DELETE FROM"] : ["DELETE FROM"];
23271
23343
  if (node.relation) {
23272
23344
  parts.push(deparseRangeVar(node.relation));
23273
23345
  }
@@ -23655,27 +23727,6 @@ function mergeDuplicateJoinIncludeDecisions(decisions, rootTable) {
23655
23727
  }
23656
23728
  return merged;
23657
23729
  }
23658
- function renumberParamRefsInAst(node, offset) {
23659
- if (offset === 0) return node;
23660
- return renumberNode(node, offset);
23661
- }
23662
- function renumberNode(value, offset) {
23663
- if (value === null || value === void 0) return value;
23664
- if (Array.isArray(value)) {
23665
- return value.map((item) => renumberNode(item, offset));
23666
- }
23667
- if (typeof value !== "object") return value;
23668
- const obj = value;
23669
- if ("ParamRef" in obj && obj.ParamRef !== null && typeof obj.ParamRef === "object") {
23670
- const pr = obj.ParamRef;
23671
- return { ParamRef: { ...pr, number: pr.number + offset } };
23672
- }
23673
- const result = {};
23674
- for (const key of Object.keys(obj)) {
23675
- result[key] = renumberNode(obj[key], offset);
23676
- }
23677
- return result;
23678
- }
23679
23730
  function maxParamRefNumber(value) {
23680
23731
  if (value === null || typeof value !== "object") return 0;
23681
23732
  if (Array.isArray(value)) {
@@ -23705,6 +23756,8 @@ var PlanCompiler = class _PlanCompiler {
23705
23756
  bindingNames;
23706
23757
  scope;
23707
23758
  relationTargetProjections;
23759
+ nestedSelectCompiler;
23760
+ localSubtree;
23708
23761
  /** Mutable state shared with extracted condition/value compilation functions */
23709
23762
  state = {
23710
23763
  parameters: [],
@@ -23715,6 +23768,8 @@ var PlanCompiler = class _PlanCompiler {
23715
23768
  };
23716
23769
  /** Track root table for EXISTS FK correlation */
23717
23770
  currentRootTable = "";
23771
+ /** The emitted alias of the root range when it differs from its table (a nested body). */
23772
+ currentRootAlias;
23718
23773
  /** Pending JOINs registered by filter/include strategies (flushed in compileSelect) */
23719
23774
  pendingJoins = [];
23720
23775
  /** Raw JOIN AST nodes from include handlers (e.g., LATERAL) */
@@ -23762,6 +23817,8 @@ var PlanCompiler = class _PlanCompiler {
23762
23817
  this.bindingNames = options.bindingNames;
23763
23818
  this.scope = options.scope;
23764
23819
  this.relationTargetProjections = options.relationTargetProjections;
23820
+ this.nestedSelectCompiler = options.compileNestedSelect;
23821
+ this.localSubtree = options.localSubtree === true;
23765
23822
  }
23766
23823
  childCompilerOptions(overrides = {}) {
23767
23824
  return {
@@ -23785,6 +23842,10 @@ var PlanCompiler = class _PlanCompiler {
23785
23842
  ...this.relationTargetProjections !== void 0 && {
23786
23843
  relationTargetProjections: this.relationTargetProjections
23787
23844
  },
23845
+ ...this.nestedSelectCompiler !== void 0 && {
23846
+ compileNestedSelect: this.nestedSelectCompiler
23847
+ },
23848
+ ...this.localSubtree && { localSubtree: true },
23788
23849
  ...overrides
23789
23850
  };
23790
23851
  }
@@ -23799,7 +23860,7 @@ var PlanCompiler = class _PlanCompiler {
23799
23860
  if (this.currentRootTable.length > 0 && relationBindingFor(this.scope, queryLocal(this.currentRootTable)) === void 0 && declaredRelationBindingFor(this.scope, this.currentRootTable) === void 0) {
23800
23861
  bindings.push(
23801
23862
  relationBinding({
23802
- qualifier: this.tableIdentifier(this.currentRootTable),
23863
+ qualifier: this.currentRootAlias !== void 0 ? queryLocal(this.currentRootAlias) : this.tableIdentifier(this.currentRootTable),
23803
23864
  kind: "declared-table",
23804
23865
  logicalTable: this.currentRootTable
23805
23866
  })
@@ -24141,6 +24202,7 @@ var PlanCompiler = class _PlanCompiler {
24141
24202
  joins: []
24142
24203
  };
24143
24204
  this.currentRootTable = plan.rootTable;
24205
+ this.currentRootAlias = plan.rootAlias;
24144
24206
  this.pendingJoins = [];
24145
24207
  this.rawJoins = [];
24146
24208
  this.keylessJoinProjections.clear();
@@ -24247,6 +24309,10 @@ var PlanCompiler = class _PlanCompiler {
24247
24309
  outerAlias: identifierText(plan.enclosingRanges[0][0].qualifier)
24248
24310
  }
24249
24311
  },
24312
+ ...plan.enclosingQualifiers && {
24313
+ enclosingQualifiers: plan.enclosingQualifiers
24314
+ },
24315
+ ...plan.rootAlias && { rootRangeAlias: plan.rootAlias },
24250
24316
  ...plan.resolvedExecution && { resolvedExecution: true },
24251
24317
  ...plan.directConditions && {
24252
24318
  compileCaseCondition: (intent, ctx, state) => this.compilePositionCondition(intent, plan, ctx, state, "case-when")
@@ -24280,6 +24346,9 @@ var PlanCompiler = class _PlanCompiler {
24280
24346
  ])
24281
24347
  )
24282
24348
  },
24349
+ ...this.nestedSelectCompiler !== void 0 && {
24350
+ compileNestedSelect: this.nestedSelectCompiler
24351
+ },
24283
24352
  compileSubquery: (query, paramOffset, parent, expression) => this.compileExpressionSubquery(
24284
24353
  query,
24285
24354
  paramOffset,
@@ -24305,6 +24374,10 @@ var PlanCompiler = class _PlanCompiler {
24305
24374
  schemaForRangeVar(plan, table2) {
24306
24375
  return hasBindingName(this.scope ?? this.bindingNames, queryLocal(table2)) ? void 0 : plan.schema ?? this.schema;
24307
24376
  }
24377
+ /** A FROM name bound in this query to a local source (an NQL binding, a CTE or a BatchValues range). */
24378
+ isQueryLocalSource(name) {
24379
+ return localSourcePredicate(this.bindingNames, this.scope)(name);
24380
+ }
24308
24381
  isNqlBindingRoot(plan) {
24309
24382
  return hasBindingName(
24310
24383
  this.scope ?? this.bindingNames,
@@ -24695,16 +24768,21 @@ var PlanCompiler = class _PlanCompiler {
24695
24768
  (entry2) => expression !== void 0 && entry2.expression === expression
24696
24769
  );
24697
24770
  if (resolved) {
24698
- const state = this.createHandlerState();
24699
- state.parameters = [];
24700
- state.paramIndex = paramOffset;
24701
- const ast = compileResolvedSubqueryBody(
24702
- resolved.body,
24703
- parentContext ?? this.createHandlerContext(parentPlan),
24704
- state
24705
- );
24706
- return { ast, parameters: state.parameters };
24771
+ const parent2 = parentContext ?? this.createHandlerContext(parentPlan);
24772
+ if (!this.nestedSelectCompiler)
24773
+ throw new Error(
24774
+ "An expression subquery reached the adapter without its nested select."
24775
+ );
24776
+ const compiled = this.nestedSelectCompiler(resolved.select, parent2);
24777
+ return {
24778
+ ast: renumberParamRefsInAst(compiled.ast, paramOffset),
24779
+ parameters: compiled.parameters
24780
+ };
24707
24781
  }
24782
+ if (this.model !== void 0 && parentPlan.directConditions && !this.localSubtree && !this.isQueryLocalSource(query.from))
24783
+ throw new Error(
24784
+ "An expression subquery reached the adapter without its nested select."
24785
+ );
24708
24786
  if (!parentPlan.directConditions) {
24709
24787
  assertNoSelectExpressionCorrelation(query);
24710
24788
  const innerCompiler2 = new _PlanCompiler(this.childCompilerOptions());
@@ -24730,7 +24808,9 @@ var PlanCompiler = class _PlanCompiler {
24730
24808
  const suffix = i === 0 ? "_sq" : `_sq_${i}`;
24731
24809
  rootAlias = `${truncateIdentifier2(query.from, 63 - suffix.length)}${suffix}`;
24732
24810
  }
24733
- const innerCompiler = new _PlanCompiler(this.childCompilerOptions());
24811
+ const innerCompiler = new _PlanCompiler(
24812
+ this.childCompilerOptions({ localSubtree: true })
24813
+ );
24734
24814
  const innerPlan = {
24735
24815
  rootTable: query.from,
24736
24816
  decisions: intentToDecisions(query, query.from, {
@@ -25515,12 +25595,13 @@ var PlanCompiler = class _PlanCompiler {
25515
25595
  */
25516
25596
  compileRelationAwareColumnRef(column2, table2) {
25517
25597
  const dot = column2.lastIndexOf(".");
25598
+ const root = (qualifier) => qualifier === this.currentRootTable && this.currentRootAlias !== void 0 ? this.currentRootAlias : qualifier;
25518
25599
  if (dot !== -1) {
25519
25600
  const relation = column2.slice(0, dot);
25520
25601
  if (relation === this.currentRootTable) {
25521
25602
  return expressionQualifiedColumnRef(
25522
25603
  column2.slice(dot + 1),
25523
- relation,
25604
+ root(relation),
25524
25605
  this.handlerCtx()
25525
25606
  );
25526
25607
  }
@@ -25534,7 +25615,7 @@ var PlanCompiler = class _PlanCompiler {
25534
25615
  this.handlerCtx()
25535
25616
  );
25536
25617
  }
25537
- return table2 === void 0 ? expressionColumnRef(column2, this.handlerCtx()) : expressionQualifiedColumnRef(column2, table2, this.handlerCtx());
25618
+ return table2 === void 0 ? expressionColumnRef(column2, this.handlerCtx()) : expressionQualifiedColumnRef(column2, root(table2), this.handlerCtx());
25538
25619
  }
25539
25620
  /**
25540
25621
  * Compile a single groupBy decision into a ColumnRef AST node.
@@ -26546,7 +26627,12 @@ function compileInsertFrom(config, ctx, state) {
26546
26627
  ];
26547
26628
  }
26548
26629
  let whereClause;
26549
- if (config.where && config.where.length > 0) {
26630
+ if (config.whereCompiler) {
26631
+ whereClause = config.whereCompiler(
26632
+ { ...ctx, currentAlias: sourceAlias },
26633
+ state
26634
+ );
26635
+ } else if (config.where && config.where.length > 0) {
26550
26636
  const dispatch = createWhereDispatcher(compileWhereIntent);
26551
26637
  const subCtx = { ...ctx, currentAlias: sourceAlias };
26552
26638
  if (config.where.length === 1) {
@@ -26623,7 +26709,12 @@ function compileUpsertFrom(config, ctx, state) {
26623
26709
  ];
26624
26710
  }
26625
26711
  let whereClause;
26626
- if (config.where && config.where.length > 0) {
26712
+ if (config.whereCompiler) {
26713
+ whereClause = config.whereCompiler(
26714
+ { ...ctx, currentAlias: sourceAlias },
26715
+ state
26716
+ );
26717
+ } else if (config.where && config.where.length > 0) {
26627
26718
  const dispatch = createWhereDispatcher(compileWhereIntent);
26628
26719
  const subCtx = { ...ctx, currentAlias: sourceAlias };
26629
26720
  if (config.where.length === 1) {
@@ -27107,7 +27198,8 @@ import {
27107
27198
  // src/pgsql-adapter.ts
27108
27199
  import {
27109
27200
  copyDefaultFilters,
27110
- getRelationalReadPlan as getRelationalReadPlan3,
27201
+ getRelationalReadPlan as getRelationalReadPlan2,
27202
+ planInScope as planInScope2,
27111
27203
  resolveReportIncludes as resolveReportIncludes2,
27112
27204
  validateRecursiveSetOperation
27113
27205
  } from "@dbsp/core/internal";
@@ -27124,13 +27216,12 @@ function assertRelationalOutput(plan, context) {
27124
27216
  // src/pgsql-adapter.ts
27125
27217
  import { randomBytes } from "crypto";
27126
27218
  import { isProxy } from "util/types";
27127
- import { POSTGRESQL_CAPABILITIES as POSTGRESQL_CAPABILITIES4, plan as planFn3 } from "@dbsp/core";
27219
+ import { POSTGRESQL_CAPABILITIES as POSTGRESQL_CAPABILITIES4, plan as planFn2 } from "@dbsp/core";
27128
27220
  import { inspectMutationRows as inspectMutationRows2 } from "@dbsp/core/internal";
27129
27221
  import { convertBigintJsReadValue } from "@dbsp/types";
27130
27222
  import {
27131
27223
  assertCompiledQuery,
27132
- projectionlessCompiledQuery,
27133
- rebuildCompiledQuery
27224
+ projectionlessCompiledQuery
27134
27225
  } from "@dbsp/types/adapter-sdk";
27135
27226
  import {
27136
27227
  getNqlBindingRefName as getNqlBindingRefName2,
@@ -27591,14 +27682,10 @@ import { resolveOutputReadHandling as resolveOutputReadHandling4 } from "@dbsp/t
27591
27682
  import { compiledQueryFromProjection } from "@dbsp/types/adapter-sdk";
27592
27683
  var projectionEnvelopeBrand = /* @__PURE__ */ Symbol("projectionEnvelope");
27593
27684
  var projectionOutputMaps = /* @__PURE__ */ new WeakMap();
27685
+ var compiledStatementAsts = /* @__PURE__ */ new WeakMap();
27594
27686
  function outputKeyMapFor(query) {
27595
27687
  return query.outputKeyMap ?? projectionOutputMaps.get(query);
27596
27688
  }
27597
- function preserveOutputKeyMap(prior, next) {
27598
- const map = outputKeyMapFor(prior);
27599
- if (map !== void 0) projectionOutputMaps.set(next, map);
27600
- return next;
27601
- }
27602
27689
  var scalarOneShape = {
27603
27690
  kind: "scalar",
27604
27691
  cardinality: "one"
@@ -27699,9 +27786,11 @@ function fromCompiledQuery(compiled) {
27699
27786
  )
27700
27787
  );
27701
27788
  }
27789
+ const ast = compiledStatementAsts.get(compiled);
27702
27790
  return makeEnvelope({
27703
27791
  sql: compiled.sql,
27704
27792
  parameters: compiled.parameters,
27793
+ ...ast !== void 0 ? { ast } : {},
27705
27794
  projection: { kind: "known", outputs },
27706
27795
  ...compiled.hydrationPlan !== void 0 ? { hydrationPlan: compiled.hydrationPlan } : {}
27707
27796
  });
@@ -27868,6 +27957,7 @@ function projectNamedFields(source, options) {
27868
27957
  return makeEnvelope({
27869
27958
  sql: options.sql,
27870
27959
  parameters: options.parameters,
27960
+ ...options.ast !== void 0 ? { ast: options.ast } : {},
27871
27961
  projection: source.projection,
27872
27962
  ...hydrationPlan2 !== void 0 ? { hydrationPlan: hydrationPlan2 } : {}
27873
27963
  });
@@ -27895,6 +27985,7 @@ function projectNamedFields(source, options) {
27895
27985
  return makeEnvelope({
27896
27986
  sql: options.sql,
27897
27987
  parameters: options.parameters,
27988
+ ...options.ast !== void 0 ? { ast: options.ast } : {},
27898
27989
  projection: { kind: "known", outputs },
27899
27990
  ...hydrationPlan !== void 0 ? { hydrationPlan } : {}
27900
27991
  });
@@ -27916,6 +28007,7 @@ function preserveOneToOne(source, options) {
27916
28007
  return makeEnvelope({
27917
28008
  sql: options.sql,
27918
28009
  parameters: options.parameters,
28010
+ ...options.ast !== void 0 ? { ast: options.ast } : {},
27919
28011
  projection: source.projection,
27920
28012
  ...hydrationPlan !== void 0 ? { hydrationPlan } : {}
27921
28013
  });
@@ -27924,6 +28016,7 @@ function dropPositionalUnion(branches, options) {
27924
28016
  return makeEnvelope({
27925
28017
  sql: options.sql,
27926
28018
  parameters: options.parameters,
28019
+ ...options.ast !== void 0 ? { ast: options.ast } : {},
27927
28020
  projection: {
27928
28021
  kind: "dropped",
27929
28022
  reason: options.reason,
@@ -27962,6 +28055,7 @@ function finalizeEnvelope(env) {
27962
28055
  if (env.projection.outputKeyMap !== void 0) {
27963
28056
  projectionOutputMaps.set(compiled2, env.projection.outputKeyMap);
27964
28057
  }
28058
+ if (env.ast !== void 0) compiledStatementAsts.set(compiled2, env.ast);
27965
28059
  return compiled2;
27966
28060
  }
27967
28061
  const columnMetadata = /* @__PURE__ */ new Map();
@@ -27991,6 +28085,7 @@ function finalizeEnvelope(env) {
27991
28085
  };
27992
28086
  const compiled = compiledQueryFromProjection(fields);
27993
28087
  projectionOutputMaps.set(compiled, outputKeyMap);
28088
+ if (env.ast !== void 0) compiledStatementAsts.set(compiled, env.ast);
27994
28089
  return compiled;
27995
28090
  }
27996
28091
  function buildReturnedOutputKeyMap(outputs) {
@@ -28651,7 +28746,7 @@ function assertPlannedReportAuthority(plan) {
28651
28746
  );
28652
28747
  }
28653
28748
  }
28654
- function compileSelectEnvelope(plan, options, deps) {
28749
+ function compileSelectEnvelope(plan, options, deps, nested) {
28655
28750
  const schemaName = deps.schemaName;
28656
28751
  const resolvedModelForCompiler = options?.model ?? deps.model;
28657
28752
  if ([plan.intent, plan.executableIntent].some(
@@ -28694,7 +28789,8 @@ function compileSelectEnvelope(plan, options, deps) {
28694
28789
  },
28695
28790
  ...resolvedModelForCompiler != null && {
28696
28791
  model: resolvedModelForCompiler
28697
- }
28792
+ },
28793
+ compileNestedSelect: nestedSelectCompiler(options, deps)
28698
28794
  };
28699
28795
  const expressionConditions = plan.execution?.expressionConditions?.map(
28700
28796
  (entry2) => ({
@@ -28837,7 +28933,12 @@ function compileSelectEnvelope(plan, options, deps) {
28837
28933
  plan.execution.expressionSubqueries
28838
28934
  )
28839
28935
  },
28840
- ...execIntent.having && { rawHaving: execIntent.having }
28936
+ ...execIntent.having && { rawHaving: execIntent.having },
28937
+ ...nested?.rootAlias !== void 0 && { rootAlias: nested.rootAlias },
28938
+ ...nested && {
28939
+ enclosingRanges: nested.enclosingRanges,
28940
+ enclosingQualifiers: nested.enclosingQualifiers
28941
+ }
28841
28942
  };
28842
28943
  if (resolvedWhere)
28843
28944
  simplifiedPlan = {
@@ -28852,6 +28953,8 @@ function compileSelectEnvelope(plan, options, deps) {
28852
28953
  };
28853
28954
  }
28854
28955
  const result = compilePlan(simplifiedPlan, compilerOptions);
28956
+ if (nested)
28957
+ assertScalarBodyArity(result.ast, plan.rootTable, resolvedModelForCompiler);
28855
28958
  const baseEnv = fromAstProjection({
28856
28959
  sql: result.sql,
28857
28960
  parameters: result.parameters,
@@ -28905,10 +29008,88 @@ function bindExpressionSubqueries(intent, entries) {
28905
29008
  throw new Error(`Missing expression subquery at ${entry2.intentPath}`);
28906
29009
  return {
28907
29010
  expression: node,
28908
- body: entry2.body
29011
+ select: entry2.select
28909
29012
  };
28910
29013
  });
28911
29014
  }
29015
+ function nestedSelectCompiler(options, deps) {
29016
+ return (select, parent) => {
29017
+ const range = select.execution.rootRange;
29018
+ const enclosingQualifiers = new Map(parent.enclosingQualifiers ?? []);
29019
+ const parentRoot = parent.rootRangeAlias ?? parent.rootTable;
29020
+ enclosingQualifiers.set(
29021
+ parentRoot,
29022
+ parent.currentAlias !== void 0 && parent.currentAlias !== parentRoot ? parent.currentAlias : identifierText(
29023
+ declaredRelationBindingFor(parent.scope, parent.rootTable)?.qualifier ?? queryLocal(parentRoot)
29024
+ )
29025
+ );
29026
+ enclosingQualifiers.set(
29027
+ range.alias,
29028
+ range.alias !== range.table ? range.alias : identifierText(
29029
+ resolveDeclaredIdentifier(
29030
+ deps.declaredNames,
29031
+ deps.dbCasing ?? "preserve",
29032
+ { kind: "table", table: range.table }
29033
+ )
29034
+ )
29035
+ );
29036
+ const known = [
29037
+ ...parent.queryRanges ?? [],
29038
+ ...(parent.enclosingRanges ?? []).flat(),
29039
+ ...parent.scope?.bindings.values() ?? []
29040
+ ];
29041
+ const enclosingRanges = select.enclosing.map(
29042
+ (scope) => scope.map((enclosingRange) => {
29043
+ const emitted = enclosingQualifiers.get(enclosingRange.alias) ?? enclosingRange.alias;
29044
+ return known.find(
29045
+ (binding) => identifierText(binding.qualifier) === emitted
29046
+ ) ?? relationBinding({
29047
+ qualifier: queryLocal(emitted),
29048
+ kind: "declared-table",
29049
+ logicalTable: enclosingRange.table
29050
+ });
29051
+ })
29052
+ );
29053
+ const envelope = compileSelectEnvelope(
29054
+ markPlannedReport({
29055
+ rootTable: select.intent.from,
29056
+ decisions: select.decisions,
29057
+ warnings: [],
29058
+ ctes: [],
29059
+ intent: select.intent,
29060
+ execution: select.execution,
29061
+ metadata: {
29062
+ planningTimeMs: 0,
29063
+ relationsAnalyzed: 0,
29064
+ isAmbiguous: false
29065
+ }
29066
+ }),
29067
+ options,
29068
+ deps,
29069
+ {
29070
+ ...range.alias !== range.table && { rootAlias: range.alias },
29071
+ enclosingRanges,
29072
+ enclosingQualifiers
29073
+ }
29074
+ );
29075
+ if (envelope.ast === void 0)
29076
+ throw new Error("A nested select produced no AST.");
29077
+ return { ast: envelope.ast, parameters: envelope.parameters };
29078
+ };
29079
+ }
29080
+ function assertScalarBodyArity(ast, table2, model) {
29081
+ const targets = ast.SelectStmt?.targetList ?? [];
29082
+ const star = model?.getTable(table2)?.columns.length ?? 1;
29083
+ const columns = targets.reduce((n, target) => {
29084
+ const fields = target.ResTarget?.val?.ColumnRef?.fields;
29085
+ const last = Array.isArray(fields) ? fields.at(-1) : void 0;
29086
+ return n + (last !== null && typeof last === "object" && "A_Star" in last ? star : 1);
29087
+ }, 0);
29088
+ if (columns !== 1)
29089
+ throw new Error(
29090
+ `scalar subquery body projects ${columns} columns; a scalar subquery yields one value.`
29091
+ );
29092
+ }
28912
29093
  function planningNodeAtPath(intent, path) {
28913
29094
  let node = intent;
28914
29095
  for (const key of path.replaceAll("[", ".").replaceAll("]", "").split(".")) {
@@ -28919,6 +29100,83 @@ function planningNodeAtPath(intent, path) {
28919
29100
  return node;
28920
29101
  }
28921
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
+
28922
29180
  // src/adapter-compiler-mutations.ts
28923
29181
  var POSTGRESQL_PARAMETER_LIMIT = 65535;
28924
29182
  var HETEROGENEOUS_INSERT_CELL_LIMIT = 2 * POSTGRESQL_PARAMETER_LIMIT;
@@ -28944,12 +29202,6 @@ function assertParameterLimit(operation, count) {
28944
29202
  function whereIntentAsDecision(where) {
28945
29203
  return where;
28946
29204
  }
28947
- function renumberSqlParams(sql, offset) {
28948
- if (offset === 0) return sql;
28949
- return sql.replace(/\$(\d+)/g, (_match, num) => {
28950
- return `$${Number.parseInt(num, 10) + offset}`;
28951
- });
28952
- }
28953
29205
  function compileSourceQueryCte(operation, sourceName, sourceQuery, options, deps) {
28954
29206
  const model = deps.model;
28955
29207
  if (model === void 0) {
@@ -28960,9 +29212,9 @@ function compileSourceQueryCte(operation, sourceName, sourceQuery, options, deps
28960
29212
  const sourcePlan = planFn(sourceQuery, model, {
28961
29213
  dialectCapabilities: deps.dialectCapabilities ?? POSTGRESQL_CAPABILITIES3
28962
29214
  });
28963
- const source = compileSelect(sourcePlan, options, deps);
29215
+ const source = compileSelectEnvelope(sourcePlan, options, deps);
28964
29216
  return {
28965
- sql: source.sql,
29217
+ ast: requireStatementAst(source, `the source query '${sourceName}'`),
28966
29218
  parameters: source.parameters
28967
29219
  };
28968
29220
  }
@@ -28988,12 +29240,20 @@ function prependSourceCte(query, sourceName, sourceCte) {
28988
29240
  if (sourceCte === void 0) {
28989
29241
  return finalizeEnvelope(query);
28990
29242
  }
28991
- const cteParamCount = sourceCte.parameters.length;
28992
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
+ );
28993
29252
  return finalizeEnvelope(
28994
29253
  preserveOneToOne(query, {
28995
- sql: `WITH ${quoteIdent(sourceCteName, "alias")} as (${sourceCte.sql}) ${renumberSqlParams(query.sql, cteParamCount)}`,
28996
- parameters: [...sourceCte.parameters, ...query.parameters]
29254
+ sql: deparseQuoted(ast),
29255
+ parameters: [...sourceCte.parameters, ...query.parameters],
29256
+ ast
28997
29257
  })
28998
29258
  );
28999
29259
  }
@@ -29059,7 +29319,8 @@ function mutationContext(deps, rootTable, maxRecursiveDepth) {
29059
29319
  ...deps.schemaName !== void 0 && { schema: deps.schemaName },
29060
29320
  maxRecursiveDepth,
29061
29321
  compileCustomFnFilter: buildCustomFnFilter2,
29062
- createWhereDispatcher: () => createWhereDispatcher(compileWhereIntent)
29322
+ createWhereDispatcher: () => createWhereDispatcher(compileWhereIntent),
29323
+ compileNestedSelect: nestedSelectCompiler(void 0, deps)
29063
29324
  };
29064
29325
  }
29065
29326
  function resolveExistsRelation(sourceTable, relation, model) {
@@ -29253,7 +29514,11 @@ function compileInsertFrom2(intent, options, deps) {
29253
29514
  );
29254
29515
  const state = createCompilerState();
29255
29516
  assertNoPathRefInConditionBodies(intent.where);
29256
- const resolvedWhere = intent.where ? resolveExistsIntent(intent.where, intent.source, deps) : void 0;
29517
+ const whereCompiler = resolvedMutationWhere(intent.where, intent.source, {
29518
+ ...deps,
29519
+ ...bindingNames !== void 0 && { bindingNames }
29520
+ });
29521
+ const resolvedWhere = intent.where && !whereCompiler ? resolveExistsIntent(intent.where, intent.source, deps) : void 0;
29257
29522
  const sourceBinding2 = mutationBinding(
29258
29523
  { ...deps, ...bindingNames !== void 0 && { bindingNames } },
29259
29524
  intent.source
@@ -29286,6 +29551,7 @@ function compileInsertFrom2(intent, options, deps) {
29286
29551
  }))
29287
29552
  },
29288
29553
  ...resolvedWhere && { where: [whereIntentAsDecision(resolvedWhere)] },
29554
+ ...whereCompiler && { whereCompiler },
29289
29555
  ...intent.limit !== void 0 && { limit: intent.limit },
29290
29556
  ...intent.returning && { returning: [...intent.returning] },
29291
29557
  ...intent.returning && {
@@ -29324,7 +29590,10 @@ function resolvedMutationWhere(where, table2, deps) {
29324
29590
  root,
29325
29591
  [root],
29326
29592
  allocator,
29327
- deps.model
29593
+ deps.model,
29594
+ 0,
29595
+ [],
29596
+ localSourcePredicate(deps.bindingNames, deps.scope)
29328
29597
  );
29329
29598
  if (!resolved) {
29330
29599
  throw new Error(
@@ -29415,7 +29684,16 @@ function compileBatchUpdate(intent, options, deps) {
29415
29684
  value
29416
29685
  })) : void 0;
29417
29686
  let whereGuard;
29418
- if (intent.where) {
29687
+ const guardCompiler = resolvedMutationWhere(intent.where, intent.table, deps);
29688
+ if (guardCompiler)
29689
+ whereGuard = guardCompiler(
29690
+ {
29691
+ ...ctx,
29692
+ currentAlias: declaredMutationTableMetadata(deps, intent.table)?.physicalName ?? declaredMutationTable(deps, intent.table)
29693
+ },
29694
+ state
29695
+ );
29696
+ else if (intent.where) {
29419
29697
  assertNoPathRefInConditionBodies(intent.where);
29420
29698
  const resolvedWhere = resolveExistsIntent(intent.where, intent.table, deps);
29421
29699
  const whereCtx = {
@@ -29681,7 +29959,11 @@ function compileUpsertFrom2(intent, options, deps) {
29681
29959
  );
29682
29960
  const state = createCompilerState();
29683
29961
  assertNoPathRefInConditionBodies(intent.where);
29684
- const resolvedWhere = intent.where ? resolveExistsIntent(intent.where, intent.source, deps) : void 0;
29962
+ const whereCompiler = resolvedMutationWhere(intent.where, intent.source, {
29963
+ ...deps,
29964
+ ...bindingNames !== void 0 && { bindingNames }
29965
+ });
29966
+ const resolvedWhere = intent.where && !whereCompiler ? resolveExistsIntent(intent.where, intent.source, deps) : void 0;
29685
29967
  let columns;
29686
29968
  if (intent.columns) {
29687
29969
  columns = [...intent.columns];
@@ -29729,6 +30011,7 @@ function compileUpsertFrom2(intent, options, deps) {
29729
30011
  }))
29730
30012
  },
29731
30013
  ...resolvedWhere && { where: [whereIntentAsDecision(resolvedWhere)] },
30014
+ ...whereCompiler && { whereCompiler },
29732
30015
  ...intent.limit !== void 0 && { limit: intent.limit },
29733
30016
  ...intent.returning && { returning: [...intent.returning] },
29734
30017
  ...intent.returning && {
@@ -29752,10 +30035,10 @@ function compileUpsertFrom2(intent, options, deps) {
29752
30035
  // src/adapter-compiler-recursive.ts
29753
30036
  import {
29754
30037
  getRelationalReadPlan,
30038
+ planInScope,
29755
30039
  resolveReportIncludes
29756
30040
  } from "@dbsp/core/internal";
29757
30041
  import { markPlannedReport as markPlannedReport2 } from "@dbsp/types/internal";
29758
- import { plan as planFn2 } from "@dbsp/core";
29759
30042
  function withBindingProjectionScope(deps, bindingNames, projections) {
29760
30043
  const scope = queryScopeForBindingProjections(bindingNames, projections);
29761
30044
  return {
@@ -29769,10 +30052,11 @@ function getRegisteredProjection(registry, name) {
29769
30052
  if (registry.size === 0) return void 0;
29770
30053
  return registry.get(name);
29771
30054
  }
29772
- function createPlanReportForQuery(query, model, defaultFilters) {
30055
+ function createPlanReportForQuery(query, model, defaultFilters, isLocalSource) {
29773
30056
  const resolution = resolveReportIncludes(query, [], model, {
29774
30057
  ...defaultFilters && { defaultFilters },
29775
- skipRootDefaultFilter: true
30058
+ skipRootDefaultFilter: true,
30059
+ isLocalSource
29776
30060
  });
29777
30061
  return markPlannedReport2({
29778
30062
  rootTable: query.from,
@@ -29793,20 +30077,36 @@ function createPlanReportForQuery(query, model, defaultFilters) {
29793
30077
  }
29794
30078
  function createPlanReportForCteQuery(query, deps, hasRegisteredSource = false) {
29795
30079
  const queryLocalSource = hasRegisteredSource || hasBindingName(deps.bindingNames, query.from);
30080
+ const isLocalSource = localSourcePredicate(deps.bindingNames, deps.scope);
29796
30081
  const issued = getRelationalReadPlan(query, queryLocalSource);
29797
30082
  if (issued) return issued;
29798
30083
  if (queryLocalSource) {
29799
- return createPlanReportForQuery(query, deps.model, deps.defaultFilters);
30084
+ return createPlanReportForQuery(
30085
+ query,
30086
+ deps.model,
30087
+ deps.defaultFilters,
30088
+ isLocalSource
30089
+ );
29800
30090
  }
29801
30091
  if (deps.model === void 0 || deps.model.getTable(query.from) === void 0) {
29802
- return createPlanReportForQuery(query, deps.model, deps.defaultFilters);
30092
+ return createPlanReportForQuery(
30093
+ query,
30094
+ deps.model,
30095
+ deps.defaultFilters,
30096
+ isLocalSource
30097
+ );
29803
30098
  }
29804
- return planFn2(query, deps.model, {
29805
- ...deps.defaultFilters && { defaultFilters: deps.defaultFilters },
29806
- ...deps.dialectCapabilities !== void 0 && {
29807
- dialectCapabilities: deps.dialectCapabilities
29808
- }
29809
- });
30099
+ return planInScope(
30100
+ query,
30101
+ deps.model,
30102
+ {
30103
+ ...deps.defaultFilters && { defaultFilters: deps.defaultFilters },
30104
+ ...deps.dialectCapabilities !== void 0 && {
30105
+ dialectCapabilities: deps.dialectCapabilities
30106
+ }
30107
+ },
30108
+ { isLocalSource }
30109
+ );
29810
30110
  }
29811
30111
  function dbOutputKey(name) {
29812
30112
  return name;
@@ -29911,12 +30211,13 @@ function buildCteProjectionShape(source, select) {
29911
30211
  }
29912
30212
  return { selections, expressions, preserveOneToOne: false };
29913
30213
  }
29914
- function projectCteQueryEnvelope(source, query, sql, parameters, hydrationPlan) {
30214
+ function projectCteQueryEnvelope(source, query, sql, parameters, hydrationPlan, ast) {
29915
30215
  const shape = buildCteProjectionShape(source, query.select);
29916
30216
  if (shape.preserveOneToOne) {
29917
30217
  return preserveOneToOne(source, {
29918
30218
  sql,
29919
30219
  parameters,
30220
+ ...ast !== void 0 ? { ast } : {},
29920
30221
  ...hydrationPlan !== void 0 ? { hydrationPlan } : {},
29921
30222
  preserveHydrationPlan: false
29922
30223
  });
@@ -29924,6 +30225,7 @@ function projectCteQueryEnvelope(source, query, sql, parameters, hydrationPlan)
29924
30225
  return projectNamedFields(source, {
29925
30226
  sql,
29926
30227
  parameters,
30228
+ ...ast !== void 0 ? { ast } : {},
29927
30229
  selections: shape.selections,
29928
30230
  expressions: shape.expressions,
29929
30231
  ...hydrationPlan !== void 0 ? { hydrationPlan } : {},
@@ -29943,21 +30245,23 @@ function compileQueryEnvelope(query, options, deps, registry) {
29943
30245
  query,
29944
30246
  compiled.sql,
29945
30247
  compiled.parameters,
29946
- compiled.hydrationPlan
30248
+ compiled.hydrationPlan,
30249
+ compiled.ast
29947
30250
  );
29948
30251
  }
29949
30252
  return compiled;
29950
30253
  }
29951
- function rehomeQueryEnvelope(source, query, compiled, sql, parameters) {
30254
+ function rehomeQueryEnvelope(source, query, compiled, sql, parameters, ast) {
29952
30255
  return projectCteQueryEnvelope(
29953
30256
  source,
29954
30257
  query,
29955
30258
  sql,
29956
30259
  parameters,
29957
- compiled.hydrationPlan
30260
+ compiled.hydrationPlan,
30261
+ ast
29958
30262
  );
29959
30263
  }
29960
- function compileRecursive(report, model, _options, deps) {
30264
+ function compileRecursive(report, model, options, deps) {
29961
30265
  const schemaName = deps.schemaName;
29962
30266
  const state = createCompilerState();
29963
30267
  const intent = report.intent;
@@ -30030,7 +30334,8 @@ function compileRecursive(report, model, _options, deps) {
30030
30334
  ...schemaName !== void 0 && { schema: schemaName },
30031
30335
  maxRecursiveDepth: intent.maxDepth,
30032
30336
  compileCustomFnFilter: buildCustomFnFilter2,
30033
- createWhereDispatcher: () => createWhereDispatcher(compileWhereIntent)
30337
+ createWhereDispatcher: () => createWhereDispatcher(compileWhereIntent),
30338
+ compileNestedSelect: nestedSelectCompiler(options, deps)
30034
30339
  };
30035
30340
  const startSelect = intent.start.select ?? [];
30036
30341
  const nodeIdColumn = intent.start.nodeIdExpr.kind === "column" ? intent.start.nodeIdExpr.name : pkColumn;
@@ -30123,7 +30428,8 @@ function compileRecursive(report, model, _options, deps) {
30123
30428
  ...schemaName !== void 0 && { schema: schemaName },
30124
30429
  maxRecursiveDepth: intent.maxDepth,
30125
30430
  compileCustomFnFilter: buildCustomFnFilter2,
30126
- createWhereDispatcher: () => createWhereDispatcher(compileWhereIntent)
30431
+ createWhereDispatcher: () => createWhereDispatcher(compileWhereIntent),
30432
+ compileNestedSelect: nestedSelectCompiler(options, deps)
30127
30433
  };
30128
30434
  const startSelect = intent.start.select ?? [];
30129
30435
  const nodeIdColumn = intent.start.nodeIdExpr.kind === "column" ? intent.start.nodeIdExpr.name : pkColumn;
@@ -30303,9 +30609,14 @@ function compileRecursive(report, model, _options, deps) {
30303
30609
  return finalizeEnvelope(env);
30304
30610
  }
30305
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) {
30306
30617
  const state = createCompilerState();
30307
30618
  const allCteParams = [];
30308
- const cteSqlFragments = [];
30619
+ const cteNodes = [];
30309
30620
  const cteProjectionByName = new Map(
30310
30621
  initialProjectionByName
30311
30622
  );
@@ -30324,12 +30635,11 @@ function compileCteQuery(intent, options, deps, initialProjectionByName) {
30324
30635
  const node = buildUnnestCte(cte, state);
30325
30636
  const cteParams = state.parameters.slice(beforeUnnestParamCount);
30326
30637
  allCteParams.push(...cteParams);
30327
- const cteSql = deparseQuoted(node);
30328
- cteSqlFragments.push(cteSql);
30638
+ cteNodes.push(node);
30329
30639
  cteProjectionByName.set(
30330
30640
  emittedCteName,
30331
30641
  fromOutputDescriptors({
30332
- sql: cteSql,
30642
+ sql: deparseQuoted(node),
30333
30643
  parameters: cteParams,
30334
30644
  columns: [
30335
30645
  ...Object.keys(cte.columns),
@@ -30339,7 +30649,6 @@ function compileCteQuery(intent, options, deps, initialProjectionByName) {
30339
30649
  );
30340
30650
  } else if (cte.kind === "rawCte") {
30341
30651
  isRecursive = true;
30342
- const currentParamOffset = allCteParams.length;
30343
30652
  const rawCteStepDeps = withBindingProjectionScope(
30344
30653
  visibleCteDeps,
30345
30654
  withBindingName(visibleCteDeps.bindingNames, queryLocal(cte.name)),
@@ -30353,20 +30662,9 @@ function compileCteQuery(intent, options, deps, initialProjectionByName) {
30353
30662
  cteProjectionByName
30354
30663
  );
30355
30664
  finalizeEnvelope(rawCte.projection);
30356
- const renumberedRawCteSql = currentParamOffset > 0 ? rawCte.sql.replace(
30357
- /\$([0-9]+)/g,
30358
- (_, n) => `$${parseInt(n, 10) + currentParamOffset}`
30359
- ) : rawCte.sql;
30665
+ cteNodes.push(shiftParameters(rawCte.ast, allCteParams.length));
30360
30666
  allCteParams.push(...rawCte.params);
30361
- cteSqlFragments.push(renumberedRawCteSql);
30362
- cteProjectionByName.set(
30363
- emittedCteName,
30364
- preserveOneToOne(rawCte.bindingProjection, {
30365
- sql: renumberedRawCteSql,
30366
- parameters: rawCte.params,
30367
- preserveHydrationPlan: false
30368
- })
30369
- );
30667
+ cteProjectionByName.set(emittedCteName, rawCte.bindingProjection);
30370
30668
  } else if (cte.kind === "simpleCte") {
30371
30669
  const innerCte = cte;
30372
30670
  const innerCompiled = compileQueryEnvelope(
@@ -30376,17 +30674,20 @@ function compileCteQuery(intent, options, deps, initialProjectionByName) {
30376
30674
  cteProjectionByName
30377
30675
  );
30378
30676
  assertRelationalOutput(innerCompiled.hydrationPlan, "Relational bodies");
30379
- const currentParamOffset = allCteParams.length;
30380
- const renumberedInnerSql = currentParamOffset > 0 ? innerCompiled.sql.replace(
30381
- /\$([0-9]+)/g,
30382
- (_, n) => `$${parseInt(n, 10) + currentParamOffset}`
30383
- ) : innerCompiled.sql;
30677
+ cteNodes.push(
30678
+ commonTableExpression(
30679
+ emittedCteName,
30680
+ shiftParameters(
30681
+ requireStatementAst(innerCompiled, `CTE '${cte.name}'`),
30682
+ allCteParams.length
30683
+ )
30684
+ )
30685
+ );
30384
30686
  allCteParams.push(...innerCompiled.parameters);
30385
- cteSqlFragments.push(`"${emittedCteName}" AS (${renumberedInnerSql})`);
30386
30687
  cteProjectionByName.set(
30387
30688
  emittedCteName,
30388
30689
  preserveOneToOne(innerCompiled, {
30389
- sql: renumberedInnerSql,
30690
+ sql: innerCompiled.sql,
30390
30691
  parameters: innerCompiled.parameters,
30391
30692
  preserveHydrationPlan: false
30392
30693
  })
@@ -30419,23 +30720,24 @@ function compileCteQuery(intent, options, deps, initialProjectionByName) {
30419
30720
  relationTargetProjections: cteProjectionByName
30420
30721
  }
30421
30722
  );
30422
- const cteParamCount = allCteParams.length;
30423
- const renumberedOuterSql = cteParamCount > 0 ? outerCompiled.sql.replace(
30424
- /\$([0-9]+)/g,
30425
- (_, n) => `$${parseInt(n, 10) + cteParamCount}`
30426
- ) : outerCompiled.sql;
30427
- const withClause = cteSqlFragments.join(", ");
30428
- const withKeyword = isRecursive ? "WITH RECURSIVE" : "WITH";
30429
- 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);
30430
30732
  const parameters = [...allCteParams, ...outerCompiled.parameters];
30431
- const env = outerRegisteredSource ? projectCteQueryEnvelope(
30733
+ return outerRegisteredSource ? projectCteQueryEnvelope(
30432
30734
  outerRegisteredSource,
30433
30735
  intent.query,
30434
30736
  sql,
30435
30737
  parameters,
30436
- outerCompiled.hydrationPlan
30437
- ) : preserveOneToOne(outerCompiled, { sql, parameters });
30438
- return finalizeEnvelope(env);
30738
+ outerCompiled.hydrationPlan,
30739
+ ast
30740
+ ) : preserveOneToOne(outerCompiled, { sql, parameters, ast });
30439
30741
  }
30440
30742
  function buildUnnestCte(cte, state) {
30441
30743
  const columns = Object.keys(cte.columns);
@@ -30518,39 +30820,52 @@ function buildRawCte(cte, anchorDeps, stepDeps, options, registry) {
30518
30820
  options,
30519
30821
  scopedStepDeps
30520
30822
  );
30521
- const baseParamCount = baseCompiled.parameters.length;
30522
- const renumberedStepSql = baseParamCount > 0 ? rawStepCompiled.sql.replace(
30523
- /\$([0-9]+)/g,
30524
- (_, n) => `$${parseInt(n, 10) + baseParamCount}`
30525
- ) : 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
+ );
30526
30834
  const allParams = [
30527
30835
  ...baseCompiled.parameters,
30528
30836
  ...rawStepCompiled.parameters
30529
30837
  ];
30530
- let finalStepSql = renumberedStepSql;
30838
+ let stepAst = shiftedStepAst;
30531
30839
  if (cte.maxDepth !== void 0) {
30532
- const depthCol = `"${(cte.depthColumn ?? "depth").replace(/"/g, '""')}"`;
30533
- const depthParamIndex = allParams.length + 1;
30534
30840
  allParams.push(cte.maxDepth);
30535
- const hasWhere = /\bWHERE\b/i.test(finalStepSql);
30536
- 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
+ );
30537
30847
  }
30848
+ const stepSql = deparseQuoted(stepAst);
30538
30849
  const stepRegisteredSource = stepQuery.from === cte.name ? baseCompiled : getRegisteredProjection(stepProjectionRegistry, stepQuery.from);
30539
30850
  const stepCompiled = stepRegisteredSource ? rehomeQueryEnvelope(
30540
30851
  stepRegisteredSource,
30541
30852
  stepQuery,
30542
30853
  rawStepCompiled,
30543
- finalStepSql,
30544
- allParams
30854
+ stepSql,
30855
+ allParams,
30856
+ stepAst
30545
30857
  ) : preserveOneToOne(rawStepCompiled, {
30546
- sql: finalStepSql,
30547
- parameters: allParams
30858
+ sql: stepSql,
30859
+ parameters: allParams,
30860
+ ast: stepAst
30548
30861
  });
30549
- const setOp = cte.unionAll ? "UNION ALL" : "UNION";
30550
- const cteName = `"${emittedBindName(queryLocal(cte.name))}"`;
30551
- 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);
30552
30867
  return {
30553
- sql: cteSql,
30868
+ ast,
30554
30869
  params: allParams,
30555
30870
  projection: dropPositionalUnion([baseCompiled, stepCompiled], {
30556
30871
  sql: cteSql,
@@ -30566,6 +30881,25 @@ function buildRawCte(cte, anchorDeps, stepDeps, options, registry) {
30566
30881
  })
30567
30882
  };
30568
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
+ }
30569
30903
 
30570
30904
  // src/ddl/table-operations.ts
30571
30905
  function quoteIdentifier2(name) {
@@ -31929,52 +32263,37 @@ function normalizeMaxPreparedStatements(maxStatements) {
31929
32263
  }
31930
32264
 
31931
32265
  // src/set-operation.ts
31932
- import { getRelationalReadPlan as getRelationalReadPlan2 } from "@dbsp/core/internal";
31933
- function isProjectionEnvelope(result) {
31934
- return "projection" in result;
31935
- }
31936
- function toProjectionEnvelope(result) {
31937
- return isProjectionEnvelope(result) ? result : fromCompiledQuery(result);
31938
- }
31939
- function renumberParams(sql, offset) {
31940
- if (offset === 0) return sql;
31941
- return sql.replace(/\$(\d+)/g, (_match, num) => {
31942
- return `$${Number.parseInt(num, 10) + offset}`;
31943
- });
31944
- }
31945
- function compileSetOperation(intent, compileFn) {
31946
- return finalizeEnvelope(compileSetOperationEnvelope(intent, compileFn));
31947
- }
31948
- function compileSetOperationEnvelope(intent, compileFn) {
31949
- const left = compileLeafOrBranch(intent.left, compileFn);
32266
+ function compileSetOperationEnvelope(intent, compileLeaf) {
32267
+ const left = compileLeafOrBranch(intent.left, compileLeaf);
31950
32268
  assertRelationalOutput(left.hydrationPlan, "Set operations");
31951
- const right = compileLeafOrBranch(intent.right, compileFn);
32269
+ const right = compileLeafOrBranch(intent.right, compileLeaf);
31952
32270
  assertRelationalOutput(right.hydrationPlan, "Set operations");
31953
- const rightSQL = renumberParams(right.sql, left.parameters.length);
31954
- const opKeyword = intent.op.toUpperCase() + (intent.all ? " ALL" : "");
31955
- 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
+ );
31956
32281
  const parameters = [...left.parameters, ...right.parameters];
31957
32282
  return dropPositionalUnion([left, right], {
31958
- sql,
32283
+ sql: deparseQuoted(ast),
31959
32284
  parameters,
32285
+ ast,
31960
32286
  reason: "set-operation-positional-merge"
31961
32287
  });
31962
32288
  }
31963
- function compileLeafOrBranch(intent, compileFn) {
32289
+ function compileLeafOrBranch(intent, compileLeaf) {
31964
32290
  if ("kind" in intent && intent.kind === "setOperation") {
31965
- return compileSetOperationEnvelope(intent, compileFn);
31966
- }
31967
- return toProjectionEnvelope(compileFn(intent));
31968
- }
31969
- function createLeafCompileFn(adapter, model, planFn4, options) {
31970
- return (query) => {
31971
- const planReport = getRelationalReadPlan2(query) ?? planFn4(query, model, {
31972
- dialectCapabilities: adapter.dialectCapabilities
31973
- });
31974
- return fromCompiledQuery(
31975
- adapter.compile(planReport, { ...options, model })
32291
+ return compileSetOperationEnvelope(
32292
+ intent,
32293
+ compileLeaf
31976
32294
  );
31977
- };
32295
+ }
32296
+ return compileLeaf(intent);
31978
32297
  }
31979
32298
 
31980
32299
  // src/streaming/cursor.ts
@@ -32853,12 +33172,6 @@ function protectedStatementCleanupAction(rawSqlStatement, detail2) {
32853
33172
  function raise(error) {
32854
33173
  throw error;
32855
33174
  }
32856
- function renumberSqlParams2(sql, offset) {
32857
- if (offset === 0) return sql;
32858
- return sql.replace(/\$(\d+)/g, (_match, num) => {
32859
- return `$${Number.parseInt(num, 10) + offset}`;
32860
- });
32861
- }
32862
33175
  function pgReturnedIdentifier2(identifier3) {
32863
33176
  let result = "";
32864
33177
  let byteLength = 0;
@@ -32870,16 +33183,6 @@ function pgReturnedIdentifier2(identifier3) {
32870
33183
  }
32871
33184
  return result;
32872
33185
  }
32873
- function prefixNqlBindingCtes(bindingCtes, sql) {
32874
- if (bindingCtes.length === 0) return sql;
32875
- const withMatch = /^(WITH\s+RECURSIVE\s+|WITH\s+)/i.exec(sql);
32876
- if (!withMatch) {
32877
- return `WITH ${bindingCtes.join(", ")} ${sql}`;
32878
- }
32879
- const [prefix] = withMatch;
32880
- const withKeyword = /^WITH\s+RECURSIVE\s+/i.test(prefix) ? "WITH RECURSIVE" : "WITH";
32881
- return `${withKeyword} ${bindingCtes.join(", ")}, ${sql.slice(prefix.length)}`;
32882
- }
32883
33186
  function isCompiledNqlQuery(input) {
32884
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);
32885
33188
  }
@@ -33176,7 +33479,48 @@ function resolveRuntimeBindingCteColumnTypes(name, binding, schemaName) {
33176
33479
  return resolvePgTypeForColumnTypeInfo(name, column2, info, schemaName);
33177
33480
  });
33178
33481
  }
33179
- 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) {
33180
33524
  const pgTypes = resolveRuntimeBindingCteColumnTypes(
33181
33525
  name,
33182
33526
  binding,
@@ -33187,39 +33531,34 @@ function compileTypedNqlRuntimeBindingCte(name, binding, parameterOffset, cteNam
33187
33531
  binding,
33188
33532
  parameterOffset,
33189
33533
  cteName,
33190
- columnSql,
33534
+ cteColumns,
33191
33535
  pgTypes
33192
33536
  );
33193
33537
  }
33194
- function compileNqlRuntimeBindingCteWithPgTypes(name, binding, parameterOffset, cteName, columnSql, pgTypes) {
33195
- const anchorColumns = binding.columns.map((column2, columnIndex) => {
33196
- const columnAlias = quoteIdent(column2, "column");
33197
- const pgType = pgTypes[columnIndex];
33198
- return pgType === void 0 ? `NULL AS ${columnAlias}` : `CAST(NULL AS ${pgType}) AS ${columnAlias}`;
33199
- }).join(", ");
33200
- const sourceAnchorSql = `SELECT ${anchorColumns} WHERE false`;
33201
- if (binding.rows.length === 0) {
33202
- return {
33203
- cte: `${cteName} (${columnSql}) as (${sourceAnchorSql})`,
33204
- parameters: []
33205
- };
33206
- }
33207
- assertRuntimeBindingValuesParameterCount(name, binding, parameterOffset);
33208
- const parameters = [];
33209
- let nextParam = parameterOffset + 1;
33210
- const valuesSql = binding.rows.map((row) => {
33211
- const placeholders = binding.columns.map((column2, columnIndex) => {
33212
- parameters.push(row[column2]);
33213
- 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");
33214
33543
  const pgType = pgTypes[columnIndex];
33215
- return pgType === void 0 ? paramRef : `${paramRef}::${pgType}`;
33216
- });
33217
- return `(${placeholders.join(", ")})`;
33218
- }).join(", ");
33219
- return {
33220
- cte: `${cteName} (${columnSql}) as (${sourceAnchorSql} UNION ALL VALUES ${valuesSql})`,
33221
- parameters
33544
+ return {
33545
+ ResTarget: {
33546
+ name: column2,
33547
+ val: pgType === void 0 ? nullConstant : runtimeBindingCast(nullConstant, pgType)
33548
+ }
33549
+ };
33550
+ }),
33551
+ whereClause: falseConstant
33222
33552
  };
33553
+ return runtimeBindingCteNode(
33554
+ name,
33555
+ binding,
33556
+ parameterOffset,
33557
+ cteName,
33558
+ cteColumns,
33559
+ anchor,
33560
+ pgTypes
33561
+ );
33223
33562
  }
33224
33563
  function compileNqlRuntimeBindingCte(name, binding, deps, parameterOffset, sourceTable, schemaName, model, returningItems) {
33225
33564
  const sourceBinding2 = sourceTable === void 0 ? void 0 : relationBindingFor(deps.scope, queryLocal(sourceTable));
@@ -33249,21 +33588,22 @@ function compileNqlRuntimeBindingCte(name, binding, deps, parameterOffset, sourc
33249
33588
  `NQL runtime binding '${name}' cannot be materialized without projected columns.`
33250
33589
  );
33251
33590
  }
33252
- const cteName = quoteIdent(emittedBindName(queryLocal(name)), "alias");
33591
+ const cteName = emittedBindName(queryLocal(name));
33592
+ validateIdentifier(cteName, "alias");
33253
33593
  const emittedColumnNames = binding.columns.map(pgReturnedIdentifier2);
33254
33594
  if (new Set(emittedColumnNames).size !== emittedColumnNames.length) {
33255
33595
  throw new Error(
33256
33596
  `NQL runtime binding '${name}' emits duplicate column names after PostgreSQL returned-label truncation.`
33257
33597
  );
33258
33598
  }
33259
- const columnSql = emittedColumnNames.map((column2) => quoteIdent(column2, "column")).join(", ");
33599
+ for (const column2 of emittedColumnNames) validateIdentifier(column2, "column");
33260
33600
  if (binding.columnTypes !== void 0) {
33261
33601
  return compileTypedNqlRuntimeBindingCte(
33262
33602
  name,
33263
33603
  binding,
33264
33604
  parameterOffset,
33265
33605
  cteName,
33266
- columnSql,
33606
+ emittedColumnNames,
33267
33607
  schemaName
33268
33608
  );
33269
33609
  }
@@ -33279,7 +33619,7 @@ function compileNqlRuntimeBindingCte(name, binding, deps, parameterOffset, sourc
33279
33619
  binding,
33280
33620
  parameterOffset,
33281
33621
  cteName,
33282
- columnSql,
33622
+ emittedColumnNames,
33283
33623
  declaredOutputPgTypes
33284
33624
  );
33285
33625
  }
@@ -33288,43 +33628,58 @@ function compileNqlRuntimeBindingCte(name, binding, deps, parameterOffset, sourc
33288
33628
  `NQL runtime binding '${name}' cannot materialize a typed relation because its source table is unavailable.`
33289
33629
  );
33290
33630
  }
33291
- const projectedColumns = binding.columns.map((column2) => quoteIdent(sourcePhysicalColumnFor(column2), "column")).join(", ");
33292
- const sourceAnchorSql = `SELECT ${projectedColumns} FROM ${sourceBinding2 === void 0 && schemaName ? `${quoteIdent(schemaName, "schema")}.` : ""}${quoteIdent(
33293
- sourceBinding2 === void 0 ? identifierText(declaredTable(requireDeclaredNames(deps), sourceTable)) : sourceTable,
33294
- "table"
33295
- )} WHERE false`;
33296
- if (binding.rows.length === 0) {
33297
- return {
33298
- cte: `${cteName} (${columnSql}) as (${sourceAnchorSql})`,
33299
- parameters: []
33300
- };
33631
+ if (sourceBinding2 === void 0 && schemaName) {
33632
+ validateIdentifier(schemaName, "schema");
33301
33633
  }
33302
- assertRuntimeBindingValuesParameterCount(name, binding, parameterOffset);
33303
- 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(
33304
33662
  name,
33305
33663
  { ...binding, columns: binding.columns.map(sourceColumnFor) },
33306
33664
  model,
33307
33665
  sourceTable,
33308
33666
  schemaName
33309
33667
  );
33310
- const parameters = [];
33311
- let nextParam = parameterOffset + 1;
33312
- const valuesSql = binding.rows.map((row) => {
33313
- const placeholders = binding.columns.map((column2, columnIndex) => {
33314
- parameters.push(row[column2]);
33315
- return `$${nextParam++}::${columnTypes[columnIndex]}`;
33316
- });
33317
- return `(${placeholders.join(", ")})`;
33318
- }).join(", ");
33319
- return {
33320
- cte: `${cteName} (${columnSql}) as (${sourceAnchorSql} UNION ALL VALUES ${valuesSql})`,
33321
- parameters
33322
- };
33668
+ return runtimeBindingCteNode(
33669
+ name,
33670
+ binding,
33671
+ parameterOffset,
33672
+ cteName,
33673
+ emittedColumnNames,
33674
+ anchor,
33675
+ columnTypes
33676
+ );
33323
33677
  }
33324
- function createNqlBindingSelectPlan(query, model, defaultFilters) {
33678
+ function createNqlBindingSelectPlan(query, model, defaultFilters, isLocalSource) {
33325
33679
  const resolution = resolveReportIncludes2(query, [], model, {
33326
33680
  ...defaultFilters && { defaultFilters },
33327
- skipRootDefaultFilter: true
33681
+ skipRootDefaultFilter: true,
33682
+ isLocalSource
33328
33683
  });
33329
33684
  return markPlannedReport3({
33330
33685
  rootTable: query.from,
@@ -33460,12 +33815,13 @@ function buildNqlBindingProjectionShape(source, select) {
33460
33815
  }
33461
33816
  return { selections, expressions, preserveOneToOne: false };
33462
33817
  }
33463
- function projectNqlBindingQueryEnvelope(source, query, sql, parameters, hydrationPlan) {
33818
+ function projectNqlBindingQueryEnvelope(source, query, sql, parameters, hydrationPlan, ast) {
33464
33819
  const shape = buildNqlBindingProjectionShape(source, query.select);
33465
33820
  if (shape.preserveOneToOne) {
33466
33821
  return preserveOneToOne(source, {
33467
33822
  sql,
33468
33823
  parameters,
33824
+ ...ast !== void 0 ? { ast } : {},
33469
33825
  ...hydrationPlan !== void 0 ? { hydrationPlan } : {},
33470
33826
  preserveHydrationPlan: false
33471
33827
  });
@@ -33473,6 +33829,7 @@ function projectNqlBindingQueryEnvelope(source, query, sql, parameters, hydratio
33473
33829
  return projectNamedFields(source, {
33474
33830
  sql,
33475
33831
  parameters,
33832
+ ...ast !== void 0 ? { ast } : {},
33476
33833
  selections: shape.selections,
33477
33834
  expressions: shape.expressions,
33478
33835
  ...hydrationPlan !== void 0 ? { hydrationPlan } : {},
@@ -33810,6 +34167,7 @@ var PgAdapter = class {
33810
34167
  bindingProjections
33811
34168
  );
33812
34169
  const queryFromBinding = hasBindingName(bindingNames, bundle.query.from);
34170
+ const isLocalSource = localSourcePredicate(bindingNames, deps.scope);
33813
34171
  const scanFilters = options?.defaultFilters ? copyDefaultFilters(
33814
34172
  options.defaultFilters,
33815
34173
  (table2) => !hasBindingName(bindingNames, table2)
@@ -33817,13 +34175,19 @@ var PgAdapter = class {
33817
34175
  const planReport = bundle.plan ?? (queryFromBinding ? createNqlBindingSelectPlan(
33818
34176
  bundle.query,
33819
34177
  deps.model,
33820
- scanFilters
33821
- ) : planFn3(bundle.query, this.requireNqlCompileModel(options), {
33822
- ...scanFilters && {
33823
- defaultFilters: scanFilters
34178
+ scanFilters,
34179
+ isLocalSource
34180
+ ) : planInScope2(
34181
+ bundle.query,
34182
+ this.requireNqlCompileModel(options),
34183
+ {
34184
+ ...scanFilters && {
34185
+ defaultFilters: scanFilters
34186
+ },
34187
+ dialectCapabilities: options?.dialectCapabilities ?? this.dialectCapabilities
33824
34188
  },
33825
- dialectCapabilities: options?.dialectCapabilities ?? this.dialectCapabilities
33826
- }));
34189
+ { isLocalSource }
34190
+ ));
33827
34191
  const compiled = compileSelectEnvelope(planReport, options, deps);
33828
34192
  const registeredSource = getNqlBindingProjection(
33829
34193
  bindingProjections,
@@ -33834,7 +34198,8 @@ var PgAdapter = class {
33834
34198
  bundle.query,
33835
34199
  compiled.sql,
33836
34200
  compiled.parameters,
33837
- compiled.hydrationPlan
34201
+ compiled.hydrationPlan,
34202
+ compiled.ast
33838
34203
  ) : compiled;
33839
34204
  }
33840
34205
  if (bundle.cteQuery !== void 0) {
@@ -33937,17 +34302,18 @@ var PgAdapter = class {
33937
34302
  `NQL binding '${name}' has no query intent or runtime rows to materialize.`
33938
34303
  );
33939
34304
  }
33940
- const cteName = quoteIdent(emittedBindName(queryLocal(name)), "alias");
34305
+ const cteName = emittedBindName(queryLocal(name));
34306
+ validateIdentifier(cteName, "alias");
33941
34307
  const bindingBundle = bundle.mutationBindings?.has(name) ? { mutation: bundle.mutationBindings.get(name) } : { query: queryIntent };
33942
- const compiled2 = this.compileNqlBundleLeafEnvelope(
34308
+ const compiled = this.compileNqlBundleLeafEnvelope(
33943
34309
  bindingBundle,
33944
34310
  options,
33945
34311
  new Set(bindingProjections.keys()),
33946
34312
  bindingProjections
33947
34313
  );
33948
- assertRelationalOutput(compiled2.hydrationPlan, "Relational bodies");
34314
+ assertRelationalOutput(compiled.hydrationPlan, "Relational bodies");
33949
34315
  const outputSchema = bundle.bindingOutputSchemas?.get(name);
33950
- const compiledBindingOutputs = compiled2.projection.kind === "known" ? compiled2.projection.outputs : void 0;
34316
+ const compiledBindingOutputs = compiled.projection.kind === "known" ? compiled.projection.outputs : void 0;
33951
34317
  const emittedBindingOutputKeys = outputSchema?.declaredOutputs !== void 0 && compiledBindingOutputs !== void 0 ? new Map(
33952
34318
  outputSchema.columns.map((column2) => {
33953
34319
  const output = compiledBindingOutputs.get(column2) ?? [...compiledBindingOutputs.values()].find(
@@ -33957,21 +34323,27 @@ var PgAdapter = class {
33957
34323
  })
33958
34324
  ) : void 0;
33959
34325
  const bindingProjection = outputSchema?.declaredOutputs !== void 0 ? fromOutputDescriptors({
33960
- sql: compiled2.sql,
33961
- parameters: compiled2.parameters,
34326
+ sql: compiled.sql,
34327
+ parameters: compiled.parameters,
33962
34328
  columns: outputSchema.columns,
33963
34329
  declaredOutputs: outputSchema.declaredOutputs,
33964
34330
  ...emittedBindingOutputKeys !== void 0 && {
33965
34331
  emittedOutputKeys: emittedBindingOutputKeys
33966
34332
  },
33967
- ...compiled2.hydrationPlan !== void 0 && {
33968
- hydrationPlan: compiled2.hydrationPlan
34333
+ ...compiled.hydrationPlan !== void 0 && {
34334
+ hydrationPlan: compiled.hydrationPlan
33969
34335
  }
33970
- }) : compiled2;
34336
+ }) : compiled;
33971
34337
  ctes.push(
33972
- `${cteName} as (${renumberSqlParams2(compiled2.sql, parameters.length)})`
34338
+ commonTableExpression(
34339
+ cteName,
34340
+ shiftParameters(
34341
+ requireStatementAst(compiled, `NQL binding '${name}'`),
34342
+ parameters.length
34343
+ )
34344
+ )
33973
34345
  );
33974
- parameters.push(...compiled2.parameters);
34346
+ parameters.push(...compiled.parameters);
33975
34347
  bindingProjections.set(name, bindingProjection);
33976
34348
  }
33977
34349
  const leafBundle = {
@@ -33990,19 +34362,25 @@ var PgAdapter = class {
33990
34362
  bindingNames,
33991
34363
  bindingProjections
33992
34364
  );
33993
- const compiled = finalizeEnvelope(compiledEnvelope);
33994
34365
  if (ctes.length === 0) {
33995
- return guardCompiledQuery(compiled, "NQL bundle");
34366
+ return guardCompiledQuery(
34367
+ finalizeEnvelope(compiledEnvelope),
34368
+ "NQL bundle"
34369
+ );
33996
34370
  }
34371
+ const ast = withLeadingCtes(
34372
+ shiftParameters(
34373
+ requireStatementAst(compiledEnvelope, "the final NQL statement"),
34374
+ parameters.length
34375
+ ),
34376
+ ctes
34377
+ );
33997
34378
  return guardCompiledQuery(
33998
- preserveOutputKeyMap(
33999
- compiled,
34000
- rebuildCompiledQuery(compiled, {
34001
- sql: prefixNqlBindingCtes(
34002
- ctes,
34003
- renumberSqlParams2(compiled.sql, parameters.length)
34004
- ),
34005
- parameters: [...parameters, ...compiled.parameters]
34379
+ finalizeEnvelope(
34380
+ preserveOneToOne(compiledEnvelope, {
34381
+ sql: deparseQuoted(ast),
34382
+ parameters: [...parameters, ...compiledEnvelope.parameters],
34383
+ ast
34006
34384
  })
34007
34385
  ),
34008
34386
  "NQL bundle"
@@ -34112,7 +34490,7 @@ var PgAdapter = class {
34112
34490
  // case 'selectCustomExpression').
34113
34491
  compileSubquery(query, paramOffset) {
34114
34492
  if (deps.model !== void 0) {
34115
- const issued = planFn3(query, deps.model, {
34493
+ const issued = planFn2(query, deps.model, {
34116
34494
  ...options?.defaultFilters && {
34117
34495
  defaultFilters: options.defaultFilters
34118
34496
  },
@@ -34376,13 +34754,24 @@ var PgAdapter = class {
34376
34754
  bindingProjections
34377
34755
  );
34378
34756
  const queryFromBinding = hasBindingName(bindingNames, query.from);
34379
- const issuedPlan = getRelationalReadPlan3(query, queryFromBinding);
34380
- const planReport = issuedPlan ?? (queryFromBinding ? createNqlBindingSelectPlan(query, model, options?.defaultFilters) : planFn3(query, model, {
34381
- ...options?.defaultFilters && {
34382
- defaultFilters: options.defaultFilters
34757
+ const isLocalSource = localSourcePredicate(bindingNames, deps.scope);
34758
+ const issuedPlan = getRelationalReadPlan2(query, queryFromBinding);
34759
+ const planReport = issuedPlan ?? (queryFromBinding ? createNqlBindingSelectPlan(
34760
+ query,
34761
+ model,
34762
+ options?.defaultFilters,
34763
+ isLocalSource
34764
+ ) : planInScope2(
34765
+ query,
34766
+ model,
34767
+ {
34768
+ ...options?.defaultFilters && {
34769
+ defaultFilters: options.defaultFilters
34770
+ },
34771
+ dialectCapabilities: options?.dialectCapabilities ?? this.dialectCapabilities
34383
34772
  },
34384
- dialectCapabilities: options?.dialectCapabilities ?? this.dialectCapabilities
34385
- }));
34773
+ { isLocalSource }
34774
+ ));
34386
34775
  const compiled = compileSelectEnvelope(planReport, leafOptions, deps);
34387
34776
  const registeredSource = getNqlBindingProjection(
34388
34777
  bindingProjections,
@@ -34393,7 +34782,8 @@ var PgAdapter = class {
34393
34782
  query,
34394
34783
  compiled.sql,
34395
34784
  compiled.parameters,
34396
- compiled.hydrationPlan
34785
+ compiled.hydrationPlan,
34786
+ compiled.ast
34397
34787
  ) : compiled;
34398
34788
  };
34399
34789
  const envelope = compileSetOperationEnvelope(intent, compileFn);
@@ -59312,8 +59702,6 @@ export {
59312
59702
  generateMigrationSQL2,
59313
59703
  generateDownSQL2,
59314
59704
  introspect,
59315
- compileSetOperation,
59316
- createLeafCompileFn,
59317
59705
  buildDeclareCursor,
59318
59706
  buildFetch,
59319
59707
  buildCloseCursor,
@@ -59463,4 +59851,4 @@ export {
59463
59851
  planPgTransitionRun,
59464
59852
  applyPgTransitionRun
59465
59853
  };
59466
- //# sourceMappingURL=chunk-WGJ4IBEN.js.map
59854
+ //# sourceMappingURL=chunk-GTX6FAK2.js.map