@dbsp/adapter-pgsql 7.2.0 → 7.3.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
  }
@@ -14133,7 +14163,7 @@ function validateOperators(input) {
14133
14163
  }
14134
14164
  }
14135
14165
  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;
14166
+ 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
14167
  return resolveAddressedColumn(
14138
14168
  { ...operand, range: { ...operand.range, alias } },
14139
14169
  ctx,
@@ -14262,6 +14292,17 @@ function compileResolvedSubqueryBodyUnchecked(body, ctx, state) {
14262
14292
  }
14263
14293
  return { SelectStmt: stmt };
14264
14294
  }
14295
+ function nestedSelect(select, ctx, state) {
14296
+ if (!ctx.compileNestedSelect)
14297
+ throw new Error(
14298
+ "An expression subquery reached the adapter without its nested select."
14299
+ );
14300
+ const compiled = ctx.compileNestedSelect(select, ctx);
14301
+ const ast = renumberParamRefsInAst(compiled.ast, state.paramIndex);
14302
+ state.parameters.push(...compiled.parameters);
14303
+ state.paramIndex += compiled.parameters.length;
14304
+ return ast;
14305
+ }
14265
14306
  function compileResolvedExpressionUnchecked(expr, ctx, state) {
14266
14307
  const compile = (e) => compileResolvedExpressionUnchecked(e, ctx, state);
14267
14308
  switch (expr.kind) {
@@ -14323,11 +14364,7 @@ function compileResolvedExpressionUnchecked(expr, ctx, state) {
14323
14364
  return {
14324
14365
  SubLink: {
14325
14366
  subLinkType: "EXPR_SUBLINK",
14326
- subselect: compileResolvedSubqueryBodyUnchecked(
14327
- expr.body,
14328
- ctx,
14329
- state
14330
- )
14367
+ subselect: "select" in expr ? nestedSelect(expr.select, ctx, state) : compileResolvedSubqueryBodyUnchecked(expr.body, ctx, state)
14331
14368
  }
14332
14369
  };
14333
14370
  case "operator": {
@@ -14653,10 +14690,6 @@ function compileResolvedCondition(tree, ctx, state) {
14653
14690
  validateOperators(tree);
14654
14691
  return compileResolvedConditionUnchecked(tree, ctx, state);
14655
14692
  }
14656
- function compileResolvedSubqueryBody(body, ctx, state) {
14657
- validateOperators(body);
14658
- return compileResolvedSubqueryBodyUnchecked(body, ctx, state);
14659
- }
14660
14693
 
14661
14694
  // src/compiler.ts
14662
14695
  import { InvalidOperationError as InvalidOperationError2 } from "@dbsp/core";
@@ -16398,6 +16431,15 @@ function buildCustomFnFilter(filterIntent, ctx, state, conditionCompiler) {
16398
16431
  deriveFkColumnName: ctx.deriveFkColumnName
16399
16432
  },
16400
16433
  compileExpressionSubquery: ctx.compileSubquery,
16434
+ ...ctx.compileNestedSelect !== void 0 && {
16435
+ compileNestedSelect: ctx.compileNestedSelect
16436
+ },
16437
+ ...ctx.enclosingQualifiers !== void 0 && {
16438
+ enclosingQualifiers: ctx.enclosingQualifiers
16439
+ },
16440
+ ...ctx.rootRangeAlias !== void 0 && {
16441
+ rootRangeAlias: ctx.rootRangeAlias
16442
+ },
16401
16443
  paramState: state,
16402
16444
  ...ctx.model !== void 0 && { model: ctx.model },
16403
16445
  ...ctx.declaredNames !== void 0 && {
@@ -17385,6 +17427,15 @@ function createConditionCompiler(createWhereDispatcher2, buildCustomFnFilter3) {
17385
17427
  defaultPkColumnName: ctx.defaultPkColumnName,
17386
17428
  deriveFkColumnName: ctx.deriveFkColumnName,
17387
17429
  compileSubquery: ctx.compileExpressionSubquery,
17430
+ ...ctx.compileNestedSelect !== void 0 && {
17431
+ compileNestedSelect: ctx.compileNestedSelect
17432
+ },
17433
+ ...ctx.enclosingQualifiers !== void 0 && {
17434
+ enclosingQualifiers: ctx.enclosingQualifiers
17435
+ },
17436
+ ...ctx.rootRangeAlias !== void 0 && {
17437
+ rootRangeAlias: ctx.rootRangeAlias
17438
+ },
17388
17439
  ...ctx.resolvedConditions && {
17389
17440
  resolvedConditions: ctx.resolvedConditions
17390
17441
  },
@@ -23655,27 +23706,6 @@ function mergeDuplicateJoinIncludeDecisions(decisions, rootTable) {
23655
23706
  }
23656
23707
  return merged;
23657
23708
  }
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
23709
  function maxParamRefNumber(value) {
23680
23710
  if (value === null || typeof value !== "object") return 0;
23681
23711
  if (Array.isArray(value)) {
@@ -23705,6 +23735,8 @@ var PlanCompiler = class _PlanCompiler {
23705
23735
  bindingNames;
23706
23736
  scope;
23707
23737
  relationTargetProjections;
23738
+ nestedSelectCompiler;
23739
+ localSubtree;
23708
23740
  /** Mutable state shared with extracted condition/value compilation functions */
23709
23741
  state = {
23710
23742
  parameters: [],
@@ -23715,6 +23747,8 @@ var PlanCompiler = class _PlanCompiler {
23715
23747
  };
23716
23748
  /** Track root table for EXISTS FK correlation */
23717
23749
  currentRootTable = "";
23750
+ /** The emitted alias of the root range when it differs from its table (a nested body). */
23751
+ currentRootAlias;
23718
23752
  /** Pending JOINs registered by filter/include strategies (flushed in compileSelect) */
23719
23753
  pendingJoins = [];
23720
23754
  /** Raw JOIN AST nodes from include handlers (e.g., LATERAL) */
@@ -23762,6 +23796,8 @@ var PlanCompiler = class _PlanCompiler {
23762
23796
  this.bindingNames = options.bindingNames;
23763
23797
  this.scope = options.scope;
23764
23798
  this.relationTargetProjections = options.relationTargetProjections;
23799
+ this.nestedSelectCompiler = options.compileNestedSelect;
23800
+ this.localSubtree = options.localSubtree === true;
23765
23801
  }
23766
23802
  childCompilerOptions(overrides = {}) {
23767
23803
  return {
@@ -23785,6 +23821,10 @@ var PlanCompiler = class _PlanCompiler {
23785
23821
  ...this.relationTargetProjections !== void 0 && {
23786
23822
  relationTargetProjections: this.relationTargetProjections
23787
23823
  },
23824
+ ...this.nestedSelectCompiler !== void 0 && {
23825
+ compileNestedSelect: this.nestedSelectCompiler
23826
+ },
23827
+ ...this.localSubtree && { localSubtree: true },
23788
23828
  ...overrides
23789
23829
  };
23790
23830
  }
@@ -23799,7 +23839,7 @@ var PlanCompiler = class _PlanCompiler {
23799
23839
  if (this.currentRootTable.length > 0 && relationBindingFor(this.scope, queryLocal(this.currentRootTable)) === void 0 && declaredRelationBindingFor(this.scope, this.currentRootTable) === void 0) {
23800
23840
  bindings.push(
23801
23841
  relationBinding({
23802
- qualifier: this.tableIdentifier(this.currentRootTable),
23842
+ qualifier: this.currentRootAlias !== void 0 ? queryLocal(this.currentRootAlias) : this.tableIdentifier(this.currentRootTable),
23803
23843
  kind: "declared-table",
23804
23844
  logicalTable: this.currentRootTable
23805
23845
  })
@@ -24141,6 +24181,7 @@ var PlanCompiler = class _PlanCompiler {
24141
24181
  joins: []
24142
24182
  };
24143
24183
  this.currentRootTable = plan.rootTable;
24184
+ this.currentRootAlias = plan.rootAlias;
24144
24185
  this.pendingJoins = [];
24145
24186
  this.rawJoins = [];
24146
24187
  this.keylessJoinProjections.clear();
@@ -24247,6 +24288,10 @@ var PlanCompiler = class _PlanCompiler {
24247
24288
  outerAlias: identifierText(plan.enclosingRanges[0][0].qualifier)
24248
24289
  }
24249
24290
  },
24291
+ ...plan.enclosingQualifiers && {
24292
+ enclosingQualifiers: plan.enclosingQualifiers
24293
+ },
24294
+ ...plan.rootAlias && { rootRangeAlias: plan.rootAlias },
24250
24295
  ...plan.resolvedExecution && { resolvedExecution: true },
24251
24296
  ...plan.directConditions && {
24252
24297
  compileCaseCondition: (intent, ctx, state) => this.compilePositionCondition(intent, plan, ctx, state, "case-when")
@@ -24280,6 +24325,9 @@ var PlanCompiler = class _PlanCompiler {
24280
24325
  ])
24281
24326
  )
24282
24327
  },
24328
+ ...this.nestedSelectCompiler !== void 0 && {
24329
+ compileNestedSelect: this.nestedSelectCompiler
24330
+ },
24283
24331
  compileSubquery: (query, paramOffset, parent, expression) => this.compileExpressionSubquery(
24284
24332
  query,
24285
24333
  paramOffset,
@@ -24305,6 +24353,10 @@ var PlanCompiler = class _PlanCompiler {
24305
24353
  schemaForRangeVar(plan, table2) {
24306
24354
  return hasBindingName(this.scope ?? this.bindingNames, queryLocal(table2)) ? void 0 : plan.schema ?? this.schema;
24307
24355
  }
24356
+ /** A FROM name bound in this query to a local source (an NQL binding, a CTE or a BatchValues range). */
24357
+ isQueryLocalSource(name) {
24358
+ return localSourcePredicate(this.bindingNames, this.scope)(name);
24359
+ }
24308
24360
  isNqlBindingRoot(plan) {
24309
24361
  return hasBindingName(
24310
24362
  this.scope ?? this.bindingNames,
@@ -24695,16 +24747,21 @@ var PlanCompiler = class _PlanCompiler {
24695
24747
  (entry2) => expression !== void 0 && entry2.expression === expression
24696
24748
  );
24697
24749
  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 };
24750
+ const parent2 = parentContext ?? this.createHandlerContext(parentPlan);
24751
+ if (!this.nestedSelectCompiler)
24752
+ throw new Error(
24753
+ "An expression subquery reached the adapter without its nested select."
24754
+ );
24755
+ const compiled = this.nestedSelectCompiler(resolved.select, parent2);
24756
+ return {
24757
+ ast: renumberParamRefsInAst(compiled.ast, paramOffset),
24758
+ parameters: compiled.parameters
24759
+ };
24707
24760
  }
24761
+ if (this.model !== void 0 && parentPlan.directConditions && !this.localSubtree && !this.isQueryLocalSource(query.from))
24762
+ throw new Error(
24763
+ "An expression subquery reached the adapter without its nested select."
24764
+ );
24708
24765
  if (!parentPlan.directConditions) {
24709
24766
  assertNoSelectExpressionCorrelation(query);
24710
24767
  const innerCompiler2 = new _PlanCompiler(this.childCompilerOptions());
@@ -24730,7 +24787,9 @@ var PlanCompiler = class _PlanCompiler {
24730
24787
  const suffix = i === 0 ? "_sq" : `_sq_${i}`;
24731
24788
  rootAlias = `${truncateIdentifier2(query.from, 63 - suffix.length)}${suffix}`;
24732
24789
  }
24733
- const innerCompiler = new _PlanCompiler(this.childCompilerOptions());
24790
+ const innerCompiler = new _PlanCompiler(
24791
+ this.childCompilerOptions({ localSubtree: true })
24792
+ );
24734
24793
  const innerPlan = {
24735
24794
  rootTable: query.from,
24736
24795
  decisions: intentToDecisions(query, query.from, {
@@ -25515,12 +25574,13 @@ var PlanCompiler = class _PlanCompiler {
25515
25574
  */
25516
25575
  compileRelationAwareColumnRef(column2, table2) {
25517
25576
  const dot = column2.lastIndexOf(".");
25577
+ const root = (qualifier) => qualifier === this.currentRootTable && this.currentRootAlias !== void 0 ? this.currentRootAlias : qualifier;
25518
25578
  if (dot !== -1) {
25519
25579
  const relation = column2.slice(0, dot);
25520
25580
  if (relation === this.currentRootTable) {
25521
25581
  return expressionQualifiedColumnRef(
25522
25582
  column2.slice(dot + 1),
25523
- relation,
25583
+ root(relation),
25524
25584
  this.handlerCtx()
25525
25585
  );
25526
25586
  }
@@ -25534,7 +25594,7 @@ var PlanCompiler = class _PlanCompiler {
25534
25594
  this.handlerCtx()
25535
25595
  );
25536
25596
  }
25537
- return table2 === void 0 ? expressionColumnRef(column2, this.handlerCtx()) : expressionQualifiedColumnRef(column2, table2, this.handlerCtx());
25597
+ return table2 === void 0 ? expressionColumnRef(column2, this.handlerCtx()) : expressionQualifiedColumnRef(column2, root(table2), this.handlerCtx());
25538
25598
  }
25539
25599
  /**
25540
25600
  * Compile a single groupBy decision into a ColumnRef AST node.
@@ -26546,7 +26606,12 @@ function compileInsertFrom(config, ctx, state) {
26546
26606
  ];
26547
26607
  }
26548
26608
  let whereClause;
26549
- if (config.where && config.where.length > 0) {
26609
+ if (config.whereCompiler) {
26610
+ whereClause = config.whereCompiler(
26611
+ { ...ctx, currentAlias: sourceAlias },
26612
+ state
26613
+ );
26614
+ } else if (config.where && config.where.length > 0) {
26550
26615
  const dispatch = createWhereDispatcher(compileWhereIntent);
26551
26616
  const subCtx = { ...ctx, currentAlias: sourceAlias };
26552
26617
  if (config.where.length === 1) {
@@ -26623,7 +26688,12 @@ function compileUpsertFrom(config, ctx, state) {
26623
26688
  ];
26624
26689
  }
26625
26690
  let whereClause;
26626
- if (config.where && config.where.length > 0) {
26691
+ if (config.whereCompiler) {
26692
+ whereClause = config.whereCompiler(
26693
+ { ...ctx, currentAlias: sourceAlias },
26694
+ state
26695
+ );
26696
+ } else if (config.where && config.where.length > 0) {
26627
26697
  const dispatch = createWhereDispatcher(compileWhereIntent);
26628
26698
  const subCtx = { ...ctx, currentAlias: sourceAlias };
26629
26699
  if (config.where.length === 1) {
@@ -27108,6 +27178,7 @@ import {
27108
27178
  import {
27109
27179
  copyDefaultFilters,
27110
27180
  getRelationalReadPlan as getRelationalReadPlan3,
27181
+ planInScope as planInScope2,
27111
27182
  resolveReportIncludes as resolveReportIncludes2,
27112
27183
  validateRecursiveSetOperation
27113
27184
  } from "@dbsp/core/internal";
@@ -27124,7 +27195,7 @@ function assertRelationalOutput(plan, context) {
27124
27195
  // src/pgsql-adapter.ts
27125
27196
  import { randomBytes } from "crypto";
27126
27197
  import { isProxy } from "util/types";
27127
- import { POSTGRESQL_CAPABILITIES as POSTGRESQL_CAPABILITIES4, plan as planFn3 } from "@dbsp/core";
27198
+ import { POSTGRESQL_CAPABILITIES as POSTGRESQL_CAPABILITIES4, plan as planFn2 } from "@dbsp/core";
27128
27199
  import { inspectMutationRows as inspectMutationRows2 } from "@dbsp/core/internal";
27129
27200
  import { convertBigintJsReadValue } from "@dbsp/types";
27130
27201
  import {
@@ -28651,7 +28722,7 @@ function assertPlannedReportAuthority(plan) {
28651
28722
  );
28652
28723
  }
28653
28724
  }
28654
- function compileSelectEnvelope(plan, options, deps) {
28725
+ function compileSelectEnvelope(plan, options, deps, nested) {
28655
28726
  const schemaName = deps.schemaName;
28656
28727
  const resolvedModelForCompiler = options?.model ?? deps.model;
28657
28728
  if ([plan.intent, plan.executableIntent].some(
@@ -28694,7 +28765,8 @@ function compileSelectEnvelope(plan, options, deps) {
28694
28765
  },
28695
28766
  ...resolvedModelForCompiler != null && {
28696
28767
  model: resolvedModelForCompiler
28697
- }
28768
+ },
28769
+ compileNestedSelect: nestedSelectCompiler(options, deps)
28698
28770
  };
28699
28771
  const expressionConditions = plan.execution?.expressionConditions?.map(
28700
28772
  (entry2) => ({
@@ -28837,7 +28909,12 @@ function compileSelectEnvelope(plan, options, deps) {
28837
28909
  plan.execution.expressionSubqueries
28838
28910
  )
28839
28911
  },
28840
- ...execIntent.having && { rawHaving: execIntent.having }
28912
+ ...execIntent.having && { rawHaving: execIntent.having },
28913
+ ...nested?.rootAlias !== void 0 && { rootAlias: nested.rootAlias },
28914
+ ...nested && {
28915
+ enclosingRanges: nested.enclosingRanges,
28916
+ enclosingQualifiers: nested.enclosingQualifiers
28917
+ }
28841
28918
  };
28842
28919
  if (resolvedWhere)
28843
28920
  simplifiedPlan = {
@@ -28852,6 +28929,8 @@ function compileSelectEnvelope(plan, options, deps) {
28852
28929
  };
28853
28930
  }
28854
28931
  const result = compilePlan(simplifiedPlan, compilerOptions);
28932
+ if (nested)
28933
+ assertScalarBodyArity(result.ast, plan.rootTable, resolvedModelForCompiler);
28855
28934
  const baseEnv = fromAstProjection({
28856
28935
  sql: result.sql,
28857
28936
  parameters: result.parameters,
@@ -28905,10 +28984,88 @@ function bindExpressionSubqueries(intent, entries) {
28905
28984
  throw new Error(`Missing expression subquery at ${entry2.intentPath}`);
28906
28985
  return {
28907
28986
  expression: node,
28908
- body: entry2.body
28987
+ select: entry2.select
28909
28988
  };
28910
28989
  });
28911
28990
  }
28991
+ function nestedSelectCompiler(options, deps) {
28992
+ return (select, parent) => {
28993
+ const range = select.execution.rootRange;
28994
+ const enclosingQualifiers = new Map(parent.enclosingQualifiers ?? []);
28995
+ const parentRoot = parent.rootRangeAlias ?? parent.rootTable;
28996
+ enclosingQualifiers.set(
28997
+ parentRoot,
28998
+ parent.currentAlias !== void 0 && parent.currentAlias !== parentRoot ? parent.currentAlias : identifierText(
28999
+ declaredRelationBindingFor(parent.scope, parent.rootTable)?.qualifier ?? queryLocal(parentRoot)
29000
+ )
29001
+ );
29002
+ enclosingQualifiers.set(
29003
+ range.alias,
29004
+ range.alias !== range.table ? range.alias : identifierText(
29005
+ resolveDeclaredIdentifier(
29006
+ deps.declaredNames,
29007
+ deps.dbCasing ?? "preserve",
29008
+ { kind: "table", table: range.table }
29009
+ )
29010
+ )
29011
+ );
29012
+ const known = [
29013
+ ...parent.queryRanges ?? [],
29014
+ ...(parent.enclosingRanges ?? []).flat(),
29015
+ ...parent.scope?.bindings.values() ?? []
29016
+ ];
29017
+ const enclosingRanges = select.enclosing.map(
29018
+ (scope) => scope.map((enclosingRange) => {
29019
+ const emitted = enclosingQualifiers.get(enclosingRange.alias) ?? enclosingRange.alias;
29020
+ return known.find(
29021
+ (binding) => identifierText(binding.qualifier) === emitted
29022
+ ) ?? relationBinding({
29023
+ qualifier: queryLocal(emitted),
29024
+ kind: "declared-table",
29025
+ logicalTable: enclosingRange.table
29026
+ });
29027
+ })
29028
+ );
29029
+ const envelope = compileSelectEnvelope(
29030
+ markPlannedReport({
29031
+ rootTable: select.intent.from,
29032
+ decisions: select.decisions,
29033
+ warnings: [],
29034
+ ctes: [],
29035
+ intent: select.intent,
29036
+ execution: select.execution,
29037
+ metadata: {
29038
+ planningTimeMs: 0,
29039
+ relationsAnalyzed: 0,
29040
+ isAmbiguous: false
29041
+ }
29042
+ }),
29043
+ options,
29044
+ deps,
29045
+ {
29046
+ ...range.alias !== range.table && { rootAlias: range.alias },
29047
+ enclosingRanges,
29048
+ enclosingQualifiers
29049
+ }
29050
+ );
29051
+ if (envelope.ast === void 0)
29052
+ throw new Error("A nested select produced no AST.");
29053
+ return { ast: envelope.ast, parameters: envelope.parameters };
29054
+ };
29055
+ }
29056
+ function assertScalarBodyArity(ast, table2, model) {
29057
+ const targets = ast.SelectStmt?.targetList ?? [];
29058
+ const star = model?.getTable(table2)?.columns.length ?? 1;
29059
+ const columns = targets.reduce((n, target) => {
29060
+ const fields = target.ResTarget?.val?.ColumnRef?.fields;
29061
+ const last = Array.isArray(fields) ? fields.at(-1) : void 0;
29062
+ return n + (last !== null && typeof last === "object" && "A_Star" in last ? star : 1);
29063
+ }, 0);
29064
+ if (columns !== 1)
29065
+ throw new Error(
29066
+ `scalar subquery body projects ${columns} columns; a scalar subquery yields one value.`
29067
+ );
29068
+ }
28912
29069
  function planningNodeAtPath(intent, path) {
28913
29070
  let node = intent;
28914
29071
  for (const key of path.replaceAll("[", ".").replaceAll("]", "").split(".")) {
@@ -29059,7 +29216,8 @@ function mutationContext(deps, rootTable, maxRecursiveDepth) {
29059
29216
  ...deps.schemaName !== void 0 && { schema: deps.schemaName },
29060
29217
  maxRecursiveDepth,
29061
29218
  compileCustomFnFilter: buildCustomFnFilter2,
29062
- createWhereDispatcher: () => createWhereDispatcher(compileWhereIntent)
29219
+ createWhereDispatcher: () => createWhereDispatcher(compileWhereIntent),
29220
+ compileNestedSelect: nestedSelectCompiler(void 0, deps)
29063
29221
  };
29064
29222
  }
29065
29223
  function resolveExistsRelation(sourceTable, relation, model) {
@@ -29253,7 +29411,11 @@ function compileInsertFrom2(intent, options, deps) {
29253
29411
  );
29254
29412
  const state = createCompilerState();
29255
29413
  assertNoPathRefInConditionBodies(intent.where);
29256
- const resolvedWhere = intent.where ? resolveExistsIntent(intent.where, intent.source, deps) : void 0;
29414
+ const whereCompiler = resolvedMutationWhere(intent.where, intent.source, {
29415
+ ...deps,
29416
+ ...bindingNames !== void 0 && { bindingNames }
29417
+ });
29418
+ const resolvedWhere = intent.where && !whereCompiler ? resolveExistsIntent(intent.where, intent.source, deps) : void 0;
29257
29419
  const sourceBinding2 = mutationBinding(
29258
29420
  { ...deps, ...bindingNames !== void 0 && { bindingNames } },
29259
29421
  intent.source
@@ -29286,6 +29448,7 @@ function compileInsertFrom2(intent, options, deps) {
29286
29448
  }))
29287
29449
  },
29288
29450
  ...resolvedWhere && { where: [whereIntentAsDecision(resolvedWhere)] },
29451
+ ...whereCompiler && { whereCompiler },
29289
29452
  ...intent.limit !== void 0 && { limit: intent.limit },
29290
29453
  ...intent.returning && { returning: [...intent.returning] },
29291
29454
  ...intent.returning && {
@@ -29324,7 +29487,10 @@ function resolvedMutationWhere(where, table2, deps) {
29324
29487
  root,
29325
29488
  [root],
29326
29489
  allocator,
29327
- deps.model
29490
+ deps.model,
29491
+ 0,
29492
+ [],
29493
+ localSourcePredicate(deps.bindingNames, deps.scope)
29328
29494
  );
29329
29495
  if (!resolved) {
29330
29496
  throw new Error(
@@ -29415,7 +29581,16 @@ function compileBatchUpdate(intent, options, deps) {
29415
29581
  value
29416
29582
  })) : void 0;
29417
29583
  let whereGuard;
29418
- if (intent.where) {
29584
+ const guardCompiler = resolvedMutationWhere(intent.where, intent.table, deps);
29585
+ if (guardCompiler)
29586
+ whereGuard = guardCompiler(
29587
+ {
29588
+ ...ctx,
29589
+ currentAlias: declaredMutationTableMetadata(deps, intent.table)?.physicalName ?? declaredMutationTable(deps, intent.table)
29590
+ },
29591
+ state
29592
+ );
29593
+ else if (intent.where) {
29419
29594
  assertNoPathRefInConditionBodies(intent.where);
29420
29595
  const resolvedWhere = resolveExistsIntent(intent.where, intent.table, deps);
29421
29596
  const whereCtx = {
@@ -29681,7 +29856,11 @@ function compileUpsertFrom2(intent, options, deps) {
29681
29856
  );
29682
29857
  const state = createCompilerState();
29683
29858
  assertNoPathRefInConditionBodies(intent.where);
29684
- const resolvedWhere = intent.where ? resolveExistsIntent(intent.where, intent.source, deps) : void 0;
29859
+ const whereCompiler = resolvedMutationWhere(intent.where, intent.source, {
29860
+ ...deps,
29861
+ ...bindingNames !== void 0 && { bindingNames }
29862
+ });
29863
+ const resolvedWhere = intent.where && !whereCompiler ? resolveExistsIntent(intent.where, intent.source, deps) : void 0;
29685
29864
  let columns;
29686
29865
  if (intent.columns) {
29687
29866
  columns = [...intent.columns];
@@ -29729,6 +29908,7 @@ function compileUpsertFrom2(intent, options, deps) {
29729
29908
  }))
29730
29909
  },
29731
29910
  ...resolvedWhere && { where: [whereIntentAsDecision(resolvedWhere)] },
29911
+ ...whereCompiler && { whereCompiler },
29732
29912
  ...intent.limit !== void 0 && { limit: intent.limit },
29733
29913
  ...intent.returning && { returning: [...intent.returning] },
29734
29914
  ...intent.returning && {
@@ -29752,10 +29932,10 @@ function compileUpsertFrom2(intent, options, deps) {
29752
29932
  // src/adapter-compiler-recursive.ts
29753
29933
  import {
29754
29934
  getRelationalReadPlan,
29935
+ planInScope,
29755
29936
  resolveReportIncludes
29756
29937
  } from "@dbsp/core/internal";
29757
29938
  import { markPlannedReport as markPlannedReport2 } from "@dbsp/types/internal";
29758
- import { plan as planFn2 } from "@dbsp/core";
29759
29939
  function withBindingProjectionScope(deps, bindingNames, projections) {
29760
29940
  const scope = queryScopeForBindingProjections(bindingNames, projections);
29761
29941
  return {
@@ -29769,10 +29949,11 @@ function getRegisteredProjection(registry, name) {
29769
29949
  if (registry.size === 0) return void 0;
29770
29950
  return registry.get(name);
29771
29951
  }
29772
- function createPlanReportForQuery(query, model, defaultFilters) {
29952
+ function createPlanReportForQuery(query, model, defaultFilters, isLocalSource) {
29773
29953
  const resolution = resolveReportIncludes(query, [], model, {
29774
29954
  ...defaultFilters && { defaultFilters },
29775
- skipRootDefaultFilter: true
29955
+ skipRootDefaultFilter: true,
29956
+ isLocalSource
29776
29957
  });
29777
29958
  return markPlannedReport2({
29778
29959
  rootTable: query.from,
@@ -29793,20 +29974,36 @@ function createPlanReportForQuery(query, model, defaultFilters) {
29793
29974
  }
29794
29975
  function createPlanReportForCteQuery(query, deps, hasRegisteredSource = false) {
29795
29976
  const queryLocalSource = hasRegisteredSource || hasBindingName(deps.bindingNames, query.from);
29977
+ const isLocalSource = localSourcePredicate(deps.bindingNames, deps.scope);
29796
29978
  const issued = getRelationalReadPlan(query, queryLocalSource);
29797
29979
  if (issued) return issued;
29798
29980
  if (queryLocalSource) {
29799
- return createPlanReportForQuery(query, deps.model, deps.defaultFilters);
29981
+ return createPlanReportForQuery(
29982
+ query,
29983
+ deps.model,
29984
+ deps.defaultFilters,
29985
+ isLocalSource
29986
+ );
29800
29987
  }
29801
29988
  if (deps.model === void 0 || deps.model.getTable(query.from) === void 0) {
29802
- return createPlanReportForQuery(query, deps.model, deps.defaultFilters);
29989
+ return createPlanReportForQuery(
29990
+ query,
29991
+ deps.model,
29992
+ deps.defaultFilters,
29993
+ isLocalSource
29994
+ );
29803
29995
  }
29804
- return planFn2(query, deps.model, {
29805
- ...deps.defaultFilters && { defaultFilters: deps.defaultFilters },
29806
- ...deps.dialectCapabilities !== void 0 && {
29807
- dialectCapabilities: deps.dialectCapabilities
29808
- }
29809
- });
29996
+ return planInScope(
29997
+ query,
29998
+ deps.model,
29999
+ {
30000
+ ...deps.defaultFilters && { defaultFilters: deps.defaultFilters },
30001
+ ...deps.dialectCapabilities !== void 0 && {
30002
+ dialectCapabilities: deps.dialectCapabilities
30003
+ }
30004
+ },
30005
+ { isLocalSource }
30006
+ );
29810
30007
  }
29811
30008
  function dbOutputKey(name) {
29812
30009
  return name;
@@ -29957,7 +30154,7 @@ function rehomeQueryEnvelope(source, query, compiled, sql, parameters) {
29957
30154
  compiled.hydrationPlan
29958
30155
  );
29959
30156
  }
29960
- function compileRecursive(report, model, _options, deps) {
30157
+ function compileRecursive(report, model, options, deps) {
29961
30158
  const schemaName = deps.schemaName;
29962
30159
  const state = createCompilerState();
29963
30160
  const intent = report.intent;
@@ -30030,7 +30227,8 @@ function compileRecursive(report, model, _options, deps) {
30030
30227
  ...schemaName !== void 0 && { schema: schemaName },
30031
30228
  maxRecursiveDepth: intent.maxDepth,
30032
30229
  compileCustomFnFilter: buildCustomFnFilter2,
30033
- createWhereDispatcher: () => createWhereDispatcher(compileWhereIntent)
30230
+ createWhereDispatcher: () => createWhereDispatcher(compileWhereIntent),
30231
+ compileNestedSelect: nestedSelectCompiler(options, deps)
30034
30232
  };
30035
30233
  const startSelect = intent.start.select ?? [];
30036
30234
  const nodeIdColumn = intent.start.nodeIdExpr.kind === "column" ? intent.start.nodeIdExpr.name : pkColumn;
@@ -30123,7 +30321,8 @@ function compileRecursive(report, model, _options, deps) {
30123
30321
  ...schemaName !== void 0 && { schema: schemaName },
30124
30322
  maxRecursiveDepth: intent.maxDepth,
30125
30323
  compileCustomFnFilter: buildCustomFnFilter2,
30126
- createWhereDispatcher: () => createWhereDispatcher(compileWhereIntent)
30324
+ createWhereDispatcher: () => createWhereDispatcher(compileWhereIntent),
30325
+ compileNestedSelect: nestedSelectCompiler(options, deps)
30127
30326
  };
30128
30327
  const startSelect = intent.start.select ?? [];
30129
30328
  const nodeIdColumn = intent.start.nodeIdExpr.kind === "column" ? intent.start.nodeIdExpr.name : pkColumn;
@@ -31966,9 +32165,9 @@ function compileLeafOrBranch(intent, compileFn) {
31966
32165
  }
31967
32166
  return toProjectionEnvelope(compileFn(intent));
31968
32167
  }
31969
- function createLeafCompileFn(adapter, model, planFn4, options) {
32168
+ function createLeafCompileFn(adapter, model, planFn3, options) {
31970
32169
  return (query) => {
31971
- const planReport = getRelationalReadPlan2(query) ?? planFn4(query, model, {
32170
+ const planReport = getRelationalReadPlan2(query) ?? planFn3(query, model, {
31972
32171
  dialectCapabilities: adapter.dialectCapabilities
31973
32172
  });
31974
32173
  return fromCompiledQuery(
@@ -33321,10 +33520,11 @@ function compileNqlRuntimeBindingCte(name, binding, deps, parameterOffset, sourc
33321
33520
  parameters
33322
33521
  };
33323
33522
  }
33324
- function createNqlBindingSelectPlan(query, model, defaultFilters) {
33523
+ function createNqlBindingSelectPlan(query, model, defaultFilters, isLocalSource) {
33325
33524
  const resolution = resolveReportIncludes2(query, [], model, {
33326
33525
  ...defaultFilters && { defaultFilters },
33327
- skipRootDefaultFilter: true
33526
+ skipRootDefaultFilter: true,
33527
+ isLocalSource
33328
33528
  });
33329
33529
  return markPlannedReport3({
33330
33530
  rootTable: query.from,
@@ -33810,6 +34010,7 @@ var PgAdapter = class {
33810
34010
  bindingProjections
33811
34011
  );
33812
34012
  const queryFromBinding = hasBindingName(bindingNames, bundle.query.from);
34013
+ const isLocalSource = localSourcePredicate(bindingNames, deps.scope);
33813
34014
  const scanFilters = options?.defaultFilters ? copyDefaultFilters(
33814
34015
  options.defaultFilters,
33815
34016
  (table2) => !hasBindingName(bindingNames, table2)
@@ -33817,13 +34018,19 @@ var PgAdapter = class {
33817
34018
  const planReport = bundle.plan ?? (queryFromBinding ? createNqlBindingSelectPlan(
33818
34019
  bundle.query,
33819
34020
  deps.model,
33820
- scanFilters
33821
- ) : planFn3(bundle.query, this.requireNqlCompileModel(options), {
33822
- ...scanFilters && {
33823
- defaultFilters: scanFilters
34021
+ scanFilters,
34022
+ isLocalSource
34023
+ ) : planInScope2(
34024
+ bundle.query,
34025
+ this.requireNqlCompileModel(options),
34026
+ {
34027
+ ...scanFilters && {
34028
+ defaultFilters: scanFilters
34029
+ },
34030
+ dialectCapabilities: options?.dialectCapabilities ?? this.dialectCapabilities
33824
34031
  },
33825
- dialectCapabilities: options?.dialectCapabilities ?? this.dialectCapabilities
33826
- }));
34032
+ { isLocalSource }
34033
+ ));
33827
34034
  const compiled = compileSelectEnvelope(planReport, options, deps);
33828
34035
  const registeredSource = getNqlBindingProjection(
33829
34036
  bindingProjections,
@@ -34112,7 +34319,7 @@ var PgAdapter = class {
34112
34319
  // case 'selectCustomExpression').
34113
34320
  compileSubquery(query, paramOffset) {
34114
34321
  if (deps.model !== void 0) {
34115
- const issued = planFn3(query, deps.model, {
34322
+ const issued = planFn2(query, deps.model, {
34116
34323
  ...options?.defaultFilters && {
34117
34324
  defaultFilters: options.defaultFilters
34118
34325
  },
@@ -34376,13 +34583,24 @@ var PgAdapter = class {
34376
34583
  bindingProjections
34377
34584
  );
34378
34585
  const queryFromBinding = hasBindingName(bindingNames, query.from);
34586
+ const isLocalSource = localSourcePredicate(bindingNames, deps.scope);
34379
34587
  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
34588
+ const planReport = issuedPlan ?? (queryFromBinding ? createNqlBindingSelectPlan(
34589
+ query,
34590
+ model,
34591
+ options?.defaultFilters,
34592
+ isLocalSource
34593
+ ) : planInScope2(
34594
+ query,
34595
+ model,
34596
+ {
34597
+ ...options?.defaultFilters && {
34598
+ defaultFilters: options.defaultFilters
34599
+ },
34600
+ dialectCapabilities: options?.dialectCapabilities ?? this.dialectCapabilities
34383
34601
  },
34384
- dialectCapabilities: options?.dialectCapabilities ?? this.dialectCapabilities
34385
- }));
34602
+ { isLocalSource }
34603
+ ));
34386
34604
  const compiled = compileSelectEnvelope(planReport, leafOptions, deps);
34387
34605
  const registeredSource = getNqlBindingProjection(
34388
34606
  bindingProjections,
@@ -59463,4 +59681,4 @@ export {
59463
59681
  planPgTransitionRun,
59464
59682
  applyPgTransitionRun
59465
59683
  };
59466
- //# sourceMappingURL=chunk-WGJ4IBEN.js.map
59684
+ //# sourceMappingURL=chunk-CQSIDXP5.js.map