@aeye/query 0.3.9 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1182,18 +1182,18 @@ async function resolveSemanticRun(semantic2, alias, row, queryVector, ctx) {
1182
1182
  function readFieldText(row, alias, field) {
1183
1183
  const rec = row[alias];
1184
1184
  if (!rec) return "";
1185
- const cell = rec[field];
1186
- if (typeof cell === "string") return cell;
1187
- if (Array.isArray(cell)) return cell.filter((x) => typeof x === "string").join(" ");
1185
+ const cell2 = rec[field];
1186
+ if (typeof cell2 === "string") return cell2;
1187
+ if (Array.isArray(cell2)) return cell2.filter((x) => typeof x === "string").join(" ");
1188
1188
  return "";
1189
1189
  }
1190
1190
  function readFieldVector(row, alias, field) {
1191
1191
  const rec = row[alias];
1192
1192
  if (!rec) return null;
1193
- const cell = rec[field];
1194
- if (!Array.isArray(cell)) return null;
1193
+ const cell2 = rec[field];
1194
+ if (!Array.isArray(cell2)) return null;
1195
1195
  const out = [];
1196
- for (const v of cell) {
1196
+ for (const v of cell2) {
1197
1197
  if (typeof v !== "number") return null;
1198
1198
  out.push(v);
1199
1199
  }
@@ -1295,6 +1295,32 @@ var RelationFieldType = class _RelationFieldType extends FieldType {
1295
1295
  foreignField: fk
1296
1296
  };
1297
1297
  }
1298
+ /**
1299
+ * The UNALIASED, ordered join-key column pairs for this relation — the
1300
+ * composite/backing-aware generalization of {@link resolveKey}. Each pair is
1301
+ * `{ local, foreign }`: `local` a column on THIS Type's side, `foreign` the
1302
+ * matching column on the TARGET (the target's PK field for a belongs-to). Uses
1303
+ * the field's `RelationBacking.keys` when declared, else the single
1304
+ * name-convention pair. Drives relation comparison lowering (`= <> in`).
1305
+ */
1306
+ resolveKeys(engine, relationFieldName, thisType, targetType) {
1307
+ const forward = this.count === 1;
1308
+ let backing;
1309
+ if (forward) {
1310
+ backing = engine.fieldBacking(thisType.name, relationFieldName)?.relation;
1311
+ } else if (this.inverseVia !== void 0) {
1312
+ backing = engine.fieldBacking(targetType.name, this.inverseVia)?.relation;
1313
+ }
1314
+ if (backing?.keys && backing.keys.length > 0) {
1315
+ const targetIdentity = backing.keys.some((k) => k.foreign === void 0) ? (
1316
+ /* v8 ignore next -- a forward=false (has-many) key omitting `foreign` is not reachable via the tested inverse backings */
1317
+ (forward ? targetType : thisType).identityField().name
1318
+ ) : "";
1319
+ return relationKeyColumns(backing.keys, forward, targetIdentity).map((p) => ({ local: p.localField, foreign: p.foreignField }));
1320
+ }
1321
+ const single = this.resolveKey(relationFieldName, thisType, targetType);
1322
+ return [{ local: single.localField, foreign: single.foreignField }];
1323
+ }
1298
1324
  /**
1299
1325
  * Resolve the full join `ON` for this relation hop, consulting the field's
1300
1326
  * DEV-SIDE `RelationBacking` (physical FK columns / custom predicate) and
@@ -1686,6 +1712,10 @@ var Field = class _Field {
1686
1712
  description;
1687
1713
  /** The field's value type. */
1688
1714
  fieldType;
1715
+ /** Explicit average stored bytes, when authored (else the field type's default). */
1716
+ explicitBytes;
1717
+ /** Explicit change interval (ms) for this field, when authored (else the Type's rate). */
1718
+ explicitChanges;
1689
1719
  /** Whether the field may hold null / be absent. */
1690
1720
  nullable;
1691
1721
  /** Whether the field may be supplied on INSERT (default true). */
@@ -1706,6 +1736,8 @@ var Field = class _Field {
1706
1736
  this.label = spec.label;
1707
1737
  this.description = spec.description;
1708
1738
  this.fieldType = spec.fieldType;
1739
+ this.explicitBytes = spec.bytes;
1740
+ this.explicitChanges = spec.changes;
1709
1741
  this.nullable = spec.nullable ?? false;
1710
1742
  this.insertableSet = spec.insertable !== void 0;
1711
1743
  this.updatableSet = spec.updatable !== void 0;
@@ -1716,17 +1748,39 @@ var Field = class _Field {
1716
1748
  }
1717
1749
  /** Build a Field from its JSON, parsing the field type via `registry`. */
1718
1750
  static from(json, registry) {
1751
+ const fieldType = registry.parseFieldType(json.type);
1719
1752
  return new _Field({
1720
1753
  name: json.name,
1721
1754
  label: json.label,
1722
1755
  description: json.description,
1723
- fieldType: registry.parseFieldType(json.type),
1756
+ fieldType,
1757
+ // An explicit per-field `bytes` wins; otherwise a registry-level default for
1758
+ // this field type's kind may apply (else the field type's own avgBytes()).
1759
+ bytes: json.bytes ?? registry.defaultFieldBytes(fieldType.kind),
1760
+ changes: json.changes,
1724
1761
  nullable: json.nullable ?? false,
1725
1762
  insertable: json.insertable,
1726
1763
  updatable: json.updatable,
1727
1764
  exprs: json.exprs
1728
1765
  });
1729
1766
  }
1767
+ /**
1768
+ * Estimated average stored bytes for this field: an explicit authored `bytes`
1769
+ * when present, else the field type's own {@link FieldType.avgBytes} default.
1770
+ * Drives the whole-row and index byte-cost estimates.
1771
+ */
1772
+ bytes() {
1773
+ return this.explicitBytes ?? this.fieldType.avgBytes();
1774
+ }
1775
+ /**
1776
+ * Explicit change interval (ms) for this field, or `undefined` when it inherits
1777
+ * the Type's rate. `0` = always changing, `-1` = never, `60000` = once a
1778
+ * minute. Folded into `engine.changeInterval(query)` to estimate result
1779
+ * freshness.
1780
+ */
1781
+ changes() {
1782
+ return this.explicitChanges;
1783
+ }
1730
1784
  /**
1731
1785
  * Whether this field's TYPE could ever support expr `kind` — the availability
1732
1786
  * floor `allowsExpr` narrows. Type-gated kinds: `array-op` needs an array
@@ -1780,6 +1834,10 @@ var Field = class _Field {
1780
1834
  label: this.label,
1781
1835
  description: this.description,
1782
1836
  type: this.fieldType.toJSON(),
1837
+ // Only emit `bytes` when authored explicitly (a derived default stays implicit).
1838
+ bytes: this.explicitBytes,
1839
+ // Only emit `changes` when authored (it otherwise inherits the Type's rate).
1840
+ changes: this.explicitChanges,
1783
1841
  // Only emit `nullable` when true, keeping the default implicit.
1784
1842
  nullable: this.nullable ? true : void 0,
1785
1843
  // Emit a write flag only when it was set EXPLICITLY (preserving fidelity of
@@ -1796,6 +1854,8 @@ var Field = class _Field {
1796
1854
  label: this.label,
1797
1855
  description: this.description,
1798
1856
  fieldType: this.fieldType.clone(),
1857
+ bytes: this.explicitBytes,
1858
+ changes: this.explicitChanges,
1799
1859
  nullable: this.nullable,
1800
1860
  insertable: this.insertableSet ? this.insertable : void 0,
1801
1861
  updatable: this.updatableSet ? this.updatable : void 0,
@@ -1810,6 +1870,7 @@ var Field = class _Field {
1810
1870
  };
1811
1871
 
1812
1872
  // src/index-spec.ts
1873
+ var NON_FIELD_PART_BYTES = 8;
1813
1874
  function stableStringify(value2) {
1814
1875
  if (value2 === null) return "null";
1815
1876
  if (Array.isArray(value2)) {
@@ -1848,9 +1909,28 @@ var IndexPart = class {
1848
1909
  var Index = class _Index {
1849
1910
  /** The ordered parts of this composite index (at least one). */
1850
1911
  parts;
1851
- /** Construct an index from its ordered parts (at least one). */
1852
- constructor(parts) {
1912
+ /** Explicit average bytes per index entry, when authored (else derived from parts). */
1913
+ explicitBytes;
1914
+ /** Construct an index from its ordered parts (at least one) and optional entry-byte size. */
1915
+ constructor(parts, bytes) {
1853
1916
  this.parts = parts;
1917
+ this.explicitBytes = bytes;
1918
+ }
1919
+ /**
1920
+ * Estimated average bytes of one INDEX ENTRY — an explicit authored `bytes`,
1921
+ * else the SUM of the parts' byte sizes: a field-ref part uses that field's
1922
+ * {@link Field.bytes}; any other expr part uses a small fixed default. Drives
1923
+ * the index-only (covered) scan estimate, where reading index entries is
1924
+ * cheaper than reading whole rows.
1925
+ */
1926
+ bytes(type) {
1927
+ if (this.explicitBytes !== void 0) return this.explicitBytes;
1928
+ let total = 0;
1929
+ for (const part of this.parts) {
1930
+ const field = part.expr.kind === "field-ref" ? type.field(part.expr.field) : void 0;
1931
+ total += field ? field.bytes() : NON_FIELD_PART_BYTES;
1932
+ }
1933
+ return total;
1854
1934
  }
1855
1935
  /**
1856
1936
  * True when a full-key equality lookup yields at most one row — i.e. the
@@ -1880,11 +1960,13 @@ var Index = class _Index {
1880
1960
  }
1881
1961
  /** Build an Index from its `IndexDef` JSON. */
1882
1962
  static from(json) {
1883
- return new _Index(json.exprs.map((p) => new IndexPart(p.expr, p.count)));
1963
+ return new _Index(json.exprs.map((p) => new IndexPart(p.expr, p.count)), json.bytes);
1884
1964
  }
1885
- /** Serialize to its `IndexDef` JSON shape. */
1965
+ /** Serialize to its `IndexDef` JSON shape (emitting `bytes` only when authored explicitly). */
1886
1966
  toJSON() {
1887
- return { exprs: this.parts.map((p) => p.toJSON()) };
1967
+ const def = { exprs: this.parts.map((p) => p.toJSON()) };
1968
+ if (this.explicitBytes !== void 0) def.bytes = this.explicitBytes;
1969
+ return def;
1888
1970
  }
1889
1971
  /** Deep-copy this index (round-trips through JSON). */
1890
1972
  clone() {
@@ -1894,6 +1976,9 @@ var Index = class _Index {
1894
1976
 
1895
1977
  // src/type.ts
1896
1978
  import { z as z12 } from "zod";
1979
+ function noKeyMessage(typeName) {
1980
+ return `Type '${typeName}' needs a primary key (a unique index or an 'id' field) to participate in relations.`;
1981
+ }
1897
1982
  var Type = class _Type {
1898
1983
  /** Type name (unique within the registry). */
1899
1984
  name;
@@ -1909,6 +1994,8 @@ var Type = class _Type {
1909
1994
  count;
1910
1995
  /** Estimated average bytes per row (drives byte-cost estimation). */
1911
1996
  bytes;
1997
+ /** Estimated ms between changes to this Type's data (`0` = always, `-1` = never). */
1998
+ changes;
1912
1999
  /** Whether the whole type is flagged semantic-eligible. */
1913
2000
  semantic;
1914
2001
  /** Whether the whole type is flagged full-text-search-eligible. */
@@ -1927,7 +2014,8 @@ var Type = class _Type {
1927
2014
  this.fields = spec.fields;
1928
2015
  this.indexes = spec.indexes;
1929
2016
  this.count = spec.count;
1930
- this.bytes = spec.bytes;
2017
+ this.bytes = spec.bytes ?? this.fields.reduce((sum2, f) => sum2 + f.bytes(), 0);
2018
+ this.changes = spec.changes ?? 0;
1931
2019
  this.semantic = spec.semantic ?? false;
1932
2020
  this.search = spec.search ?? false;
1933
2021
  this.insertable = spec.insertable ?? true;
@@ -1953,6 +2041,31 @@ var Type = class _Type {
1953
2041
  * a clear error. Relations resolve their keys through this.
1954
2042
  */
1955
2043
  identityField() {
2044
+ const single = this.singleIdentity();
2045
+ if (single) return single;
2046
+ throw new QueryTypeError({ path: [], code: "type.no-identity", severity: "error", message: noKeyMessage(this.name) });
2047
+ }
2048
+ /**
2049
+ * The ordered PRIMARY KEY fields of this Type — generalizing {@link
2050
+ * identityField} to COMPOSITE keys: the single identity field (a single-part
2051
+ * unique index's field, else `id`) when present, else the fields of the first
2052
+ * multi-part UNIQUE index (last part `count === 1`) whose every part is a
2053
+ * field-ref. Relations map their key columns to these; a relation VALUE is
2054
+ * keyed by these field names. Throws when none exists.
2055
+ */
2056
+ primaryKey() {
2057
+ const single = this.singleIdentity();
2058
+ if (single) return [single];
2059
+ for (const idx of this.indexes) {
2060
+ const last = idx.parts[idx.parts.length - 1];
2061
+ if (!last || last.count !== 1) continue;
2062
+ const fields = idx.parts.map((p) => p.expr.kind === "field-ref" ? this.field(p.expr.field) : void 0);
2063
+ if (fields.every((f) => f !== void 0)) return fields;
2064
+ }
2065
+ throw new QueryTypeError({ path: [], code: "type.no-identity", severity: "error", message: noKeyMessage(this.name) });
2066
+ }
2067
+ /** The single identity field: the first single-part unique index's field, else `id`, else undefined. */
2068
+ singleIdentity() {
1956
2069
  for (const idx of this.indexes) {
1957
2070
  if (idx.parts.length !== 1) continue;
1958
2071
  const part = idx.parts[0];
@@ -1961,14 +2074,7 @@ var Type = class _Type {
1961
2074
  const field = this.field(part.expr.field);
1962
2075
  if (field) return field;
1963
2076
  }
1964
- const byName = this.field("id");
1965
- if (byName) return byName;
1966
- throw new QueryTypeError({
1967
- path: [],
1968
- code: "type.no-identity",
1969
- severity: "error",
1970
- message: `Type '${this.name}' needs an identity field (a unique single-field index or an 'id' field) to participate in relations.`
1971
- });
2077
+ return this.field("id");
1972
2078
  }
1973
2079
  /**
1974
2080
  * Fields eligible for semantic-aware querying: text fields flagged
@@ -2005,6 +2111,7 @@ var Type = class _Type {
2005
2111
  indexes,
2006
2112
  count: json.count,
2007
2113
  bytes: json.bytes,
2114
+ changes: json.changes,
2008
2115
  semantic: json.semantic,
2009
2116
  search: json.search,
2010
2117
  insertable: json.insertable,
@@ -2024,6 +2131,8 @@ var Type = class _Type {
2024
2131
  label: z12.string().optional(),
2025
2132
  description: z12.string().optional(),
2026
2133
  type: fieldTypeDefSchema(),
2134
+ bytes: z12.number().optional().describe("Estimated average stored bytes for this field (overrides the field type default)."),
2135
+ changes: z12.number().optional().describe("Ms between changes to this field (overrides the Type; 0 = always, -1 = never)."),
2027
2136
  nullable: z12.boolean().optional(),
2028
2137
  insertable: z12.boolean().optional().describe("Whether the field may be supplied on INSERT (default true)."),
2029
2138
  updatable: z12.boolean().optional().describe("Whether the field may be assigned on UPDATE (default true)."),
@@ -2035,7 +2144,8 @@ var Type = class _Type {
2035
2144
  count: z12.number().describe("Prefix distinct rows up to & including this part; last part 1 \u21D2 unique.")
2036
2145
  }).meta({ aid: "IndexPartDef" }).describe("One ordered part of a composite index.");
2037
2146
  const indexDefSchema = z12.object({
2038
- exprs: z12.array(indexPartDefSchema).describe("Ordered composite-index parts.")
2147
+ exprs: z12.array(indexPartDefSchema).describe("Ordered composite-index parts."),
2148
+ bytes: z12.number().optional().describe("Estimated average bytes per index entry (else derived from the parts).")
2039
2149
  }).meta({ aid: "IndexDef" }).describe("A composite index definition.");
2040
2150
  return z12.object({
2041
2151
  name: z12.string(),
@@ -2044,7 +2154,8 @@ var Type = class _Type {
2044
2154
  fields: z12.array(fieldDefSchema),
2045
2155
  indexes: z12.array(indexDefSchema).optional(),
2046
2156
  count: z12.number().describe("Estimated total row count."),
2047
- bytes: z12.number().describe("Estimated average bytes per row."),
2157
+ bytes: z12.number().optional().describe("Estimated average bytes per row (else derived as the sum of the fields' bytes)."),
2158
+ changes: z12.number().optional().describe("Ms between changes to this Type's data (0 = always changing, -1 = never)."),
2048
2159
  semantic: z12.boolean().optional().describe("Eligible for semantic similarity across the type."),
2049
2160
  search: z12.boolean().optional().describe("Eligible for full-text search across the type."),
2050
2161
  insertable: z12.boolean().optional().describe("Whether rows may be INSERTed (default true)."),
@@ -2064,6 +2175,8 @@ var Type = class _Type {
2064
2175
  indexes: indexes.length > 0 ? indexes : void 0,
2065
2176
  count: this.count,
2066
2177
  bytes: this.bytes,
2178
+ // Emit `changes` only when set away from the default (0 = always changing).
2179
+ changes: this.changes !== 0 ? this.changes : void 0,
2067
2180
  semantic: this.semantic ? true : void 0,
2068
2181
  search: this.search ? true : void 0,
2069
2182
  // Only emit a write flag when RESTRICTED (false), keeping the default implicit.
@@ -2082,6 +2195,7 @@ var Type = class _Type {
2082
2195
  indexes: this.indexes.map((i) => i.clone()),
2083
2196
  count: this.count,
2084
2197
  bytes: this.bytes,
2198
+ changes: this.changes,
2085
2199
  semantic: this.semantic,
2086
2200
  search: this.search,
2087
2201
  insertable: this.insertable,
@@ -2155,7 +2269,27 @@ function assertNever(value2) {
2155
2269
  }
2156
2270
 
2157
2271
  // src/cost.ts
2272
+ function mergeAffected(parts) {
2273
+ const byType = /* @__PURE__ */ new Map();
2274
+ for (const part of parts) {
2275
+ for (const t of part.types) byType.set(t.type, (byType.get(t.type) ?? 0) + t.rows);
2276
+ }
2277
+ const types = [...byType].map(([type, rows]) => ({ type, rows }));
2278
+ return { rows: types.reduce((sum2, t) => sum2 + t.rows, 0), types };
2279
+ }
2280
+ function affectedOne(type, rows) {
2281
+ return rows > 0 ? { rows, types: [{ type, rows }] } : { rows: 0, types: [] };
2282
+ }
2283
+ var AFFECTED_NONE = { rows: 0, types: [] };
2158
2284
  var ZERO_COST = { rows: 0, bytes: 0 };
2285
+ var ALWAYS_CHANGES = 0;
2286
+ var NEVER_CHANGES = -1;
2287
+ function foldChanges(a, b) {
2288
+ if (a === ALWAYS_CHANGES || b === ALWAYS_CHANGES) return ALWAYS_CHANGES;
2289
+ if (a < 0) return b;
2290
+ if (b < 0) return a;
2291
+ return Math.min(a, b);
2292
+ }
2159
2293
  var EQ_SELECTIVITY = 0.33;
2160
2294
  var RANGE_SELECTIVITY = 0.5;
2161
2295
  var IN_SELECTIVITY = 0.5;
@@ -2177,6 +2311,7 @@ function rowsCost(rows, perRowBytes) {
2177
2311
  return { rows: r, bytes: r * Math.max(0, perRowBytes) };
2178
2312
  }
2179
2313
  function bytesOfResolved(rt) {
2314
+ if (rt.kind === "field") return rt.field.bytes();
2180
2315
  return asFieldType(rt)?.avgBytes() ?? 0;
2181
2316
  }
2182
2317
  function reportCostProblems(cost, constraints, p) {
@@ -2319,11 +2454,93 @@ var ROOT_VALIDATE_CONTEXT = {
2319
2454
  inGroupBy: false
2320
2455
  };
2321
2456
  var Expr = class {
2457
+ // ─── Cost analysis surface (composed by the query cost model) ────────────
2458
+ //
2459
+ // These let the WHERE / index cost model in `queries/_cost.ts` ask each expr
2460
+ // about ITSELF instead of switching on its concrete class. Every default here
2461
+ // is the neutral answer; a kind that participates overrides the one method it
2462
+ // has an opinion about.
2463
+ /**
2464
+ * The fraction of scanned rows this predicate KEEPS when used as a WHERE /
2465
+ * HAVING / ON filter (SQL selectivity). `1` = no reduction (the neutral
2466
+ * default). Overridden by the concrete predicates (`comparison` branches on
2467
+ * its own op, `between` / `in` / `is-null` their fixed selectivity, `filters`
2468
+ * delegates to its supplied predicate). Index-covered equality is accounted
2469
+ * for separately by the cost model (via {@link indexProbe}); a predicate need
2470
+ * not discount for it here.
2471
+ */
2472
+ selectivity(_ctx, _scope) {
2473
+ return 1;
2474
+ }
2475
+ /**
2476
+ * A per-SCANNED-ROW byte penalty this node implies beyond its value size — a
2477
+ * proxy for embedding / full-text scan work. `0` (neutral) by default;
2478
+ * `semantic` / `text-search` / `text-score` override. The cost model sums
2479
+ * this across a predicate tree ({@link totalScanRowPenalty}) and multiplies by
2480
+ * the scanned-row count.
2481
+ */
2482
+ scanRowPenalty() {
2483
+ return 0;
2484
+ }
2485
+ /** This node's scan penalty summed over its whole subtree (per scanned row). */
2486
+ totalScanRowPenalty() {
2487
+ let total = 0;
2488
+ this.walk((e2) => {
2489
+ total += e2.scanRowPenalty();
2490
+ });
2491
+ return total;
2492
+ }
2493
+ /**
2494
+ * Flatten a conjunction: the AND-connected predicates this expr contributes to
2495
+ * a WHERE. A leaf reports `[this]`; a nested `and` (`((a AND b) AND c) AND d`)
2496
+ * flattens RECURSIVELY to `[a, b, c, d]`, so the index / selectivity model
2497
+ * sees every top-level conjunct regardless of nesting. A `filters` placeholder
2498
+ * expands to its execution-time predicate's conjuncts (or none). `ctx` /
2499
+ * `scope` are threaded so that expansion can consult the supplied filters.
2500
+ */
2501
+ conjuncts(_ctx, _scope) {
2502
+ return [this];
2503
+ }
2504
+ /**
2505
+ * A SHALLOW index-scannable reading of THIS predicate: the column field-ref it
2506
+ * binds to a bounded value set plus that set's `arity` (`col = v` ⇒ 1;
2507
+ * `col IN (a, b, c)` ⇒ 3), or `undefined` when this predicate is not such a
2508
+ * binding. Overridden by `comparison` (`=`) and `in` (value list). Drives
2509
+ * index-prefix matching without the cost model inspecting operand internals.
2510
+ */
2511
+ indexProbe() {
2512
+ return void 0;
2513
+ }
2514
+ /**
2515
+ * This expr AS a plain column field-ref, or `undefined` when it is anything
2516
+ * else. Overridden by `field-ref` to return itself. Lets the cost model treat
2517
+ * GROUP BY / index keys as columns without an `instanceof`.
2518
+ */
2519
+ fieldRef() {
2520
+ return void 0;
2521
+ }
2522
+ /**
2523
+ * The operands of a disjunction (`OR`), or `undefined` when this is not one.
2524
+ * Overridden by `logical` (`or`). Lets the affected-row estimator union the
2525
+ * branches (index-merge) without inspecting the concrete class.
2526
+ */
2527
+ orOperands() {
2528
+ return void 0;
2529
+ }
2530
+ /**
2531
+ * The registered DB FUNCTION this expr calls, or `undefined` when it is not a
2532
+ * call. Overridden by `function-call` / `aggregate` / `window` / tabular calls.
2533
+ * Lets `Query.references` enumerate invoked functions (and fold their
2534
+ * cost / `changes` / referenced Types) without an `instanceof`.
2535
+ */
2536
+ functionRef() {
2537
+ return void 0;
2538
+ }
2322
2539
  /** Sum the costs of this expr's immediate children (a cost building block). */
2323
- childCost(engine, scope) {
2540
+ childCost(ctx, scope) {
2324
2541
  let c = ZERO_COST;
2325
2542
  this.forEachChild((child) => {
2326
- c = addCost(c, child.cost(engine, scope));
2543
+ c = addCost(c, child.cost(ctx, scope));
2327
2544
  });
2328
2545
  return c;
2329
2546
  }
@@ -2432,8 +2649,8 @@ var BoolExpr = class extends Expr {
2432
2649
  * override this when they imply extra work — `text-search` adds a scan
2433
2650
  * penalty, `in` / `exists` add their subquery's scan cost.
2434
2651
  */
2435
- cost(engine, scope) {
2436
- return this.childCost(engine, scope);
2652
+ cost(ctx, scope) {
2653
+ return this.childCost(ctx, scope);
2437
2654
  }
2438
2655
  /**
2439
2656
  * Default boolean resolution: always a `bool` `ComputedResolved`, with
@@ -2890,7 +3107,8 @@ var LiteralExpr = class _LiteralExpr extends Expr {
2890
3107
  return this.resolve(engine, scope);
2891
3108
  }
2892
3109
  /** Zero rows; cost is just the resolved value's byte size. */
2893
- cost(engine, scope) {
3110
+ cost(ctx, scope) {
3111
+ const engine = ctx.engine;
2894
3112
  return { rows: 0, bytes: bytesOfResolved(this.resolve(engine, scope)) };
2895
3113
  }
2896
3114
  /** Evaluate to the wrapped constant value. */
@@ -3000,9 +3218,9 @@ var OutputRefExpr = class _OutputRefExpr extends Expr {
3000
3218
  return resolved;
3001
3219
  }
3002
3220
  /** Delegate to the target's cost (zero when the reference is unbound). */
3003
- cost(engine, scope) {
3221
+ cost(ctx, scope) {
3004
3222
  const target = scope.output(this.name);
3005
- return target ? target.cost(engine, scope) : ZERO_COST;
3223
+ return target ? target.cost(ctx, scope) : ZERO_COST;
3006
3224
  }
3007
3225
  /** Re-evaluate the referenced output expr over the same row / group. */
3008
3226
  async evaluate(ctx, row, group) {
@@ -3530,6 +3748,18 @@ var QueryOrder = class _QueryOrder {
3530
3748
  (v) => new _QueryOrder(v.expr, v.dir, v.nulls),
3531
3749
  { optional: ["nulls"], aid: "Order" }
3532
3750
  );
3751
+ /**
3752
+ * The per-row cost of this ORDER BY term — just its sort expression's cost.
3753
+ * Mirrors {@link SorterExpr.cost} so a SELECT can cost every `order` entry
3754
+ * uniformly (concrete term or dynamic sorter) without a type check.
3755
+ */
3756
+ cost(ctx, scope) {
3757
+ return this.expr.cost(ctx, scope);
3758
+ }
3759
+ /** The exprs this term reads for `references` — a concrete term is just its own expr. */
3760
+ referenceExprs(_spec) {
3761
+ return [this.expr];
3762
+ }
3533
3763
  /** Serialize back to an `OrderDef`, omitting `nulls` when unset. */
3534
3764
  toJSON() {
3535
3765
  const def = { expr: this.expr.toJSON(), dir: this.dir };
@@ -3717,9 +3947,39 @@ var SorterExpr = class _SorterExpr extends Expr {
3717
3947
  async evaluate(_ctx, _row, _group) {
3718
3948
  return Value.null();
3719
3949
  }
3720
- /** A sorter carries no intrinsic value cost. */
3721
- cost(_engine, _scope) {
3722
- return ZERO_COST;
3950
+ /**
3951
+ * A sorter's cost is the cost of the catalog entries it could sort BY: the
3952
+ * caller's runtime selection ({@link CostContext.sort}) when supplied, else its
3953
+ * `defaultSort`, else — as a worst case — its WHOLE catalog (any entry could be
3954
+ * chosen at execution time). Each contributes its expr's own cost, so a sort
3955
+ * key that is a SUBQUERY makes the sorter expensive (evaluated per sorted row
3956
+ * by the SELECT), while sorting by a plain column stays cheap.
3957
+ */
3958
+ cost(ctx, scope) {
3959
+ let c = ZERO_COST;
3960
+ for (const expr of this.chosenSortExprs(ctx)) c = addCost(c, expr.cost(ctx, scope));
3961
+ return c;
3962
+ }
3963
+ /**
3964
+ * The catalog exprs a cost estimate should charge for: the caller's selected
3965
+ * sorts (when a runtime `sort` is supplied), else the `defaultSort`'s sorts,
3966
+ * else every catalog entry (worst case). Selected names absent from the catalog
3967
+ * are skipped (they cost nothing here; a real run reports them loudly).
3968
+ */
3969
+ chosenSortExprs(ctx) {
3970
+ return this.referenceExprs(ctx.sort);
3971
+ }
3972
+ /**
3973
+ * The catalog exprs a caller's `sort` selection reads (for cost / references):
3974
+ * the selected sorts when a `spec` is supplied, else the `defaultSort`'s sorts,
3975
+ * else every catalog entry (worst case). Selected names absent from the catalog
3976
+ * are skipped.
3977
+ */
3978
+ referenceExprs(spec) {
3979
+ const pick = (entries) => entries.map((s) => this.sorts.get(s.sort)).filter((e2) => e2 !== void 0);
3980
+ if (spec && spec.length > 0) return pick(spec);
3981
+ if (this.defaultSort && this.defaultSort.length > 0) return pick(this.defaultSort);
3982
+ return [...this.sorts.values()];
3723
3983
  }
3724
3984
  /** Dead path (see the note above): the ORDER BY SQL is emitted by `SelectQuery` from the expanded terms; a misplaced sorter is rejected by validation — so this only NULLs defensively. */
3725
3985
  toSQL(_dialect, _ctx) {
@@ -3826,9 +4086,25 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
3826
4086
  );
3827
4087
  return textResult([], true);
3828
4088
  }
3829
- const keyField = ft.resolveKey(this.field, ownerType, target).localField;
3830
- const keyType = (ft.count === 1 ? target : ownerType).identityField().fieldType;
3831
- const relation = { source: this.source, field: this.field, keyField, keyType, to: ft.to };
4089
+ const keys = ft.resolveKeys(engine, this.field, ownerType, target).map((kp) => {
4090
+ const tf = target.field(kp.foreign);
4091
+ let keyType;
4092
+ if (tf && !(tf.fieldType instanceof RelationFieldType)) {
4093
+ keyType = tf.fieldType;
4094
+ } else {
4095
+ keyType = (ft.count === 1 ? target : ownerType).identityField().fieldType;
4096
+ }
4097
+ return { local: kp.local, foreign: kp.foreign, keyType };
4098
+ });
4099
+ const relation = {
4100
+ source: this.source,
4101
+ field: this.field,
4102
+ keyField: keys[0].local,
4103
+ keyType: keys[0].keyType,
4104
+ to: ft.to,
4105
+ count: ft.count,
4106
+ keys
4107
+ };
3832
4108
  const resolved = {
3833
4109
  kind: "type",
3834
4110
  type: target,
@@ -3882,8 +4158,12 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
3882
4158
  return resolved;
3883
4159
  }
3884
4160
  /** Zero rows; cost is just the resolved field's byte size. */
3885
- cost(engine, scope) {
3886
- return { rows: 0, bytes: bytesOfResolved(this.resolve(engine, scope)) };
4161
+ cost(ctx, scope) {
4162
+ return { rows: 0, bytes: bytesOfResolved(this.resolve(ctx.engine, scope)) };
4163
+ }
4164
+ /** A field-ref IS a plain column reference (drives GROUP BY / index-key costing). */
4165
+ fieldRef() {
4166
+ return this;
3887
4167
  }
3888
4168
  /** Read the field's runtime value, honoring backing (joins/compute/access security). */
3889
4169
  async evaluate(ctx, row) {
@@ -4182,7 +4462,8 @@ var ParamExpr = class _ParamExpr extends Expr {
4182
4462
  return this.resolve(engine, scope);
4183
4463
  }
4184
4464
  /** Zero rows; cost is just the resolved type's byte size. */
4185
- cost(engine, scope) {
4465
+ cost(ctx, scope) {
4466
+ const engine = ctx.engine;
4186
4467
  return { rows: 0, bytes: bytesOfResolved(this.resolve(engine, scope)) };
4187
4468
  }
4188
4469
  /** Evaluate to the runtime-bound value for this param name. */
@@ -4191,7 +4472,8 @@ var ParamExpr = class _ParamExpr extends Expr {
4191
4472
  }
4192
4473
  /** Emit as a bound SqlText param slot (null until a value is supplied). */
4193
4474
  toSQL(_dialect, ctx) {
4194
- const value2 = Object.prototype.hasOwnProperty.call(ctx.params, this.name) ? ctx.params[this.name] : null;
4475
+ const raw2 = Object.prototype.hasOwnProperty.call(ctx.params, this.name) ? ctx.params[this.name] : null;
4476
+ const value2 = raw2 !== null && typeof raw2 === "object" ? null : raw2;
4195
4477
  return SqlText.param(value2);
4196
4478
  }
4197
4479
  /** Serialize back to its JSON ExprDef. */
@@ -4325,8 +4607,8 @@ var BinaryExpr = class _BinaryExpr extends Expr {
4325
4607
  return this.resolve(engine, scope);
4326
4608
  }
4327
4609
  /** Cost is the sum of the child operands' costs. */
4328
- cost(engine, scope) {
4329
- return this.childCost(engine, scope);
4610
+ cost(ctx, scope) {
4611
+ return this.childCost(ctx, scope);
4330
4612
  }
4331
4613
  /** Evaluate both operands and apply the op (NULL-propagating; `+` concatenates non-numbers). */
4332
4614
  async evaluate(ctx, row, group) {
@@ -4460,8 +4742,8 @@ var UnaryExpr = class _UnaryExpr extends Expr {
4460
4742
  return this.resolve(engine, scope);
4461
4743
  }
4462
4744
  /** Cost is the operand's cost. */
4463
- cost(engine, scope) {
4464
- return this.childCost(engine, scope);
4745
+ cost(ctx, scope) {
4746
+ return this.childCost(ctx, scope);
4465
4747
  }
4466
4748
  /** Evaluate the operand and apply the sign (NULL/non-numeric → NULL). */
4467
4749
  async evaluate(ctx, row, group) {
@@ -4492,6 +4774,151 @@ var UnaryExpr = class _UnaryExpr extends Expr {
4492
4774
  // src/exprs/comparison.ts
4493
4775
  import { z as z20 } from "zod";
4494
4776
 
4777
+ // src/runtime/tri.ts
4778
+ function not3(a) {
4779
+ return a === void 0 ? void 0 : !a;
4780
+ }
4781
+ function and3(a, b) {
4782
+ if (a === false || b === false) return false;
4783
+ if (a === void 0 || b === void 0) return void 0;
4784
+ return true;
4785
+ }
4786
+ function or3(a, b) {
4787
+ if (a === true || b === true) return true;
4788
+ if (a === void 0 || b === void 0) return void 0;
4789
+ return false;
4790
+ }
4791
+ function triOf(v) {
4792
+ return v.isNull() ? void 0 : v.toBoolean();
4793
+ }
4794
+
4795
+ // src/exprs/_relation-compare.ts
4796
+ var HAS_MANY_ALIAS = "__rel";
4797
+ function relationCompare(operand, engine, typeOf) {
4798
+ const ref3 = operand.fieldRef();
4799
+ if (!ref3) return void 0;
4800
+ const owner = typeOf(ref3.source);
4801
+ if (!owner) return void 0;
4802
+ const field = owner.field(ref3.field);
4803
+ if (!field || !(field.fieldType instanceof RelationFieldType)) return void 0;
4804
+ const ft = field.fieldType;
4805
+ const target = engine.type(ft.to);
4806
+ if (!target) return void 0;
4807
+ return { source: ref3.source, keys: ft.resolveKeys(engine, ref3.field, owner, target), count: ft.count, target };
4808
+ }
4809
+ function runtimeTypeOf(ctx) {
4810
+ return (s) => ctx.sourceType(s) ?? ctx.engine.type(s);
4811
+ }
4812
+ function sqlTypeOf(ctx) {
4813
+ return (s) => {
4814
+ const b = ctx.scope.lookup(s);
4815
+ return b && b.kind === "type" ? b.type : void 0;
4816
+ };
4817
+ }
4818
+ function column(row, source, name, ctx) {
4819
+ const rec = row[source] ?? ctx.correlation?.[source];
4820
+ if (!rec) return Value.null();
4821
+ return cell(rec, name);
4822
+ }
4823
+ async function tuple(operand, rel, keys, row, ctx, group) {
4824
+ if (rel) return rel.keys.map((k) => column(row, rel.source, k.local, ctx));
4825
+ const v = await operand.evaluate(ctx, row, group);
4826
+ if (v.isNull()) return keys.map(() => Value.null());
4827
+ const raw2 = v.raw;
4828
+ if (raw2 !== null && typeof raw2 === "object" && !Array.isArray(raw2)) {
4829
+ const obj2 = raw2;
4830
+ return keys.map((k) => Value.of(obj2[k.foreign] ?? null));
4831
+ }
4832
+ return [v];
4833
+ }
4834
+ function eq3(a, b) {
4835
+ if (a.isNull() || b.isNull()) return void 0;
4836
+ return a.compareTo(b) === 0;
4837
+ }
4838
+ function cell(rec, name) {
4839
+ return Value.of(rec[name] ?? null);
4840
+ }
4841
+ async function evaluateRelationCompare(op, left, right, leftRel, rightRel, row, ctx, group) {
4842
+ const keys = (leftRel ?? rightRel).keys;
4843
+ const lt2 = await tuple(left, leftRel, keys, row, ctx, group);
4844
+ const rt = await tuple(right, rightRel, keys, row, ctx, group);
4845
+ let acc = true;
4846
+ for (let i = 0; i < keys.length; i++) acc = and3(acc, eq3(lt2[i], rt[i]));
4847
+ return op === "=" ? acc : not3(acc);
4848
+ }
4849
+ async function valueTuple(value2, pkFields, row, ctx, group) {
4850
+ const v = await value2.evaluate(ctx, row, group);
4851
+ if (v.isNull()) return pkFields.map(() => Value.null());
4852
+ const raw2 = v.raw;
4853
+ if (raw2 !== null && typeof raw2 === "object" && !Array.isArray(raw2)) {
4854
+ const obj2 = raw2;
4855
+ return pkFields.map((f) => Value.of(obj2[f] ?? null));
4856
+ }
4857
+ return [v];
4858
+ }
4859
+ async function evaluateHasMany(op, rel, value2, row, ctx, group) {
4860
+ const pkFields = rel.target.primaryKey().map((f) => f.name);
4861
+ const outer = rel.keys.map((k) => column(row, rel.source, k.local, ctx));
4862
+ const pkVals = await valueTuple(value2, pkFields, row, ctx, group);
4863
+ if (outer.some((v) => v.isNull()) || pkVals.some((v) => v.isNull())) return op !== "=";
4864
+ const rows = (await ctx.typeState(rel.target)).current;
4865
+ const found = rows.some(
4866
+ (tr) => rel.keys.every((k, i) => eq3(cell(tr, k.foreign), outer[i]) === true) && pkFields.every((f, i) => eq3(cell(tr, f), pkVals[i]) === true)
4867
+ );
4868
+ return op === "=" ? found : !found;
4869
+ }
4870
+ function tupleSql(operand, rel, keys, dialect, ctx) {
4871
+ if (rel) return rel.keys.map((k) => new FieldRefExpr(rel.source, k.local).toSQL(dialect, ctx));
4872
+ if (operand instanceof ParamExpr) {
4873
+ const pv = ctx.params[operand.name];
4874
+ if (pv !== null && pv !== void 0 && typeof pv === "object") {
4875
+ const obj2 = pv;
4876
+ return keys.map((k) => SqlText.param(obj2[k.foreign] ?? null));
4877
+ }
4878
+ return [SqlText.param(pv ?? null)];
4879
+ }
4880
+ return [operand.toSQL(dialect, ctx)];
4881
+ }
4882
+ function emitRelationCompare(op, left, right, leftRel, rightRel, dialect, ctx) {
4883
+ const keys = (leftRel ?? rightRel).keys;
4884
+ const ls = tupleSql(left, leftRel, keys, dialect, ctx);
4885
+ const rs = tupleSql(right, rightRel, keys, dialect, ctx);
4886
+ const eqs = keys.map((_, i) => SqlText.join([ls[i], SqlText.raw("="), rs[i]], " "));
4887
+ const anded = SqlText.join(eqs, " AND ").parens();
4888
+ return op === "=" ? anded : SqlText.concat([SqlText.raw("NOT "), anded]);
4889
+ }
4890
+ function valueComponentsSql(value2, pkFields, ctx) {
4891
+ if (!(value2 instanceof ParamExpr)) return pkFields.map(() => null);
4892
+ const pv = ctx.params[value2.name];
4893
+ if (pv !== null && pv !== void 0 && typeof pv === "object") {
4894
+ const obj2 = pv;
4895
+ return pkFields.map((f) => obj2[f] ?? null);
4896
+ }
4897
+ return [pv ?? null];
4898
+ }
4899
+ function emitHasMany(op, rel, value2, dialect, ctx) {
4900
+ const pkFields = rel.target.primaryKey().map((f) => f.name);
4901
+ const comps = valueComponentsSql(value2, pkFields, ctx);
4902
+ const eq2 = (left, right) => ({ kind: "comparison", op: "=", left, right });
4903
+ const col = (source, field) => ({ kind: "field-ref", source, field });
4904
+ const where = [
4905
+ // Correlation: each has-many key joins the target's FK-back column to this row's identity.
4906
+ ...rel.keys.map((k) => eq2(col(HAS_MANY_ALIAS, k.foreign), col(rel.source, k.local))),
4907
+ // Membership: the target's PK equals the value's components.
4908
+ ...pkFields.map((pk, i) => eq2(col(HAS_MANY_ALIAS, pk), { kind: "literal", value: comps[i] ?? null }))
4909
+ ];
4910
+ const def = {
4911
+ kind: "select",
4912
+ // Project the target's PK column (a bare ref, no bound param) — EXISTS
4913
+ // ignores the projected value, and `SELECT 1` would bind a stray literal.
4914
+ fields: [{ expr: col(HAS_MANY_ALIAS, pkFields[0]) }],
4915
+ from: { kind: "aliased", type: rel.target.name, as: HAS_MANY_ALIAS },
4916
+ where
4917
+ };
4918
+ const sub2 = emitSubquerySQL(dialect, ctx, def);
4919
+ return SqlText.concat([SqlText.raw(op === "=" ? "EXISTS " : "NOT EXISTS "), sub2]);
4920
+ }
4921
+
4495
4922
  // src/exprs/_field-guard.ts
4496
4923
  function operandCtx(operand, kind, ctx, relationOk = false) {
4497
4924
  if (!(operand instanceof FieldRefExpr)) return ctx;
@@ -4561,7 +4988,7 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
4561
4988
  right;
4562
4989
  static KIND = "comparison";
4563
4990
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
4564
- static INSTRUCTIONS = "`left <op> right` \u2192 boolean (`= <> < <= > >=`, `like`, `notLike`, `ilike`). Do NOT compare a RELATION field-ref to an id/scalar (e.g. `salesOrder.customer = customer.id`) \u2014 that is rejected: to correlate, JOIN the relation (`joins:[{on:{kind:'relation',source,field,as}}]`) and compare the joined key. Comparing two relations of the SAME target IS allowed (compared by FK key).";
4991
+ static INSTRUCTIONS = "`left <op> right` \u2192 boolean (`= <> < <= > >=`, `like`, `notLike`, `ilike`). A RELATION field-ref compares by IDENTITY with `=`/`<>` ONLY (ordering / LIKE on a relation is rejected). Its RHS may be (a) another relation of the SAME target \u2014 compared by FK key (`order.customer = invoice.customer`); or (b) a `{ pk }` VALUE param keyed by the target's primary-key fields (`assignedUser = :u` with `:u = {id:5}`); a single-key relation also accepts a bare scalar param. A BELONGS-TO compares the FK columns; a HAS-MANY compares by MEMBERSHIP \u2014 `= value` is TRUE when the value's key is in the related set (correlated EXISTS), `<>` is NOT EXISTS; a has-many may not be compared to another relation. Do NOT compare a relation to a scalar id COLUMN/field-ref (the correlation bug) \u2014 JOIN the relation (`joins:[{on:{kind:'relation',source,field,as}}]`) and compare the joined key.";
4565
4992
  kind = _ComparisonExpr.KIND;
4566
4993
  /** Reconstruct a ComparisonExpr from its JSON def (validates `kind`, recurses into operands via `registry.parseExpr`). */
4567
4994
  static from(json, registry) {
@@ -4613,6 +5040,18 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
4613
5040
  const r = p.at("right", () => this.right.validateWalk(engine, scope, p, operandCtx(this.right, "comparison", ctx, true)));
4614
5041
  const lft = asFieldType(l);
4615
5042
  const rft = asFieldType(r);
5043
+ if (this.op !== "=" && this.op !== "<>" && (relationOf(l) || relationOf(r))) {
5044
+ p.error("comparison.relation-order", `A relation compares by identity \u2014 use '=' or '<>', not '${this.op}'.`);
5045
+ }
5046
+ const lRel = relationOf(l);
5047
+ const rRel = relationOf(r);
5048
+ if (lRel && rRel && (lRel.count > 1 || rRel.count > 1)) {
5049
+ const set = lRel.count > 1 ? lRel : rRel;
5050
+ p.error(
5051
+ "comparison.relation-set",
5052
+ `Has-many relation '${set.source}.${set.field}' compares against a value (its members' key), not another relation ('${(set === lRel ? rRel : lRel).source}.${(set === lRel ? rRel : lRel).field}').`
5053
+ );
5054
+ }
4616
5055
  if (LIKE_OPS.has(this.op)) {
4617
5056
  if (!exempt2(this.left) && categoryOf(l) !== "text") {
4618
5057
  p.at(
@@ -4647,8 +5086,41 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
4647
5086
  }
4648
5087
  return this.resolve(engine, scope);
4649
5088
  }
5089
+ /**
5090
+ * WHERE selectivity by operator: a range (`< <= > >=`) keeps ~half the rows;
5091
+ * equality and the equality-like ops (`= <> like notLike ilike`) keep ~a third.
5092
+ * An index-covered `=` is discounted separately by the cost model (via
5093
+ * {@link indexProbe}); this is the non-indexed fallback.
5094
+ */
5095
+ selectivity() {
5096
+ switch (this.op) {
5097
+ case "<":
5098
+ case "<=":
5099
+ case ">":
5100
+ case ">=":
5101
+ return RANGE_SELECTIVITY;
5102
+ default:
5103
+ return EQ_SELECTIVITY;
5104
+ }
5105
+ }
5106
+ /** An `=` against a column is an index point-probe (arity 1); other ops are not. */
5107
+ indexProbe() {
5108
+ if (this.op !== "=") return void 0;
5109
+ const ref3 = this.left.fieldRef() ?? this.right.fieldRef();
5110
+ return ref3 ? { ref: ref3, arity: 1 } : void 0;
5111
+ }
4650
5112
  /** Evaluate under 3VL: a NULL operand yields UNKNOWN; text compares case-insensitively unless a `sensitive` field is involved. */
4651
5113
  async evaluateBool(ctx, row, group) {
5114
+ if (this.op === "=" || this.op === "<>") {
5115
+ const typeOf = runtimeTypeOf(ctx);
5116
+ const leftRel = relationCompare(this.left, ctx.engine, typeOf);
5117
+ const rightRel = relationCompare(this.right, ctx.engine, typeOf);
5118
+ if (leftRel && leftRel.count > 1) return evaluateHasMany(this.op, leftRel, this.right, row, ctx, group);
5119
+ if (rightRel && rightRel.count > 1) return evaluateHasMany(this.op, rightRel, this.left, row, ctx, group);
5120
+ if (leftRel || rightRel) {
5121
+ return evaluateRelationCompare(this.op, this.left, this.right, leftRel, rightRel, row, ctx, group);
5122
+ }
5123
+ }
4652
5124
  const l = await this.left.evaluate(ctx, row, group);
4653
5125
  const r = await this.right.evaluate(ctx, row, group);
4654
5126
  if (l.isNull() || r.isNull()) return void 0;
@@ -4686,6 +5158,16 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
4686
5158
  }
4687
5159
  /** Emit as a SqlText fragment (ILIKE delegates to the dialect; case-insensitive text wraps both operands in `LOWER(...)`). */
4688
5160
  toSQL(dialect, ctx) {
5161
+ if (this.op === "=" || this.op === "<>") {
5162
+ const typeOf = sqlTypeOf(ctx);
5163
+ const leftRel = relationCompare(this.left, ctx.engine, typeOf);
5164
+ const rightRel = relationCompare(this.right, ctx.engine, typeOf);
5165
+ if (leftRel && leftRel.count > 1) return emitHasMany(this.op, leftRel, this.right, dialect, ctx);
5166
+ if (rightRel && rightRel.count > 1) return emitHasMany(this.op, rightRel, this.left, dialect, ctx);
5167
+ if (leftRel || rightRel) {
5168
+ return emitRelationCompare(this.op, this.left, this.right, leftRel, rightRel, dialect, ctx);
5169
+ }
5170
+ }
4689
5171
  let left = this.left.toSQL(dialect, ctx);
4690
5172
  let right = this.right.toSQL(dialect, ctx);
4691
5173
  if (this.op === "ilike") return dialect.ilike(left, right);
@@ -4720,26 +5202,6 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
4720
5202
 
4721
5203
  // src/exprs/logical.ts
4722
5204
  import { z as z21 } from "zod";
4723
-
4724
- // src/runtime/tri.ts
4725
- function not3(a) {
4726
- return a === void 0 ? void 0 : !a;
4727
- }
4728
- function and3(a, b) {
4729
- if (a === false || b === false) return false;
4730
- if (a === void 0 || b === void 0) return void 0;
4731
- return true;
4732
- }
4733
- function or3(a, b) {
4734
- if (a === true || b === true) return true;
4735
- if (a === void 0 || b === void 0) return void 0;
4736
- return false;
4737
- }
4738
- function triOf(v) {
4739
- return v.isNull() ? void 0 : v.toBoolean();
4740
- }
4741
-
4742
- // src/exprs/logical.ts
4743
5205
  var LOGICAL_OPS = ["and", "or", "not"];
4744
5206
  var LogicalExpr = class _LogicalExpr extends BoolExpr {
4745
5207
  /** Wrap a boolean connective (`and` / `or` / `not`) over its operands. */
@@ -4808,6 +5270,20 @@ var LogicalExpr = class _LogicalExpr extends BoolExpr {
4808
5270
  forEachChild(visit) {
4809
5271
  for (const o of this.operands) visit(o);
4810
5272
  }
5273
+ /**
5274
+ * Flatten an `and` into its constituent conjuncts, RECURSIVELY — so
5275
+ * `((a AND b) AND c) AND d` yields `[a, b, c, d]` and the WHERE cost model sees
5276
+ * every top-level conjunct for selectivity / index matching. `or` / `not` are
5277
+ * opaque (a single conjunct — the default).
5278
+ */
5279
+ conjuncts(ctx, scope) {
5280
+ if (this.op !== "and") return [this];
5281
+ return this.operands.flatMap((o) => o.conjuncts(ctx, scope));
5282
+ }
5283
+ /** An `or` exposes its operands so the affected-row estimator can union the branches. */
5284
+ orOperands() {
5285
+ return this.op === "or" ? this.operands : void 0;
5286
+ }
4811
5287
  /** Validate that each operand is boolean (and that `not` has exactly one operand); resolves to bool. */
4812
5288
  validateWalk(engine, scope, p, ctx) {
4813
5289
  if (this.op === "not" && this.operands.length !== 1) {
@@ -4929,7 +5405,7 @@ var InExpr = class _InExpr extends BoolExpr {
4929
5405
  not;
4930
5406
  static KIND = "in";
4931
5407
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
4932
- static INSTRUCTIONS = "`value IN (list | subquery)` (negatable via `not`): membership test. `in` is EITHER an explicit array of value exprs OR a subquery projecting exactly ONE field (correlated or not). To project a value across a relation, add a `relation` join in the subquery and field-ref the joined alias \u2014 do NOT project/compare a relation field-ref as a scalar id. To correlate the subquery, JOIN the relation and compare the joined key to the outer scalar. Set `not:true` for NOT IN.";
5408
+ static INSTRUCTIONS = "`value IN (list | subquery)` (negatable via `not`): membership test. `in` is EITHER an explicit array of value exprs OR a subquery projecting exactly ONE field (correlated or not). When `value` is a RELATION field-ref, the list holds `{ pk }` VALUE params (or bare scalars for a single-key relation): a belongs-to matches by FK key, a has-many by MEMBERSHIP (\u2208 the related set); `NOT IN` negates. To project a value across a relation in the SUBQUERY form, add a `relation` join and field-ref the joined alias \u2014 do NOT project/compare a relation field-ref as a scalar id. To correlate the subquery, JOIN the relation and compare the joined key to the outer scalar. Set `not:true` for NOT IN.";
4933
5409
  /**
4934
5410
  * Worked examples (see `ExprClass.EXAMPLES`) — the two `in` shapes: an explicit
4935
5411
  * value LIST, and a single-field SUBQUERY that crosses a relation via a
@@ -5095,13 +5571,46 @@ var InExpr = class _InExpr extends BoolExpr {
5095
5571
  return this.resolve(engine, scope);
5096
5572
  }
5097
5573
  /** Estimated cost: children plus the inner query's cost when this is the subquery form. */
5098
- cost(engine, scope) {
5099
- let c = this.childCost(engine, scope);
5100
- if (this.subquery) c = addCost(c, engine.parseQuery(this.subquery).cost(engine, scope.child()));
5574
+ cost(ctx, scope) {
5575
+ let c = this.childCost(ctx, scope);
5576
+ if (this.subquery) c = addCost(c, ctx.engine.parseQuery(this.subquery).cost(ctx, scope.child()));
5101
5577
  return c;
5102
5578
  }
5579
+ /** Membership keeps ~half the rows (matches a non-indexed range's breadth). */
5580
+ selectivity() {
5581
+ return IN_SELECTIVITY;
5582
+ }
5583
+ /**
5584
+ * A `col IN (a, b, c)` value LIST against a column is an index point-probe of
5585
+ * arity = the list length (a `NOT IN` / subquery form is not a point-set).
5586
+ */
5587
+ indexProbe() {
5588
+ if (!this.list || this.not) return void 0;
5589
+ const ref3 = this.value.fieldRef();
5590
+ return ref3 ? { ref: ref3, arity: this.list.length } : void 0;
5591
+ }
5103
5592
  /** Evaluate under 3VL: TRUE if any element equals the value; else UNKNOWN if the value or any element is NULL; else FALSE (negated for `NOT IN`). */
5104
5593
  async evaluateBool(ctx, row, group) {
5594
+ const typeOf = runtimeTypeOf(ctx);
5595
+ const rel = relationCompare(this.value, ctx.engine, typeOf);
5596
+ if (rel && this.list) {
5597
+ if (rel.count > 1) {
5598
+ let found = false;
5599
+ for (const el of this.list) {
5600
+ if (await evaluateHasMany("=", rel, el, row, ctx, group)) {
5601
+ found = true;
5602
+ break;
5603
+ }
5604
+ }
5605
+ return this.not ? !found : found;
5606
+ }
5607
+ let acc = false;
5608
+ for (const el of this.list) {
5609
+ const elRel = relationCompare(el, ctx.engine, typeOf);
5610
+ acc = or3(acc, await evaluateRelationCompare("=", this.value, el, rel, elRel, row, ctx, group));
5611
+ }
5612
+ return this.not ? not3(acc) : acc;
5613
+ }
5105
5614
  const v = await this.value.evaluate(ctx, row, group);
5106
5615
  let matched = false;
5107
5616
  let anyNull = v.isNull();
@@ -5131,6 +5640,15 @@ var InExpr = class _InExpr extends BoolExpr {
5131
5640
  }
5132
5641
  /** Emit as a SqlText fragment (`value [NOT] IN (...)` over a list or an emitted subquery). */
5133
5642
  toSQL(dialect, ctx) {
5643
+ const typeOf = sqlTypeOf(ctx);
5644
+ const rel = relationCompare(this.value, ctx.engine, typeOf);
5645
+ if (rel && this.list) {
5646
+ const ors = rel.count > 1 ? this.list.map((el) => emitHasMany("=", rel, el, dialect, ctx)) : this.list.map(
5647
+ (el) => emitRelationCompare("=", this.value, el, rel, relationCompare(el, ctx.engine, typeOf), dialect, ctx)
5648
+ );
5649
+ const anded = SqlText.join(ors, " OR ").parens();
5650
+ return this.not ? SqlText.concat([SqlText.raw("NOT "), anded]) : anded;
5651
+ }
5134
5652
  const rhs = this.list ? SqlText.join(this.list.map((e2) => e2.toSQL(dialect, ctx)), ", ").parens() : this.subquery ? emitSubquerySQL(dialect, ctx, this.subquery) : SqlText.raw("()");
5135
5653
  return SqlText.join(
5136
5654
  [this.value.toSQL(dialect, ctx), SqlText.raw(this.not ? "NOT IN" : "IN"), rhs],
@@ -5263,6 +5781,10 @@ var BetweenExpr = class _BetweenExpr extends BoolExpr {
5263
5781
  }
5264
5782
  return this.resolve(engine, scope);
5265
5783
  }
5784
+ /** A range test keeps ~half the rows (range selectivity). */
5785
+ selectivity() {
5786
+ return RANGE_SELECTIVITY;
5787
+ }
5266
5788
  /** Evaluate `v >= lo AND v <= hi` under 3VL (a NULL bound makes that side UNKNOWN, but FALSE still dominates); negated for `NOT BETWEEN`. */
5267
5789
  async evaluateBool(ctx, row, group) {
5268
5790
  const v = await this.value.evaluate(ctx, row, group);
@@ -5373,6 +5895,10 @@ var IsNullExpr = class _IsNullExpr extends BoolExpr {
5373
5895
  p.at("value", () => this.value.validateWalk(engine, scope, p, operandCtx(this.value, "is-null", ctx)));
5374
5896
  return this.resolve(engine, scope);
5375
5897
  }
5898
+ /** A null test keeps ~a third of the rows (equality-like selectivity). */
5899
+ selectivity() {
5900
+ return EQ_SELECTIVITY;
5901
+ }
5376
5902
  /** Evaluate the operand and return whether it is (not) null. */
5377
5903
  async evaluateBool(ctx, row, group) {
5378
5904
  const v = await this.value.evaluate(ctx, row, group);
@@ -5520,8 +6046,9 @@ var ExistsExpr = class _ExistsExpr extends BoolExpr {
5520
6046
  return this.resolve(engine, scope);
5521
6047
  }
5522
6048
  /** Estimated cost: the subquery's scan cost (its own output is a single boolean). */
5523
- cost(engine, scope) {
5524
- return engine.parseQuery(this.query).cost(engine, scope.child());
6049
+ cost(ctx, scope) {
6050
+ const engine = ctx.engine;
6051
+ return engine.parseQuery(this.query).cost(ctx, scope.child());
5525
6052
  }
5526
6053
  /** Execute the correlated subquery and return whether it produced any rows (negated for `NOT EXISTS`). */
5527
6054
  async evaluateBool(ctx, row) {
@@ -5907,8 +6434,8 @@ var CaseExpr = class _CaseExpr extends Expr {
5907
6434
  return this.resolve(engine, scope);
5908
6435
  }
5909
6436
  /** Cost is the sum of the child branch costs. */
5910
- cost(engine, scope) {
5911
- return this.childCost(engine, scope);
6437
+ cost(ctx, scope) {
6438
+ return this.childCost(ctx, scope);
5912
6439
  }
5913
6440
  /** Return the first matching branch's result, else the `else` result, else NULL. */
5914
6441
  async evaluate(ctx, row, group) {
@@ -6207,8 +6734,12 @@ var AggregateExpr = class _AggregateExpr extends Expr {
6207
6734
  return this.resolve(engine, scope);
6208
6735
  }
6209
6736
  /** Cost is the per-arg byte cost (or zero for the arg-less `count(*)`). */
6210
- cost(engine, scope) {
6211
- return this.args.size === 0 ? { rows: 0, bytes: 0 } : this.childCost(engine, scope);
6737
+ cost(ctx, scope) {
6738
+ return this.args.size === 0 ? { rows: 0, bytes: 0 } : this.childCost(ctx, scope);
6739
+ }
6740
+ /** This expr calls the aggregate function `fn`. */
6741
+ functionRef() {
6742
+ return this.fn;
6212
6743
  }
6213
6744
  /** Collect each group row's named args (deduped when DISTINCT) and run the registered aggregate. */
6214
6745
  async evaluate(ctx, row, group) {
@@ -6450,8 +6981,12 @@ var WindowExpr = class _WindowExpr extends Expr {
6450
6981
  return this.resolve(engine, scope);
6451
6982
  }
6452
6983
  /** Cost is the sum of the child (args/partition/order) costs. */
6453
- cost(engine, scope) {
6454
- return this.childCost(engine, scope);
6984
+ cost(ctx, scope) {
6985
+ return this.childCost(ctx, scope);
6986
+ }
6987
+ /** This expr calls the window function `fn`. */
6988
+ functionRef() {
6989
+ return this.fn;
6455
6990
  }
6456
6991
  /** Stable string key of the partition-by values for a row. */
6457
6992
  async partitionKey(ctx, row) {
@@ -6667,9 +7202,15 @@ var FunctionCallExpr = class _FunctionCallExpr extends Expr {
6667
7202
  observeNamedParams(this.args, fn2, scope, here);
6668
7203
  return fn2.resolveOutput(argTypes);
6669
7204
  }
6670
- /** Cost is the sum of the argument child costs. */
6671
- cost(engine, scope) {
6672
- return this.childCost(engine, scope);
7205
+ /** Cost is the argument child costs plus any intrinsic cost the function declares. */
7206
+ cost(ctx, scope) {
7207
+ const args = this.childCost(ctx, scope);
7208
+ const fn2 = ctx.engine.lookupFunction(this.fn);
7209
+ return fn2 ? addCost(args, fn2.cost) : args;
7210
+ }
7211
+ /** This expr calls the scalar function `fn`. */
7212
+ functionRef() {
7213
+ return this.fn;
6673
7214
  }
6674
7215
  /** Evaluate the named args and run the registered scalar function. */
6675
7216
  async evaluate(ctx, row, group) {
@@ -6793,10 +7334,16 @@ var TabularFunctionCallExpr = class _TabularFunctionCallExpr extends Expr {
6793
7334
  return this.resolve(engine, scope);
6794
7335
  }
6795
7336
  /** Cost is the output type's row cardinality plus the argument child costs. */
6796
- cost(engine, scope) {
7337
+ cost(ctx, scope) {
7338
+ const engine = ctx.engine;
6797
7339
  const out = this.resolve(engine, scope);
6798
7340
  const base = out.kind === "type" ? { rows: out.type.count, bytes: out.type.count * out.type.bytes } : { rows: 0, bytes: 0 };
6799
- return addCost(base, this.childCost(engine, scope));
7341
+ const fn2 = engine.lookupFunction(this.fn);
7342
+ return addCost(addCost(base, this.childCost(ctx, scope)), fn2 ? fn2.cost : { rows: 0, bytes: 0 });
7343
+ }
7344
+ /** This expr calls the tabular function `fn`. */
7345
+ functionRef() {
7346
+ return this.fn;
6800
7347
  }
6801
7348
  /**
6802
7349
  * Invoke the function's registered runtime implementation to produce rows.
@@ -7053,9 +7600,17 @@ var SemanticExpr = class _SemanticExpr extends Expr {
7053
7600
  p.error("semantic.query-not-semantic", `Field '${q.field}' of '${type.name}' is not semantic.`);
7054
7601
  }
7055
7602
  }
7056
- /** Per-row embedding penalty approximating the scoring work. */
7057
- cost(_engine, _scope) {
7058
- return { rows: 0, bytes: SEMANTIC_ROW_PENALTY };
7603
+ /** A semantic predicate's own value cost is just its operands' (a boolean). */
7604
+ cost(ctx, scope) {
7605
+ return this.childCost(ctx, scope);
7606
+ }
7607
+ /**
7608
+ * Each SCANNED row pays an embedding penalty (a proxy for the similarity
7609
+ * work). Applied per scanned row by the WHERE cost model, rather than folded
7610
+ * once into the value cost (where it was swallowed as a zero-row contribution).
7611
+ */
7612
+ scanRowPenalty() {
7613
+ return SEMANTIC_ROW_PENALTY;
7059
7614
  }
7060
7615
  /**
7061
7616
  * Embed the query side into a vector (null when unavailable), using the
@@ -7435,9 +7990,13 @@ var TextSearchExpr = class _TextSearchExpr extends BoolExpr {
7435
7990
  }
7436
7991
  return this.resolve(engine, scope);
7437
7992
  }
7438
- /** Child cost plus a per-row text-scan penalty. */
7439
- cost(engine, scope) {
7440
- return addCost(this.childCost(engine, scope), { rows: 0, bytes: TEXT_SEARCH_ROW_PENALTY });
7993
+ /** A text-search predicate's own value cost is just its operands' (a boolean). */
7994
+ cost(ctx, scope) {
7995
+ return this.childCost(ctx, scope);
7996
+ }
7997
+ /** Each SCANNED row pays a full-text scan penalty (applied per row by the WHERE cost model). */
7998
+ scanRowPenalty() {
7999
+ return TEXT_SEARCH_ROW_PENALTY;
7441
8000
  }
7442
8001
  /**
7443
8002
  * Basic token match: the searched text matches when it contains every
@@ -7585,9 +8144,13 @@ var TextScoreExpr = class _TextScoreExpr extends Expr {
7585
8144
  }
7586
8145
  return this.resolve(engine, scope);
7587
8146
  }
7588
- /** Child cost plus a per-row text-scan penalty. */
7589
- cost(engine, scope) {
7590
- return addCost(this.childCost(engine, scope), { rows: 0, bytes: TEXT_SEARCH_ROW_PENALTY });
8147
+ /** A text-score's own value cost is just its operands' (it produces a number). */
8148
+ cost(ctx, scope) {
8149
+ return this.childCost(ctx, scope);
8150
+ }
8151
+ /** Scoring implies a full-text scan penalty per scanned row (applied by the WHERE cost model). */
8152
+ scanRowPenalty() {
8153
+ return TEXT_SEARCH_ROW_PENALTY;
7591
8154
  }
7592
8155
  /**
7593
8156
  * A deterministic in-memory relevance in [0, 1]: the FRACTION of the query's
@@ -7726,6 +8289,28 @@ var FiltersExpr = class _FiltersExpr extends BoolExpr {
7726
8289
  }
7727
8290
  return boolResult([], false, false);
7728
8291
  }
8292
+ // ─── Cost ──────────────────────────────────────────────────────────────────
8293
+ /**
8294
+ * Cost of the EXECUTION-TIME predicate bound to this source (from
8295
+ * {@link CostContext.filters}) — so a subquery inside a supplied filter is real
8296
+ * work that raises the estimate. With no predicate supplied the placeholder is
8297
+ * NEUTRAL (zero cost). Its per-row selectivity / penalty / index-probes flow
8298
+ * separately through {@link conjuncts} (the WHERE cost model expands them).
8299
+ */
8300
+ cost(ctx, scope) {
8301
+ const pred = ctx.filters?.get(this.source);
8302
+ return pred ? pred.cost(ctx, scope) : ZERO_COST;
8303
+ }
8304
+ /**
8305
+ * Expand to the supplied predicate's OWN conjuncts, so the WHERE cost model
8306
+ * applies the real filter's selectivity / index-probes / scan penalties as if
8307
+ * it had been authored inline. With no predicate supplied this contributes NO
8308
+ * conjunct (a neutral, always-true placeholder).
8309
+ */
8310
+ conjuncts(ctx, scope) {
8311
+ const pred = ctx.filters?.get(this.source);
8312
+ return pred ? pred.conjuncts(ctx, scope) : [];
8313
+ }
7729
8314
  // ─── Evaluation ────────────────────────────────────────────────────────────
7730
8315
  /**
7731
8316
  * Evaluate the execution-supplied bool expr for this source (TRUE when none).
@@ -7865,8 +8450,9 @@ var SubqueryExpr = class _SubqueryExpr extends Expr {
7865
8450
  return p.at("query", () => validateSubqueryOutput(engine, scope, p, ctx, this.query));
7866
8451
  }
7867
8452
  /** Cost of running the inner query in a child scope. */
7868
- cost(engine, scope) {
7869
- return engine.parseQuery(this.query).cost(engine, scope.child());
8453
+ cost(ctx, scope) {
8454
+ const engine = ctx.engine;
8455
+ return engine.parseQuery(this.query).cost(ctx, scope.child());
7870
8456
  }
7871
8457
  /** Execute the subquery (correlated to `row` when present) and return its first field. */
7872
8458
  async evaluate(ctx, row) {
@@ -7967,7 +8553,8 @@ var ExcludedExpr = class _ExcludedExpr extends Expr {
7967
8553
  return resolved;
7968
8554
  }
7969
8555
  /** Byte cost of the resolved field value (no rows). */
7970
- cost(engine, scope) {
8556
+ cost(ctx, scope) {
8557
+ const engine = ctx.engine;
7971
8558
  return { rows: 0, bytes: bytesOfResolved(this.resolve(engine, scope)) };
7972
8559
  }
7973
8560
  /** Read the proposed row's value for this field (null when absent). */
@@ -8030,6 +8617,49 @@ function exprDefSchema(opts = {}) {
8030
8617
  }
8031
8618
 
8032
8619
  // src/queries/query.ts
8620
+ function mergeReferences(parts) {
8621
+ const types = /* @__PURE__ */ new Set();
8622
+ const functions = /* @__PURE__ */ new Set();
8623
+ const fields = /* @__PURE__ */ new Map();
8624
+ for (const part of parts) {
8625
+ for (const t of part.types) types.add(t);
8626
+ for (const f of part.functions) functions.add(f);
8627
+ for (const fld of part.fields) fields.set(`${fld.type}.${fld.field}`, fld);
8628
+ }
8629
+ return { types: [...types], fields: [...fields.values()], functions: [...functions] };
8630
+ }
8631
+ var ReferenceCollector = class {
8632
+ constructor(engine, scope, seedTypes) {
8633
+ this.engine = engine;
8634
+ this.scope = scope;
8635
+ for (const t of seedTypes) this.types.add(t);
8636
+ }
8637
+ engine;
8638
+ scope;
8639
+ types = /* @__PURE__ */ new Set();
8640
+ fields = /* @__PURE__ */ new Map();
8641
+ functions = /* @__PURE__ */ new Set();
8642
+ /** Inspect ONE expr node: note a function call (+ Types it reads) and, when scoped, a field-ref. */
8643
+ note(n) {
8644
+ const fn2 = n.functionRef();
8645
+ if (fn2 !== void 0) {
8646
+ this.functions.add(fn2);
8647
+ const f = this.engine.lookupFunction(fn2);
8648
+ if (f) for (const t of f.references) this.types.add(t);
8649
+ }
8650
+ if (!this.scope) return;
8651
+ const fr = n.fieldRef();
8652
+ if (!fr) return;
8653
+ const rt = fr.resolve(this.engine, this.scope);
8654
+ if (rt.kind === "field") {
8655
+ this.types.add(rt.type.name);
8656
+ this.fields.set(`${rt.type.name}.${rt.field.name}`, { type: rt.type.name, field: rt.field.name });
8657
+ }
8658
+ }
8659
+ result() {
8660
+ return { types: [...this.types], fields: [...this.fields.values()], functions: [...this.functions] };
8661
+ }
8662
+ };
8033
8663
  var Query = class {
8034
8664
  /**
8035
8665
  * Resolve this query's output as a single `ResolvedType`: the lone field's
@@ -8175,6 +8805,57 @@ var Query = class {
8175
8805
  });
8176
8806
  return out;
8177
8807
  }
8808
+ /**
8809
+ * Estimate the SIZE OF THE RESULT this query returns — output `rows` (capped by
8810
+ * a literal or param-resolved LIMIT / OFFSET) sized by the PROJECTION width,
8811
+ * not the whole scanned row. Distinct from {@link cost} (the WORK to produce
8812
+ * it). The base default is the processing cost; `SelectQuery` / set-operations
8813
+ * / CTEs refine it.
8814
+ */
8815
+ outputCost(ctx, scope) {
8816
+ return this.cost(ctx, scope);
8817
+ }
8818
+ /**
8819
+ * Estimate the rows this statement MUTATES — a total plus a per-Type breakdown
8820
+ * ({@link Affected}). A read-only query is `{ rows: 0, types: [] }` (the
8821
+ * default); INSERT / UPDATE / DELETE name their target Type, and a CTE
8822
+ * statement SUMS its data-modifying entries plus the final query per Type.
8823
+ */
8824
+ affected(_ctx, _scope) {
8825
+ return AFFECTED_NONE;
8826
+ }
8827
+ /**
8828
+ * Enumerate what this query READS — the {@link QueryReferences} of Types,
8829
+ * specific fields, and DB functions it touches — INCLUDING execution-time
8830
+ * `filters` predicates and the `sort`-selected sorter catalog exprs (both from
8831
+ * `ctx`). Drives `engine.changeInterval` (freshness). The base collects Types
8832
+ * (from {@link referencedTypes}) + functions (+ any Types a function reads);
8833
+ * `SelectQuery` / set-ops / CTEs override to add the specific FIELDS read,
8834
+ * resolved against their bound scope ({@link referenceScope}).
8835
+ */
8836
+ references(engine, scope, ctx) {
8837
+ const c = new ReferenceCollector(engine, this.referenceScope(engine, scope), this.referencedTypes());
8838
+ this.forEachReferenceNode(ctx, (n) => c.note(n));
8839
+ if (ctx.filters) for (const pred of ctx.filters.values()) pred.walk((n) => c.note(n));
8840
+ return c.result();
8841
+ }
8842
+ /**
8843
+ * The bound scope a `references` walk resolves its field-refs against, or
8844
+ * `undefined` when this query has no meaningful binding (so field-refs are not
8845
+ * resolved — only Types + functions are collected). Overridden by queries that
8846
+ * bind sources (`SelectQuery` returns its sorter scope).
8847
+ */
8848
+ referenceScope(_engine, _scope) {
8849
+ return void 0;
8850
+ }
8851
+ /**
8852
+ * Visit every expr NODE `references` should inspect. The default recurses every
8853
+ * clause expr ({@link walkExprs}); `SelectQuery` overrides to expand a `sorter`
8854
+ * to only its `ctx.sort`-SELECTED catalog exprs (not the whole catalog).
8855
+ */
8856
+ forEachReferenceNode(_ctx, visit) {
8857
+ this.walkExprs(visit);
8858
+ }
8178
8859
  /**
8179
8860
  * Emit this query as a leading-`WITH`-free BODY plus the TOP-LEVEL CTE
8180
8861
  * definitions it would otherwise prepend itself. The default returns no CTEs
@@ -8843,20 +9524,21 @@ function scanCost(type) {
8843
9524
  function floor1(n) {
8844
9525
  return Math.max(1, n);
8845
9526
  }
8846
- function fieldRefSide(cmp) {
8847
- if (cmp.left instanceof FieldRefExpr) return cmp.left;
8848
- if (cmp.right instanceof FieldRefExpr) return cmp.right;
8849
- return void 0;
9527
+ function conjunctsOf(ctx, scope, where) {
9528
+ return where.flatMap((w) => [...w.conjuncts(ctx, scope)]);
8850
9529
  }
8851
- function equalityFieldRefs(where) {
8852
- const refs = [];
8853
- for (const pred of where) {
8854
- if (pred instanceof ComparisonExpr && pred.op === "=") {
8855
- const fr = fieldRefSide(pred);
8856
- if (fr) refs.push(fr);
8857
- }
9530
+ function probesOf(conjuncts) {
9531
+ const probes = [];
9532
+ for (const c of conjuncts) {
9533
+ const probe = c.indexProbe();
9534
+ if (probe) probes.push(probe);
8858
9535
  }
8859
- return refs;
9536
+ return probes;
9537
+ }
9538
+ function indexPartDigests(type) {
9539
+ const digests = /* @__PURE__ */ new Set();
9540
+ for (const idx of type.indexes) for (const part of idx.parts) digests.add(part.digest);
9541
+ return digests;
8860
9542
  }
8861
9543
  function bestPrefixReduction(type, refs) {
8862
9544
  if (refs.length === 0) return void 0;
@@ -8868,85 +9550,126 @@ function bestPrefixReduction(type, refs) {
8868
9550
  }
8869
9551
  return best;
8870
9552
  }
8871
- function reducePredicate(rows, pred, indexCovered) {
8872
- if (pred instanceof ComparisonExpr) {
8873
- if (pred.op === "=") {
8874
- if (indexCovered && fieldRefSide(pred)) return rows;
8875
- return floor1(rows * EQ_SELECTIVITY);
8876
- }
8877
- if (pred.op === "<" || pred.op === "<=" || pred.op === ">" || pred.op === ">=") {
8878
- return floor1(rows * RANGE_SELECTIVITY);
8879
- }
8880
- return floor1(rows * EQ_SELECTIVITY);
9553
+ function indexArityFactor(partDigests, probes) {
9554
+ let factor = 1;
9555
+ for (const pr of probes) {
9556
+ if (pr.arity > 1 && partDigests.has(exprDigest(pr.ref.toJSON()))) factor *= pr.arity;
8881
9557
  }
8882
- if (pred instanceof BetweenExpr) return floor1(rows * RANGE_SELECTIVITY);
8883
- if (pred instanceof InExpr) return floor1(rows * IN_SELECTIVITY);
8884
- if (pred instanceof IsNullExpr) return floor1(rows * EQ_SELECTIVITY);
9558
+ return factor;
9559
+ }
9560
+ function applyWhere(ctx, scope, base, type, where, perRowBytes) {
9561
+ const conjuncts = conjunctsOf(ctx, scope, where);
9562
+ const rows = reduceRows(ctx, scope, type, base.rows, conjuncts);
9563
+ const penalty = conjuncts.reduce((sum2, c) => sum2 + c.totalScanRowPenalty(), 0) * base.rows;
9564
+ return { rows, bytes: rows * perRowBytes + penalty };
9565
+ }
9566
+ function reduceRows(ctx, scope, type, baseRows, conjuncts) {
9567
+ const probes = probesOf(conjuncts);
9568
+ const partDigests = indexPartDigests(type);
9569
+ const reduction = bestPrefixReduction(type, probes.map((p) => p.ref));
9570
+ let rows = baseRows;
9571
+ for (const c of conjuncts) {
9572
+ const probe = c.indexProbe();
9573
+ if (reduction !== void 0 && probe && partDigests.has(exprDigest(probe.ref.toJSON()))) continue;
9574
+ rows = floor1(rows * c.selectivity(ctx, scope));
9575
+ }
9576
+ if (reduction !== void 0) rows = Math.min(rows, floor1(reduction * indexArityFactor(partDigests, probes)));
8885
9577
  return rows;
8886
9578
  }
8887
- function predicatePenalty(where) {
8888
- let penalty = 0;
8889
- for (const pred of where) {
8890
- pred.walk((e2) => {
8891
- if (e2 instanceof SemanticExpr) penalty += SEMANTIC_ROW_PENALTY;
8892
- else if (e2 instanceof TextSearchExpr) penalty += TEXT_SEARCH_ROW_PENALTY;
8893
- });
8894
- }
8895
- return penalty;
9579
+ function matchedRows(ctx, scope, type, where) {
9580
+ return andMatch(ctx, scope, type, type.count, conjunctsOf(ctx, scope, where));
8896
9581
  }
8897
- function applyWhere(base, type, where, perRowBytes) {
8898
- let rows = base.rows;
8899
- const reduction = bestPrefixReduction(type, equalityFieldRefs(where));
8900
- const indexCovered = reduction !== void 0;
8901
- for (const pred of where) rows = reducePredicate(rows, pred, indexCovered);
8902
- if (reduction !== void 0) rows = Math.min(rows, reduction);
8903
- const penalty = predicatePenalty(where) * base.rows;
8904
- return { rows, bytes: rows * perRowBytes + penalty };
9582
+ function andMatch(ctx, scope, type, base, conjuncts) {
9583
+ const ors = conjuncts.filter((c) => c.orOperands() !== void 0);
9584
+ const rest = conjuncts.filter((c) => c.orOperands() === void 0);
9585
+ let rows = reduceRows(ctx, scope, type, base, rest);
9586
+ for (const or2 of ors) rows = floor1(rows * orFraction(ctx, scope, type, or2));
9587
+ return rows;
9588
+ }
9589
+ function orFraction(ctx, scope, type, orExpr) {
9590
+ let none = 1;
9591
+ for (const operand of orExpr.orOperands()) {
9592
+ const branch = andMatch(ctx, scope, type, type.count, operand.conjuncts(ctx, scope));
9593
+ none *= 1 - branch / type.count;
9594
+ }
9595
+ return 1 - none;
8905
9596
  }
8906
9597
  function distinctEstimate(type, groupBy, scannedRows) {
8907
9598
  if (groupBy.length === 1) {
8908
- const key = groupBy[0];
8909
- if (key instanceof FieldRefExpr) {
8910
- const reduction = bestPrefixReduction(type, [key]);
9599
+ const ref3 = groupBy[0].fieldRef();
9600
+ if (ref3) {
9601
+ const reduction = bestPrefixReduction(type, [ref3]);
8911
9602
  if (reduction !== void 0) return Math.max(1, reduction);
8912
9603
  }
8913
9604
  }
8914
9605
  return Math.max(1, Math.ceil(Math.sqrt(Math.max(1, scannedRows))));
8915
9606
  }
9607
+ function coveredScanBytes(ctx, scope, fromType, fromAlias, fields, where) {
9608
+ const refs = [];
9609
+ let simple = true;
9610
+ const collect = (e2) => {
9611
+ e2.walk((n) => {
9612
+ if (n.cost(ctx, scope).rows > 0) simple = false;
9613
+ const r = n.fieldRef();
9614
+ if (!r) return;
9615
+ if (r.source !== fromAlias) simple = false;
9616
+ else refs.push(r);
9617
+ });
9618
+ };
9619
+ for (const e2 of fields) collect(e2);
9620
+ for (const w of where) collect(w);
9621
+ if (!simple || refs.length === 0) return void 0;
9622
+ const refDigests = new Set(refs.map((r) => exprDigest(r.toJSON())));
9623
+ const probes = probesOf(conjunctsOf(ctx, scope, where));
9624
+ if (probes.length === 0) return void 0;
9625
+ for (const idx of fromType.indexes) {
9626
+ const partDigests = indexPartDigestsOf(idx.parts);
9627
+ const allColumnsIndexed = [...refDigests].every((d) => partDigests.has(d));
9628
+ const whereProbesIndex = probes.some((p) => partDigests.has(exprDigest(p.ref.toJSON())));
9629
+ if (allColumnsIndexed && whereProbesIndex) return idx.bytes(fromType);
9630
+ }
9631
+ return void 0;
9632
+ }
9633
+ function indexPartDigestsOf(parts) {
9634
+ return new Set(parts.map((p) => p.digest));
9635
+ }
8916
9636
  function fanOutCost(exprCost, runs) {
8917
9637
  if (exprCost.rows <= 0) return ZERO_COST;
8918
9638
  const n = Math.max(0, runs);
8919
9639
  return { rows: exprCost.rows * n, bytes: exprCost.bytes * n };
8920
9640
  }
8921
- function backingCost(engine, scope, fieldExprs, fromType, outputRows) {
9641
+ function backingCost(ctx, scope, fieldExprs, fromType, outputRows) {
9642
+ const engine = ctx.engine;
8922
9643
  let cost = ZERO_COST;
8923
9644
  const rlsPred = engine.backing(fromType.name)?.rls()?.expr?.(fromType.name);
8924
9645
  if (rlsPred !== void 0 && typeof rlsPred !== "boolean") {
8925
- cost = addCost(cost, rlsPred.cost(engine, scope));
9646
+ cost = addCost(cost, rlsPred.cost(ctx, scope));
8926
9647
  }
8927
9648
  const counted = /* @__PURE__ */ new Set();
8928
9649
  for (const expr of fieldExprs) {
8929
9650
  expr.walk((e2) => {
8930
- if (!(e2 instanceof FieldRefExpr)) return;
8931
- const bound = scope.lookup(e2.source);
9651
+ const ref3 = e2.fieldRef();
9652
+ if (!ref3) return;
9653
+ const bound = scope.lookup(ref3.source);
8932
9654
  if (!bound || bound.kind !== "type") return;
8933
- const names = engine.fieldBacking(bound.type.name, e2.field)?.joins;
9655
+ const names = engine.fieldBacking(bound.type.name, ref3.field)?.joins;
8934
9656
  if (!names) return;
8935
9657
  for (const name of names) {
8936
- const alias = joinAlias(e2.source, name);
9658
+ const alias = joinAlias(ref3.source, name);
8937
9659
  if (counted.has(alias)) continue;
8938
9660
  counted.add(alias);
8939
9661
  const jb = engine.joinBacking(bound.type.name, name);
8940
9662
  if (!jb?.expr) continue;
8941
- cost = addCost(cost, joinSpecCost(engine, scope, e2.source, jb.expr(e2.source), outputRows));
9663
+ cost = addCost(cost, joinSpecCost(ctx, scope, ref3.source, jb.expr(ref3.source), outputRows));
8942
9664
  }
8943
9665
  });
8944
9666
  }
8945
9667
  return cost;
8946
9668
  }
8947
- function joinSpecCost(engine, scope, outer, spec, outputRows) {
9669
+ function joinSpecCost(ctx, scope, outer, spec, outputRows) {
9670
+ const engine = ctx.engine;
8948
9671
  if (spec.kind === "lateral") {
8949
- const inner = engine.coerceQuery(spec.query(outer)).cost(engine, scope.child());
9672
+ const inner = engine.coerceQuery(spec.query(outer)).cost(ctx, scope.child());
8950
9673
  const runs = Math.max(0, outputRows);
8951
9674
  return { rows: inner.rows * runs, bytes: inner.bytes * runs };
8952
9675
  }
@@ -9387,7 +10110,8 @@ function fieldReadonly(op, typeName, field) {
9387
10110
  function boundSQL(v, ctx) {
9388
10111
  if (v === void 0) return void 0;
9389
10112
  if (typeof v === "number") return SqlText.raw(String(v));
9390
- const value2 = Object.prototype.hasOwnProperty.call(ctx.params, v.name) ? ctx.params[v.name] : null;
10113
+ const raw2 = Object.prototype.hasOwnProperty.call(ctx.params, v.name) ? ctx.params[v.name] : null;
10114
+ const value2 = raw2 !== null && typeof raw2 === "object" ? null : raw2;
9391
10115
  return SqlText.param(value2);
9392
10116
  }
9393
10117
 
@@ -9860,6 +10584,24 @@ var SelectQuery = class _SelectQuery extends Query {
9860
10584
  filterScope(engine, scope) {
9861
10585
  return this.bind(engine, scope).scope;
9862
10586
  }
10587
+ /** Resolve `references` field-refs against FROM + joins + this SELECT's outputs. */
10588
+ referenceScope(engine, scope) {
10589
+ return this.sorterScope(engine, scope);
10590
+ }
10591
+ /**
10592
+ * Visit the nodes `references` inspects: every field / WHERE / GROUP BY /
10593
+ * HAVING / join-`and` expr, plus — for each `order` entry — only the exprs its
10594
+ * `ctx.sort` SELECTION reads (a `sorter` expands to its selected / default /
10595
+ * whole catalog, never blindly all of it).
10596
+ */
10597
+ forEachReferenceNode(ctx, visit) {
10598
+ for (const c of this.fields) c.expr.walk(visit);
10599
+ for (const w of this.where) w.walk(visit);
10600
+ for (const g of this.groupBy) g.walk(visit);
10601
+ for (const h of this.having) h.walk(visit);
10602
+ for (const o of this.order) for (const e2 of o.referenceExprs(ctx.sort)) e2.walk(visit);
10603
+ for (const j of this.joins) if (j.and) j.and.walk(visit);
10604
+ }
9863
10605
  /**
9864
10606
  * The scope a `sorter`'s catalog exprs resolve in for `sorters()` introspection:
9865
10607
  * FROM + joins PLUS this SELECT's outputs (so an `output`-ref sort resolves),
@@ -9953,7 +10695,15 @@ var SelectQuery = class _SelectQuery extends Query {
9953
10695
  * distinct groups (the upstream scan work is unchanged).
9954
10696
  * - LIMIT caps OUTPUT rows. ASSUMPTION: a literal LIMIT also caps how many
9955
10697
  * times a select-position subquery runs (it is evaluated once per RETURNED
9956
- * row); we do not model an ORDER BY forcing a larger upstream scan.
10698
+ * row).
10699
+ * - ORDER BY evaluates each order term (a concrete term or an EXPANDED
10700
+ * `sorter`) once per row reaching the sort — the PRE-LIMIT output count — so
10701
+ * a subquery inside a sort key (or a runtime-selected sorter entry) is real
10702
+ * per-row work; a plain-column sort adds nothing. We do not model an ORDER
10703
+ * BY forcing a larger upstream scan.
10704
+ * - INDEX-ONLY (covered) scan: with no joins / grouping / distinct / aggregate,
10705
+ * when every column referenced in SELECT + WHERE is a part of one index the
10706
+ * WHERE probes, the scan is sized by the index ENTRY bytes, not full rows.
9957
10707
  * - PER-OUTER-ROW work: a subquery / EXISTS / IN-subquery in a SELECT item
9958
10708
  * runs ONCE PER OUTPUT ROW, so its cost is multiplied by the output row
9959
10709
  * count; the same expr in WHERE / HAVING is treated as uncorrelated and
@@ -9961,7 +10711,43 @@ var SelectQuery = class _SelectQuery extends Query {
9961
10711
  * `backingCost` (a LATERAL multiplies per outer row; a shared relation join
9962
10712
  * is counted once).
9963
10713
  */
9964
- cost(engine, scope) {
10714
+ cost(ctx, scope) {
10715
+ const { inner, fromType, perRowBytes, matchedRows: matchedRows2 } = this.matchedEstimate(ctx, scope);
10716
+ const preLimitRows = matchedRows2;
10717
+ const limit = this.boundValue(this.limit, ctx);
10718
+ const outputRows = limit !== void 0 ? Math.min(matchedRows2, limit) : matchedRows2;
10719
+ let cost = { rows: outputRows, bytes: outputRows * perRowBytes };
10720
+ for (const c of this.fields) cost = addCost(cost, fanOutCost(c.expr.cost(ctx, inner), outputRows));
10721
+ for (const w of this.where) cost = addCost(cost, fanOutCost(w.cost(ctx, inner), 1));
10722
+ for (const h of this.having) cost = addCost(cost, fanOutCost(h.cost(ctx, inner), 1));
10723
+ for (const o of this.order) cost = addCost(cost, fanOutCost(o.cost(ctx, inner), preLimitRows));
10724
+ cost = addCost(cost, backingCost(ctx, inner, this.fields.map((c) => c.expr), fromType, outputRows));
10725
+ return cost;
10726
+ }
10727
+ /**
10728
+ * Estimate the RESULT SIZE this SELECT returns: the delivered row count (after
10729
+ * WHERE / GROUP / DISTINCT, then OFFSET dropped and LIMIT capped — each a
10730
+ * literal or a `ctx.params`-resolved value) sized by the PROJECTION width — the
10731
+ * sum of the selected columns' byte widths, NOT the whole scanned row. Contrast
10732
+ * {@link cost}, which totals the WORK (fan-out, subquery scans, penalties).
10733
+ */
10734
+ outputCost(ctx, scope) {
10735
+ const { inner, matchedRows: matchedRows2 } = this.matchedEstimate(ctx, scope);
10736
+ const available = Math.max(0, matchedRows2 - (this.boundValue(this.offset, ctx) ?? 0));
10737
+ const limit = this.boundValue(this.limit, ctx);
10738
+ const rows = limit !== void 0 ? Math.min(available, limit) : available;
10739
+ const width = this.fields.reduce((w, c) => w + bytesOfResolved(c.expr.resolve(ctx.engine, inner)), 0);
10740
+ return { rows, bytes: rows * width };
10741
+ }
10742
+ /**
10743
+ * The shared row estimate both {@link cost} and {@link outputCost} build on:
10744
+ * base scan × join fan-out, reduced by WHERE (index / selectivity), then
10745
+ * collapsed by GROUP BY / a bare aggregate / DISTINCT — the PRE-LIMIT matched
10746
+ * row count — plus the (possibly index-only) per-row scan byte width and the
10747
+ * bound inner scope.
10748
+ */
10749
+ matchedEstimate(ctx, scope) {
10750
+ const engine = ctx.engine;
9965
10751
  const { scope: inner, aliasTypes } = this.bind(engine, scope);
9966
10752
  const fromType = this.from.resolvedType(engine, inner).type;
9967
10753
  let rows = fromType.count;
@@ -9971,10 +10757,14 @@ var SelectQuery = class _SelectQuery extends Query {
9971
10757
  const plan = join2.buildPlan(engine, aliasTypes);
9972
10758
  if (plan) for (const hop of plan) perRowBytes += hop.targetType.bytes;
9973
10759
  }
10760
+ if (!this.joins.length && !this.groupBy.length && !this.distinct && !this.fields.some((c) => c.expr.containsAggregate())) {
10761
+ const covered = coveredScanBytes(ctx, inner, fromType, this.from.alias, this.fields.map((c) => c.expr), this.where);
10762
+ if (covered !== void 0) perRowBytes = covered;
10763
+ }
9974
10764
  const baseScan = scanCost(fromType);
9975
10765
  baseScan.rows = rows;
9976
10766
  baseScan.bytes = rows * perRowBytes;
9977
- let cost = applyWhere(baseScan, fromType, this.where, perRowBytes);
10767
+ let cost = applyWhere(ctx, inner, baseScan, fromType, this.where, perRowBytes);
9978
10768
  if (this.groupBy.length) {
9979
10769
  const distinct = distinctEstimate(fromType, this.groupBy, cost.rows);
9980
10770
  cost = { rows: distinct, bytes: distinct * perRowBytes };
@@ -9984,16 +10774,14 @@ var SelectQuery = class _SelectQuery extends Query {
9984
10774
  const distinct = distinctEstimate(fromType, this.fields.map((c) => c.expr), cost.rows);
9985
10775
  cost = { rows: distinct, bytes: distinct * perRowBytes };
9986
10776
  }
9987
- if (typeof this.limit === "number") {
9988
- const capped = Math.min(cost.rows, this.limit);
9989
- cost = { rows: capped, bytes: capped * perRowBytes };
9990
- }
9991
- const outputRows = cost.rows;
9992
- for (const c of this.fields) cost = addCost(cost, fanOutCost(c.expr.cost(engine, inner), outputRows));
9993
- for (const w of this.where) cost = addCost(cost, fanOutCost(w.cost(engine, inner), 1));
9994
- for (const h of this.having) cost = addCost(cost, fanOutCost(h.cost(engine, inner), 1));
9995
- cost = addCost(cost, backingCost(engine, inner, this.fields.map((c) => c.expr), fromType, outputRows));
9996
- return cost;
10777
+ return { inner, fromType, perRowBytes, matchedRows: cost.rows };
10778
+ }
10779
+ /** Resolve a LIMIT / OFFSET bound to a number: a literal, else a `ctx.params` value, else undefined. */
10780
+ boundValue(v, ctx) {
10781
+ if (v === void 0) return void 0;
10782
+ if (typeof v === "number") return v;
10783
+ const raw2 = ctx.params?.[v.name];
10784
+ return typeof raw2 === "number" ? raw2 : void 0;
9997
10785
  }
9998
10786
  // ─── Execution ─────────────────────────────────────────────────────────
9999
10787
  /** Root Type for join planning (FROM source's type). */
@@ -10753,14 +11541,19 @@ var InsertQuery = class _InsertQuery extends Query {
10753
11541
  return [...out];
10754
11542
  }
10755
11543
  /** Estimate `{ rows, bytes }`: the VALUES row count (or the source query's rows) at the target's per-row size. */
10756
- cost(engine, scope) {
10757
- const type = engine.type(this.into);
11544
+ cost(ctx, scope) {
11545
+ const type = ctx.engine.type(this.into);
10758
11546
  const perRow = type ? type.bytes : 0;
10759
11547
  let rows = 0;
10760
11548
  if (this.rows) rows = this.rows.length;
10761
- else if (this.select) rows = this.select.cost(engine, scope).rows;
11549
+ else if (this.select) rows = this.select.cost(ctx, scope).rows;
10762
11550
  return { rows, bytes: rows * perRow };
10763
11551
  }
11552
+ /** Rows this INSERT adds (on `into`): the VALUES row count, or the source SELECT's output rows. */
11553
+ affected(ctx, scope) {
11554
+ const rows = this.rows ? this.rows.length : this.select ? this.select.outputCost(ctx, scope).rows : 0;
11555
+ return affectedOne(this.into, rows);
11556
+ }
10764
11557
  /** Materialize rows into the target's `TypeState`, applying ON CONFLICT, then project RETURNING. */
10765
11558
  async execute(ctx) {
10766
11559
  const engine = ctx.engine;
@@ -11100,7 +11893,8 @@ var UpdateQuery = class _UpdateQuery extends Query {
11100
11893
  return [this.type];
11101
11894
  }
11102
11895
  /** Estimate `{ rows, bytes }`: the target scan × join fan-out, reduced by WHERE. */
11103
- cost(engine, scope) {
11896
+ cost(ctx, scope) {
11897
+ const engine = ctx.engine;
11104
11898
  const type = engine.type(this.type);
11105
11899
  if (!type) return { rows: 0, bytes: 0 };
11106
11900
  const { aliasTypes } = this.bind(engine, scope);
@@ -11114,7 +11908,13 @@ var UpdateQuery = class _UpdateQuery extends Query {
11114
11908
  const baseScan = scanCost(type);
11115
11909
  baseScan.rows = rows;
11116
11910
  baseScan.bytes = rows * perRowBytes;
11117
- return applyWhere(baseScan, type, this.where, perRowBytes);
11911
+ return applyWhere(ctx, scope, baseScan, type, this.where, perRowBytes);
11912
+ }
11913
+ /** Rows this UPDATE mutates: the target type's rows matching WHERE (index / selectivity / OR-aware). */
11914
+ affected(ctx, scope) {
11915
+ const type = ctx.engine.type(this.type);
11916
+ if (!type) return AFFECTED_NONE;
11917
+ return affectedOne(this.type, matchedRows(ctx, scope, type, this.where));
11118
11918
  }
11119
11919
  /** Expand joins, filter by WHERE, apply SET to each matched target row, then project RETURNING. */
11120
11920
  async execute(ctx) {
@@ -11381,7 +12181,8 @@ var DeleteQuery = class _DeleteQuery extends Query {
11381
12181
  return [this.from];
11382
12182
  }
11383
12183
  /** Estimate `{ rows, bytes }`: the target scan × join fan-out, reduced by WHERE. */
11384
- cost(engine, scope) {
12184
+ cost(ctx, scope) {
12185
+ const engine = ctx.engine;
11385
12186
  const type = engine.type(this.from);
11386
12187
  if (!type) return { rows: 0, bytes: 0 };
11387
12188
  const { aliasTypes } = this.bind(engine, scope);
@@ -11395,7 +12196,13 @@ var DeleteQuery = class _DeleteQuery extends Query {
11395
12196
  const baseScan = scanCost(type);
11396
12197
  baseScan.rows = rows;
11397
12198
  baseScan.bytes = rows * perRowBytes;
11398
- return applyWhere(baseScan, type, this.where, perRowBytes);
12199
+ return applyWhere(ctx, scope, baseScan, type, this.where, perRowBytes);
12200
+ }
12201
+ /** Rows this DELETE removes: the target type's rows matching WHERE (index / selectivity / OR-aware). */
12202
+ affected(ctx, scope) {
12203
+ const type = ctx.engine.type(this.from);
12204
+ if (!type) return AFFECTED_NONE;
12205
+ return affectedOne(this.from, matchedRows(ctx, scope, type, this.where));
11399
12206
  }
11400
12207
  /** Expand joins, filter by WHERE, project RETURNING (pre-removal), then delete the matched rows. */
11401
12208
  async execute(ctx) {
@@ -11420,7 +12227,7 @@ var DeleteQuery = class _DeleteQuery extends Query {
11420
12227
  }
11421
12228
  const defaults = this.activeDefaults(engine, aliasTypes);
11422
12229
  const targets = [];
11423
- const matchedRows = [];
12230
+ const matchedRows2 = [];
11424
12231
  const seen = /* @__PURE__ */ new Set();
11425
12232
  for (const row of rows) {
11426
12233
  if (defaults.length && !await rowPassesDefaultConditions(defaults, row, ctx)) continue;
@@ -11429,9 +12236,9 @@ var DeleteQuery = class _DeleteQuery extends Query {
11429
12236
  if (!target || seen.has(target)) continue;
11430
12237
  seen.add(target);
11431
12238
  targets.push(target);
11432
- matchedRows.push(row);
12239
+ matchedRows2.push(row);
11433
12240
  }
11434
- const outRows = await this.projectReturning(ctx, matchedRows);
12241
+ const outRows = await this.projectReturning(ctx, matchedRows2);
11435
12242
  for (const target of targets) deleteRecord(state, target);
11436
12243
  return makeResult("delete", outRows, fields, targets.length);
11437
12244
  }
@@ -11657,32 +12464,49 @@ var SetOperationQuery = class _SetOperationQuery extends Query {
11657
12464
  if (this.limit !== void 0 && typeof this.limit !== "number") params.observe(this.limit.name, numeric3, ["limit"]);
11658
12465
  if (this.offset !== void 0 && typeof this.offset !== "number") params.observe(this.offset.name, numeric3, ["offset"]);
11659
12466
  }
11660
- /** Estimate `{ rows, bytes }`: combine both arms per operation, then cap by a literal LIMIT. */
11661
- cost(engine, scope) {
11662
- const l = this.left.cost(engine, scope);
11663
- const r = this.right.cost(engine, scope);
11664
- let combined;
12467
+ /** Estimate the WORK `{ rows, bytes }`: combine both arms' cost per operation, then cap by LIMIT. */
12468
+ cost(ctx, scope) {
12469
+ return this.capByLimit(this.combineBranches(this.left.cost(ctx, scope), this.right.cost(ctx, scope)), ctx);
12470
+ }
12471
+ /** Estimate the RESULT SIZE: combine both arms' `outputCost` per operation, then cap by LIMIT. */
12472
+ outputCost(ctx, scope) {
12473
+ return this.capByLimit(this.combineBranches(this.left.outputCost(ctx, scope), this.right.outputCost(ctx, scope)), ctx);
12474
+ }
12475
+ /** Reads = the union of BOTH arms' references. */
12476
+ references(engine, scope, ctx) {
12477
+ return mergeReferences([this.left.references(engine, scope, ctx), this.right.references(engine, scope, ctx)]);
12478
+ }
12479
+ /** Combine the two arms' costs per the set operation (UNION sums, INTERSECT mins, EXCEPT keeps left). */
12480
+ combineBranches(l, r) {
11665
12481
  switch (this.kind) {
11666
12482
  case "union":
11667
- combined = addCost(l, r);
11668
- break;
12483
+ return addCost(l, r);
11669
12484
  case "intersect":
11670
- combined = { rows: Math.min(l.rows, r.rows), bytes: Math.min(l.bytes, r.bytes) };
11671
- break;
12485
+ return { rows: Math.min(l.rows, r.rows), bytes: Math.min(l.bytes, r.bytes) };
11672
12486
  case "except":
11673
- combined = l;
11674
- break;
12487
+ return l;
11675
12488
  /* v8 ignore next 2 -- exhaustive over SetKind; unreachable */
11676
12489
  default:
11677
12490
  return assertNever6(this.kind);
11678
12491
  }
11679
- if (typeof this.limit === "number" && combined.rows > 0) {
12492
+ }
12493
+ /** Cap a combined cost by the set-level LIMIT (a literal or a `ctx.params`-resolved value). */
12494
+ capByLimit(combined, ctx) {
12495
+ const limit = this.boundValue(this.limit, ctx);
12496
+ if (limit !== void 0 && combined.rows > 0) {
11680
12497
  const perRow = combined.bytes / combined.rows;
11681
- const rows = Math.min(combined.rows, this.limit);
11682
- combined = { rows, bytes: rows * perRow };
12498
+ const rows = Math.min(combined.rows, limit);
12499
+ return { rows, bytes: rows * perRow };
11683
12500
  }
11684
12501
  return combined;
11685
12502
  }
12503
+ /** Resolve a LIMIT bound to a number: a literal, else a `ctx.params` value, else undefined. */
12504
+ boundValue(v, ctx) {
12505
+ if (v === void 0) return void 0;
12506
+ if (typeof v === "number") return v;
12507
+ const raw2 = ctx.params?.[v.name];
12508
+ return typeof raw2 === "number" ? raw2 : void 0;
12509
+ }
11686
12510
  /** Run both arms, combine per the set operation, de-dup unless `all`, then apply set-level ORDER BY / OFFSET / LIMIT. */
11687
12511
  async execute(ctx) {
11688
12512
  const leftRes = await ctx.withNonRoot(() => this.left.execute(ctx));
@@ -11818,6 +12642,12 @@ var CTEEntryImpl = class _CTEEntryImpl {
11818
12642
  collectReferenced(out, cteNames) {
11819
12643
  for (const t of this.query.referencedTypes()) if (!cteNames.has(t)) out.add(t);
11820
12644
  }
12645
+ affected(ctx, scope) {
12646
+ return this.query.affected(ctx, scope);
12647
+ }
12648
+ references(engine, scope, ctx) {
12649
+ return this.query.references(engine, scope, ctx);
12650
+ }
11821
12651
  async execute(ctx) {
11822
12652
  const res = await ctx.withNonRoot(() => this.query.execute(ctx));
11823
12653
  ctx.ctes.set(this.name, [...res.rows]);
@@ -11853,6 +12683,12 @@ var CTERecursiveEntryImpl = class _CTERecursiveEntryImpl {
11853
12683
  for (const t of this.base.referencedTypes()) if (!cteNames.has(t)) out.add(t);
11854
12684
  for (const t of this.recursiveArm.referencedTypes()) if (!cteNames.has(t)) out.add(t);
11855
12685
  }
12686
+ affected(ctx, scope) {
12687
+ return mergeAffected([this.base.affected(ctx, scope), this.recursiveArm.affected(ctx, scope)]);
12688
+ }
12689
+ references(engine, scope, ctx) {
12690
+ return mergeReferences([this.base.references(engine, scope, ctx), this.recursiveArm.references(engine, scope, ctx)]);
12691
+ }
11856
12692
  async execute(ctx) {
11857
12693
  const baseRes = await ctx.withNonRoot(() => this.base.execute(ctx));
11858
12694
  let all = [...baseRes.rows];
@@ -12069,8 +12905,22 @@ var CTEStatementQuery = class _CTEStatementQuery extends Query {
12069
12905
  return [...out];
12070
12906
  }
12071
12907
  /** Estimate `{ rows, bytes }` — the final query's cost, with CTE names bound. */
12072
- cost(engine, scope) {
12073
- return this.final.cost(engine, this.bind(engine, scope));
12908
+ cost(ctx, scope) {
12909
+ return this.final.cost(ctx, this.bind(ctx.engine, scope));
12910
+ }
12911
+ /** The RESULT SIZE is the final query's output cost, with CTE names bound. */
12912
+ outputCost(ctx, scope) {
12913
+ return this.final.outputCost(ctx, this.bind(ctx.engine, scope));
12914
+ }
12915
+ /** Rows mutated: every data-modifying CTE entry plus the final query, summed per Type. */
12916
+ affected(ctx, scope) {
12917
+ const bound = this.bind(ctx.engine, scope);
12918
+ return mergeAffected([this.final.affected(ctx, bound), ...this.ctes.map((e2) => e2.affected(ctx, bound))]);
12919
+ }
12920
+ /** Reads = the final query's plus every entry's references (Types / fields / functions). */
12921
+ references(engine, scope, ctx) {
12922
+ const bound = this.bind(engine, scope);
12923
+ return mergeReferences([this.final.references(engine, bound, ctx), ...this.ctes.map((e2) => e2.references(engine, bound, ctx))]);
12074
12924
  }
12075
12925
  /** Evaluate each CTE in order (populating `ctx.ctes`), then run the final query. */
12076
12926
  async execute(ctx) {
@@ -12161,9 +13011,13 @@ var ExprQuery = class _ExprQuery extends Query {
12161
13011
  referencedTypes() {
12162
13012
  return [];
12163
13013
  }
13014
+ /** Walk the single output expression (so `references` sees its functions). */
13015
+ walkExprs(visit) {
13016
+ this.expr.walk(visit);
13017
+ }
12164
13018
  /** Estimate `{ rows, bytes }` — exactly one row sized by the expression's resolved type. */
12165
- cost(engine, scope) {
12166
- return { rows: 1, bytes: bytesOfResolved(this.expr.resolve(engine, scope)) };
13019
+ cost(ctx, scope) {
13020
+ return { rows: 1, bytes: bytesOfResolved(this.expr.resolve(ctx.engine, scope)) };
12167
13021
  }
12168
13022
  /** Evaluate the expression into a single `{ value }` output row. */
12169
13023
  async execute(ctx) {
@@ -12962,6 +13816,10 @@ function scalar2(name, instructions, params, output2, run, sql, rawArgs, example
12962
13816
  run: { shape: "scalar", run }
12963
13817
  };
12964
13818
  }
13819
+ var ONE_DAY_MS = 864e5;
13820
+ function withChanges(builtin, changes) {
13821
+ return { ...builtin, def: { ...builtin.def, changes } };
13822
+ }
12965
13823
  var SCALARS = [
12966
13824
  scalar2(
12967
13825
  "concat",
@@ -13233,7 +14091,7 @@ var SCALARS = [
13233
14091
  scalar2("pi", "The constant \u03C0.", [], NUMBER, () => Value.of(Math.PI)),
13234
14092
  scalar2("degrees", "Convert radians to degrees.", [{ name: "value", type: NUMBER }], NUMBER, (a) => numeric(arg(a, "value"), (n) => n * 180 / Math.PI)),
13235
14093
  scalar2("radians", "Convert degrees to radians.", [{ name: "value", type: NUMBER }], NUMBER, (a) => numeric(arg(a, "value"), (n) => n * Math.PI / 180)),
13236
- scalar2("random", "Random number in [0, 1).", [], NUMBER, () => Value.of(Math.random())),
14094
+ withChanges(scalar2("random", "Random number in [0, 1).", [], NUMBER, () => Value.of(Math.random())), 0),
13237
14095
  scalar2("sin", "Sine (radians).", [{ name: "value", type: NUMBER }], NUMBER, (a) => numeric(arg(a, "value"), Math.sin)),
13238
14096
  scalar2("cos", "Cosine (radians).", [{ name: "value", type: NUMBER }], NUMBER, (a) => numeric(arg(a, "value"), Math.cos)),
13239
14097
  scalar2("tan", "Tangent (radians).", [{ name: "value", type: NUMBER }], NUMBER, (a) => numeric(arg(a, "value"), Math.tan)),
@@ -13260,19 +14118,19 @@ var SCALARS = [
13260
14118
  // Emitted (both dialects) as `(CASE WHEN condition THEN then ELSE else END)`.
13261
14119
  (a) => arg(a, "condition").toBoolean() ? arg(a, "then") : arg(a, "else")
13262
14120
  ),
13263
- scalar2("now", "Current timestamp.", [], { kind: "timestamp" }, () => Value.of((/* @__PURE__ */ new Date()).toISOString())),
13264
- scalar2("currentDate", "Today\u2019s date.", [], { kind: "date" }, () => {
14121
+ withChanges(scalar2("now", "Current timestamp.", [], { kind: "timestamp" }, () => Value.of((/* @__PURE__ */ new Date()).toISOString())), 0),
14122
+ withChanges(scalar2("currentDate", "Today\u2019s date.", [], { kind: "date" }, () => {
13265
14123
  const iso = (/* @__PURE__ */ new Date()).toISOString();
13266
14124
  return Value.of(iso.split("T")[0] ?? iso);
13267
- }),
14125
+ }), ONE_DAY_MS),
13268
14126
  // ─── Group 2a: date / time ─────────────────────────────────────────────────
13269
14127
  // Temporal inputs are typed `any` (an ISO date/timestamp string OR a temporal
13270
14128
  // field), so a `date` value is accepted wherever a `timestamp` is. The FIELD
13271
14129
  // arg of the four selectors is a `rawArgs` inline literal (emitted as an
13272
14130
  // `EXTRACT`/`date_part` field, never a bind param). `currentTime`/…, the
13273
14131
  // `EXTRACT`-based extractors, and the pg selector forms live in the dialects.
13274
- scalar2("currentTime", "Current time of day (HH:MM:SS).", [], TEXT, () => Value.of((/* @__PURE__ */ new Date()).toISOString().slice(11, 19))),
13275
- scalar2("currentTimestamp", "Current timestamp.", [], TIMESTAMP, () => Value.of((/* @__PURE__ */ new Date()).toISOString())),
14132
+ withChanges(scalar2("currentTime", "Current time of day (HH:MM:SS).", [], TEXT, () => Value.of((/* @__PURE__ */ new Date()).toISOString().slice(11, 19))), 0),
14133
+ withChanges(scalar2("currentTimestamp", "Current timestamp.", [], TIMESTAMP, () => Value.of((/* @__PURE__ */ new Date()).toISOString())), 0),
13276
14134
  scalar2(
13277
14135
  "datePart",
13278
14136
  "Numeric component named by `field` (year/month/day/dow/\u2026) of `d`.",
@@ -13847,6 +14705,22 @@ var Registry = class {
13847
14705
  fieldTypeClassList() {
13848
14706
  return Array.from(this.fieldTypeClasses.values());
13849
14707
  }
14708
+ /** Registry-level default average bytes per field-type kind (a `Field` with no explicit `bytes` falls back here). */
14709
+ defaultFieldTypeBytes = /* @__PURE__ */ new Map();
14710
+ /**
14711
+ * Configure the default average stored bytes for a field-type KIND — the
14712
+ * fallback a `Field` of that kind uses when it declares no explicit `bytes`
14713
+ * (before the field type's own {@link FieldType.avgBytes}). Lets a deployment
14714
+ * tune byte-cost estimates centrally (e.g. "our `text` averages 128 bytes").
14715
+ */
14716
+ setDefaultFieldBytes(kind, bytes) {
14717
+ this.defaultFieldTypeBytes.set(kind, bytes);
14718
+ return this;
14719
+ }
14720
+ /** The configured default bytes for a field-type kind, or `undefined` when unset. */
14721
+ defaultFieldBytes(kind) {
14722
+ return this.defaultFieldTypeBytes.get(kind);
14723
+ }
13850
14724
  /** Parse a `FieldTypeDef` into a `FieldType` instance by dispatching on kind. */
13851
14725
  parseFieldType(json) {
13852
14726
  const cls = this.fieldTypeClasses.get(json.kind);
@@ -14647,6 +15521,16 @@ var QueryFunction = class _QueryFunction {
14647
15521
  */
14648
15522
  unaggregate;
14649
15523
  unaggregateEmpty;
15524
+ /** Intrinsic per-call cost this function adds beyond its args (default none). */
15525
+ cost;
15526
+ /**
15527
+ * Milliseconds between changes to this function's RESULT independent of the
15528
+ * data (`0` = always — `now()`; `-1` = pure/never — the default; `86400000` =
15529
+ * daily — `currentDate()`). Folded into `engine.changeInterval`.
15530
+ */
15531
+ changes;
15532
+ /** Type names this function internally READS (a UDF over a table); folded into cost / references. */
15533
+ references;
14650
15534
  /** Construct from already-parsed parts; use `from` to build from JSON. */
14651
15535
  constructor(spec) {
14652
15536
  this.name = spec.name;
@@ -14659,6 +15543,9 @@ var QueryFunction = class _QueryFunction {
14659
15543
  this.examples = spec.examples;
14660
15544
  this.unaggregate = spec.unaggregate;
14661
15545
  this.unaggregateEmpty = spec.unaggregateEmpty;
15546
+ this.cost = spec.cost ?? ZERO_COST;
15547
+ this.changes = spec.changes ?? NEVER_CHANGES;
15548
+ this.references = spec.references ?? [];
14662
15549
  }
14663
15550
  /** Build a runtime function from its JSON, parsing field/Type references. */
14664
15551
  static from(json, registry) {
@@ -14692,7 +15579,10 @@ var QueryFunction = class _QueryFunction {
14692
15579
  instructions: json.instructions,
14693
15580
  examples: json.examples,
14694
15581
  unaggregate: json.unaggregate,
14695
- unaggregateEmpty: json.unaggregateEmpty
15582
+ unaggregateEmpty: json.unaggregateEmpty,
15583
+ cost: json.cost,
15584
+ changes: json.changes,
15585
+ references: json.references
14696
15586
  });
14697
15587
  }
14698
15588
  /**
@@ -14720,7 +15610,11 @@ var QueryFunction = class _QueryFunction {
14720
15610
  ...this.instructions ? { instructions: this.instructions } : {},
14721
15611
  ...this.examples ? { examples: this.examples } : {},
14722
15612
  ...this.unaggregate ? { unaggregate: this.unaggregate } : {},
14723
- ...this.unaggregateEmpty ? { unaggregateEmpty: this.unaggregateEmpty } : {}
15613
+ ...this.unaggregateEmpty ? { unaggregateEmpty: this.unaggregateEmpty } : {},
15614
+ // Estimation metadata — emitted only when set away from the neutral default.
15615
+ ...this.cost.rows !== 0 || this.cost.bytes !== 0 ? { cost: this.cost } : {},
15616
+ ...this.changes !== NEVER_CHANGES ? { changes: this.changes } : {},
15617
+ ...this.references.length > 0 ? { references: [...this.references] } : {}
14724
15618
  };
14725
15619
  }
14726
15620
  /**
@@ -15038,7 +15932,7 @@ var QueryEngine = class {
15038
15932
  * supplied, the estimated `cost` is checked too and `cost.rows-exceeded` /
15039
15933
  * `cost.bytes-exceeded` problems are appended (opt-in).
15040
15934
  */
15041
- validateQuery(query, scope, constraints) {
15935
+ validateQuery(query, scope, constraints, options) {
15042
15936
  const q = this.toQuery(query);
15043
15937
  const s = scope ?? this.globalScope();
15044
15938
  const p = new Problems();
@@ -15048,12 +15942,78 @@ var QueryEngine = class {
15048
15942
  const ex = this.executor(name);
15049
15943
  ex?.validate?.(q, p);
15050
15944
  }
15051
- if (constraints) reportCostProblems(q.cost(this, s), constraints, p);
15945
+ if (constraints) reportCostProblems(q.cost(this.costContext(options), s), constraints, p);
15052
15946
  return p;
15053
15947
  }
15054
- /** Estimate a query's `{ rows, bytes }` cost against a scope (root if omitted). */
15055
- cost(query, scope) {
15056
- return this.toQuery(query).cost(this, scope ?? this.globalScope());
15948
+ /**
15949
+ * Estimate a query's `{ rows, bytes }` cost against a scope (root if omitted).
15950
+ * `options` may supply the execution-time `filters` / `sort` the query is
15951
+ * costed WITH, so a `filters` / `sorter` placeholder weaves the real supplied
15952
+ * predicate / sort into the estimate (a subquery in a filter then raises the
15953
+ * cost, as it should).
15954
+ */
15955
+ cost(query, scope, options) {
15956
+ return this.toQuery(query).cost(this.costContext(options), scope ?? this.globalScope());
15957
+ }
15958
+ /**
15959
+ * Estimate the SIZE OF THE RESULT a query hands back — `{ rows, bytes }` where
15960
+ * `rows` is the delivered row count (post-WHERE / GROUP / DISTINCT, capped by a
15961
+ * literal or `options.params`-resolved LIMIT / OFFSET) and `bytes` sizes those
15962
+ * rows by the PROJECTION width (the selected columns), not the whole scanned
15963
+ * row. Contrast {@link cost}, which estimates the WORK to produce the result.
15964
+ */
15965
+ outputCost(query, scope, options) {
15966
+ return this.toQuery(query).outputCost(this.costContext(options), scope ?? this.globalScope());
15967
+ }
15968
+ /**
15969
+ * Estimate the rows a statement MUTATES — a total plus a per-Type breakdown
15970
+ * ({@link Affected}). An UPDATE / DELETE uses the target Type's indexes +
15971
+ * selectivity (OR-aware) to count the rows its WHERE matches; an INSERT counts
15972
+ * its VALUES / source rows; a CTE SUMS every data-modifying entry plus its
15973
+ * final query per Type. Read-only queries report `{ rows: 0, types: [] }`.
15974
+ * `options.params` resolves a param-bound LIMIT where used.
15975
+ */
15976
+ affected(query, scope, options) {
15977
+ return this.toQuery(query).affected(this.costContext(options), scope ?? this.globalScope());
15978
+ }
15979
+ /**
15980
+ * Estimate how long (ms) until the DATA behind a query could change — a
15981
+ * freshness / cache-TTL signal. Uses {@link Query.references} (so it counts
15982
+ * ONLY the Types / fields the query actually reads, plus execution-time
15983
+ * `filters` / selected `sort` exprs and invoked functions) and folds their
15984
+ * `changes` rates: `0` (always changing) dominates, a negative (never) is
15985
+ * ignored, else the FASTEST positive interval wins. Each read Type contributes
15986
+ * its row-level rate; a read field with its OWN rate refines it; a called
15987
+ * function (e.g. `currentDate()`) contributes its volatility. A query over only
15988
+ * immutable data / pure literals returns `-1`.
15989
+ */
15990
+ /**
15991
+ * Enumerate what a query READS — its {@link QueryReferences} of Types, specific
15992
+ * fields, and DB functions — including execution-time `filters` predicates and
15993
+ * the `sort`-selected sorter exprs (from `options`). Powers `changeInterval`
15994
+ * and lets a caller inspect the exact surface a query touches.
15995
+ */
15996
+ references(query, scope, options) {
15997
+ this.registry.finalize();
15998
+ return this.toQuery(query).references(this, scope ?? this.globalScope(), this.costContext(options));
15999
+ }
16000
+ changeInterval(query, scope, options) {
16001
+ this.registry.finalize();
16002
+ const refs = this.toQuery(query).references(this, scope ?? this.globalScope(), this.costContext(options));
16003
+ let acc = NEVER_CHANGES;
16004
+ for (const name of refs.types) {
16005
+ const type = this.type(name);
16006
+ if (type) acc = foldChanges(acc, type.changes);
16007
+ }
16008
+ for (const ref3 of refs.fields) {
16009
+ const changes = this.type(ref3.type)?.field(ref3.field)?.changes();
16010
+ if (changes !== void 0) acc = foldChanges(acc, changes);
16011
+ }
16012
+ for (const name of refs.functions) {
16013
+ const fn2 = this.lookupFunction(name);
16014
+ if (fn2) acc = foldChanges(acc, fn2.changes);
16015
+ }
16016
+ return acc;
15057
16017
  }
15058
16018
  /**
15059
16019
  * Check a query's estimated cost against `constraints`, returning any
@@ -15061,11 +16021,23 @@ var QueryEngine = class {
15061
16021
  * A standalone entry point so callers can cost-bound a query without a full
15062
16022
  * structural re-validation.
15063
16023
  */
15064
- checkCost(query, constraints, scope) {
16024
+ checkCost(query, constraints, scope, options) {
15065
16025
  const p = new Problems();
15066
- reportCostProblems(this.cost(query, scope), constraints, p);
16026
+ reportCostProblems(this.cost(query, scope, options), constraints, p);
15067
16027
  return p;
15068
16028
  }
16029
+ /**
16030
+ * Build the {@link CostContext} for a cost walk from optional execution-time
16031
+ * selections: the `filters` map is parsed once (source → bound `Expr`) exactly
16032
+ * as `run` / `toSQL` do; `sort` is the dynamic-sort selection. With neither, a
16033
+ * bare `{ engine }` context is returned (placeholders stay neutral).
16034
+ */
16035
+ costContext(options) {
16036
+ if (!options?.filters && !options?.sort && !options?.params) return { engine: this };
16037
+ const parsed = options.filters ? this.parseFilters(options.filters) : void 0;
16038
+ const filters2 = parsed ? new Map(Object.entries(parsed)) : void 0;
16039
+ return { engine: this, filters: filters2, sort: options.sort, params: options.params };
16040
+ }
15069
16041
  async run(query, options, opts) {
15070
16042
  const q = this.toQuery(query);
15071
16043
  const ctx = new RuntimeContext(this, options);