@aeye/query 0.3.9 → 0.3.10
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.d.ts +9487 -0
- package/dist/index.js +885 -164
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1686,6 +1686,10 @@ var Field = class _Field {
|
|
|
1686
1686
|
description;
|
|
1687
1687
|
/** The field's value type. */
|
|
1688
1688
|
fieldType;
|
|
1689
|
+
/** Explicit average stored bytes, when authored (else the field type's default). */
|
|
1690
|
+
explicitBytes;
|
|
1691
|
+
/** Explicit change interval (ms) for this field, when authored (else the Type's rate). */
|
|
1692
|
+
explicitChanges;
|
|
1689
1693
|
/** Whether the field may hold null / be absent. */
|
|
1690
1694
|
nullable;
|
|
1691
1695
|
/** Whether the field may be supplied on INSERT (default true). */
|
|
@@ -1706,6 +1710,8 @@ var Field = class _Field {
|
|
|
1706
1710
|
this.label = spec.label;
|
|
1707
1711
|
this.description = spec.description;
|
|
1708
1712
|
this.fieldType = spec.fieldType;
|
|
1713
|
+
this.explicitBytes = spec.bytes;
|
|
1714
|
+
this.explicitChanges = spec.changes;
|
|
1709
1715
|
this.nullable = spec.nullable ?? false;
|
|
1710
1716
|
this.insertableSet = spec.insertable !== void 0;
|
|
1711
1717
|
this.updatableSet = spec.updatable !== void 0;
|
|
@@ -1716,17 +1722,39 @@ var Field = class _Field {
|
|
|
1716
1722
|
}
|
|
1717
1723
|
/** Build a Field from its JSON, parsing the field type via `registry`. */
|
|
1718
1724
|
static from(json, registry) {
|
|
1725
|
+
const fieldType = registry.parseFieldType(json.type);
|
|
1719
1726
|
return new _Field({
|
|
1720
1727
|
name: json.name,
|
|
1721
1728
|
label: json.label,
|
|
1722
1729
|
description: json.description,
|
|
1723
|
-
fieldType
|
|
1730
|
+
fieldType,
|
|
1731
|
+
// An explicit per-field `bytes` wins; otherwise a registry-level default for
|
|
1732
|
+
// this field type's kind may apply (else the field type's own avgBytes()).
|
|
1733
|
+
bytes: json.bytes ?? registry.defaultFieldBytes(fieldType.kind),
|
|
1734
|
+
changes: json.changes,
|
|
1724
1735
|
nullable: json.nullable ?? false,
|
|
1725
1736
|
insertable: json.insertable,
|
|
1726
1737
|
updatable: json.updatable,
|
|
1727
1738
|
exprs: json.exprs
|
|
1728
1739
|
});
|
|
1729
1740
|
}
|
|
1741
|
+
/**
|
|
1742
|
+
* Estimated average stored bytes for this field: an explicit authored `bytes`
|
|
1743
|
+
* when present, else the field type's own {@link FieldType.avgBytes} default.
|
|
1744
|
+
* Drives the whole-row and index byte-cost estimates.
|
|
1745
|
+
*/
|
|
1746
|
+
bytes() {
|
|
1747
|
+
return this.explicitBytes ?? this.fieldType.avgBytes();
|
|
1748
|
+
}
|
|
1749
|
+
/**
|
|
1750
|
+
* Explicit change interval (ms) for this field, or `undefined` when it inherits
|
|
1751
|
+
* the Type's rate. `0` = always changing, `-1` = never, `60000` = once a
|
|
1752
|
+
* minute. Folded into `engine.changeInterval(query)` to estimate result
|
|
1753
|
+
* freshness.
|
|
1754
|
+
*/
|
|
1755
|
+
changes() {
|
|
1756
|
+
return this.explicitChanges;
|
|
1757
|
+
}
|
|
1730
1758
|
/**
|
|
1731
1759
|
* Whether this field's TYPE could ever support expr `kind` — the availability
|
|
1732
1760
|
* floor `allowsExpr` narrows. Type-gated kinds: `array-op` needs an array
|
|
@@ -1780,6 +1808,10 @@ var Field = class _Field {
|
|
|
1780
1808
|
label: this.label,
|
|
1781
1809
|
description: this.description,
|
|
1782
1810
|
type: this.fieldType.toJSON(),
|
|
1811
|
+
// Only emit `bytes` when authored explicitly (a derived default stays implicit).
|
|
1812
|
+
bytes: this.explicitBytes,
|
|
1813
|
+
// Only emit `changes` when authored (it otherwise inherits the Type's rate).
|
|
1814
|
+
changes: this.explicitChanges,
|
|
1783
1815
|
// Only emit `nullable` when true, keeping the default implicit.
|
|
1784
1816
|
nullable: this.nullable ? true : void 0,
|
|
1785
1817
|
// Emit a write flag only when it was set EXPLICITLY (preserving fidelity of
|
|
@@ -1796,6 +1828,8 @@ var Field = class _Field {
|
|
|
1796
1828
|
label: this.label,
|
|
1797
1829
|
description: this.description,
|
|
1798
1830
|
fieldType: this.fieldType.clone(),
|
|
1831
|
+
bytes: this.explicitBytes,
|
|
1832
|
+
changes: this.explicitChanges,
|
|
1799
1833
|
nullable: this.nullable,
|
|
1800
1834
|
insertable: this.insertableSet ? this.insertable : void 0,
|
|
1801
1835
|
updatable: this.updatableSet ? this.updatable : void 0,
|
|
@@ -1810,6 +1844,7 @@ var Field = class _Field {
|
|
|
1810
1844
|
};
|
|
1811
1845
|
|
|
1812
1846
|
// src/index-spec.ts
|
|
1847
|
+
var NON_FIELD_PART_BYTES = 8;
|
|
1813
1848
|
function stableStringify(value2) {
|
|
1814
1849
|
if (value2 === null) return "null";
|
|
1815
1850
|
if (Array.isArray(value2)) {
|
|
@@ -1848,9 +1883,28 @@ var IndexPart = class {
|
|
|
1848
1883
|
var Index = class _Index {
|
|
1849
1884
|
/** The ordered parts of this composite index (at least one). */
|
|
1850
1885
|
parts;
|
|
1851
|
-
/**
|
|
1852
|
-
|
|
1886
|
+
/** Explicit average bytes per index entry, when authored (else derived from parts). */
|
|
1887
|
+
explicitBytes;
|
|
1888
|
+
/** Construct an index from its ordered parts (at least one) and optional entry-byte size. */
|
|
1889
|
+
constructor(parts, bytes) {
|
|
1853
1890
|
this.parts = parts;
|
|
1891
|
+
this.explicitBytes = bytes;
|
|
1892
|
+
}
|
|
1893
|
+
/**
|
|
1894
|
+
* Estimated average bytes of one INDEX ENTRY — an explicit authored `bytes`,
|
|
1895
|
+
* else the SUM of the parts' byte sizes: a field-ref part uses that field's
|
|
1896
|
+
* {@link Field.bytes}; any other expr part uses a small fixed default. Drives
|
|
1897
|
+
* the index-only (covered) scan estimate, where reading index entries is
|
|
1898
|
+
* cheaper than reading whole rows.
|
|
1899
|
+
*/
|
|
1900
|
+
bytes(type) {
|
|
1901
|
+
if (this.explicitBytes !== void 0) return this.explicitBytes;
|
|
1902
|
+
let total = 0;
|
|
1903
|
+
for (const part of this.parts) {
|
|
1904
|
+
const field = part.expr.kind === "field-ref" ? type.field(part.expr.field) : void 0;
|
|
1905
|
+
total += field ? field.bytes() : NON_FIELD_PART_BYTES;
|
|
1906
|
+
}
|
|
1907
|
+
return total;
|
|
1854
1908
|
}
|
|
1855
1909
|
/**
|
|
1856
1910
|
* True when a full-key equality lookup yields at most one row — i.e. the
|
|
@@ -1880,11 +1934,13 @@ var Index = class _Index {
|
|
|
1880
1934
|
}
|
|
1881
1935
|
/** Build an Index from its `IndexDef` JSON. */
|
|
1882
1936
|
static from(json) {
|
|
1883
|
-
return new _Index(json.exprs.map((p) => new IndexPart(p.expr, p.count)));
|
|
1937
|
+
return new _Index(json.exprs.map((p) => new IndexPart(p.expr, p.count)), json.bytes);
|
|
1884
1938
|
}
|
|
1885
|
-
/** Serialize to its `IndexDef` JSON shape. */
|
|
1939
|
+
/** Serialize to its `IndexDef` JSON shape (emitting `bytes` only when authored explicitly). */
|
|
1886
1940
|
toJSON() {
|
|
1887
|
-
|
|
1941
|
+
const def = { exprs: this.parts.map((p) => p.toJSON()) };
|
|
1942
|
+
if (this.explicitBytes !== void 0) def.bytes = this.explicitBytes;
|
|
1943
|
+
return def;
|
|
1888
1944
|
}
|
|
1889
1945
|
/** Deep-copy this index (round-trips through JSON). */
|
|
1890
1946
|
clone() {
|
|
@@ -1909,6 +1965,8 @@ var Type = class _Type {
|
|
|
1909
1965
|
count;
|
|
1910
1966
|
/** Estimated average bytes per row (drives byte-cost estimation). */
|
|
1911
1967
|
bytes;
|
|
1968
|
+
/** Estimated ms between changes to this Type's data (`0` = always, `-1` = never). */
|
|
1969
|
+
changes;
|
|
1912
1970
|
/** Whether the whole type is flagged semantic-eligible. */
|
|
1913
1971
|
semantic;
|
|
1914
1972
|
/** Whether the whole type is flagged full-text-search-eligible. */
|
|
@@ -1927,7 +1985,8 @@ var Type = class _Type {
|
|
|
1927
1985
|
this.fields = spec.fields;
|
|
1928
1986
|
this.indexes = spec.indexes;
|
|
1929
1987
|
this.count = spec.count;
|
|
1930
|
-
this.bytes = spec.bytes;
|
|
1988
|
+
this.bytes = spec.bytes ?? this.fields.reduce((sum2, f) => sum2 + f.bytes(), 0);
|
|
1989
|
+
this.changes = spec.changes ?? 0;
|
|
1931
1990
|
this.semantic = spec.semantic ?? false;
|
|
1932
1991
|
this.search = spec.search ?? false;
|
|
1933
1992
|
this.insertable = spec.insertable ?? true;
|
|
@@ -2005,6 +2064,7 @@ var Type = class _Type {
|
|
|
2005
2064
|
indexes,
|
|
2006
2065
|
count: json.count,
|
|
2007
2066
|
bytes: json.bytes,
|
|
2067
|
+
changes: json.changes,
|
|
2008
2068
|
semantic: json.semantic,
|
|
2009
2069
|
search: json.search,
|
|
2010
2070
|
insertable: json.insertable,
|
|
@@ -2024,6 +2084,8 @@ var Type = class _Type {
|
|
|
2024
2084
|
label: z12.string().optional(),
|
|
2025
2085
|
description: z12.string().optional(),
|
|
2026
2086
|
type: fieldTypeDefSchema(),
|
|
2087
|
+
bytes: z12.number().optional().describe("Estimated average stored bytes for this field (overrides the field type default)."),
|
|
2088
|
+
changes: z12.number().optional().describe("Ms between changes to this field (overrides the Type; 0 = always, -1 = never)."),
|
|
2027
2089
|
nullable: z12.boolean().optional(),
|
|
2028
2090
|
insertable: z12.boolean().optional().describe("Whether the field may be supplied on INSERT (default true)."),
|
|
2029
2091
|
updatable: z12.boolean().optional().describe("Whether the field may be assigned on UPDATE (default true)."),
|
|
@@ -2035,7 +2097,8 @@ var Type = class _Type {
|
|
|
2035
2097
|
count: z12.number().describe("Prefix distinct rows up to & including this part; last part 1 \u21D2 unique.")
|
|
2036
2098
|
}).meta({ aid: "IndexPartDef" }).describe("One ordered part of a composite index.");
|
|
2037
2099
|
const indexDefSchema = z12.object({
|
|
2038
|
-
exprs: z12.array(indexPartDefSchema).describe("Ordered composite-index parts.")
|
|
2100
|
+
exprs: z12.array(indexPartDefSchema).describe("Ordered composite-index parts."),
|
|
2101
|
+
bytes: z12.number().optional().describe("Estimated average bytes per index entry (else derived from the parts).")
|
|
2039
2102
|
}).meta({ aid: "IndexDef" }).describe("A composite index definition.");
|
|
2040
2103
|
return z12.object({
|
|
2041
2104
|
name: z12.string(),
|
|
@@ -2044,7 +2107,8 @@ var Type = class _Type {
|
|
|
2044
2107
|
fields: z12.array(fieldDefSchema),
|
|
2045
2108
|
indexes: z12.array(indexDefSchema).optional(),
|
|
2046
2109
|
count: z12.number().describe("Estimated total row count."),
|
|
2047
|
-
bytes: z12.number().describe("Estimated average bytes per row."),
|
|
2110
|
+
bytes: z12.number().optional().describe("Estimated average bytes per row (else derived as the sum of the fields' bytes)."),
|
|
2111
|
+
changes: z12.number().optional().describe("Ms between changes to this Type's data (0 = always changing, -1 = never)."),
|
|
2048
2112
|
semantic: z12.boolean().optional().describe("Eligible for semantic similarity across the type."),
|
|
2049
2113
|
search: z12.boolean().optional().describe("Eligible for full-text search across the type."),
|
|
2050
2114
|
insertable: z12.boolean().optional().describe("Whether rows may be INSERTed (default true)."),
|
|
@@ -2064,6 +2128,8 @@ var Type = class _Type {
|
|
|
2064
2128
|
indexes: indexes.length > 0 ? indexes : void 0,
|
|
2065
2129
|
count: this.count,
|
|
2066
2130
|
bytes: this.bytes,
|
|
2131
|
+
// Emit `changes` only when set away from the default (0 = always changing).
|
|
2132
|
+
changes: this.changes !== 0 ? this.changes : void 0,
|
|
2067
2133
|
semantic: this.semantic ? true : void 0,
|
|
2068
2134
|
search: this.search ? true : void 0,
|
|
2069
2135
|
// Only emit a write flag when RESTRICTED (false), keeping the default implicit.
|
|
@@ -2082,6 +2148,7 @@ var Type = class _Type {
|
|
|
2082
2148
|
indexes: this.indexes.map((i) => i.clone()),
|
|
2083
2149
|
count: this.count,
|
|
2084
2150
|
bytes: this.bytes,
|
|
2151
|
+
changes: this.changes,
|
|
2085
2152
|
semantic: this.semantic,
|
|
2086
2153
|
search: this.search,
|
|
2087
2154
|
insertable: this.insertable,
|
|
@@ -2155,7 +2222,27 @@ function assertNever(value2) {
|
|
|
2155
2222
|
}
|
|
2156
2223
|
|
|
2157
2224
|
// src/cost.ts
|
|
2225
|
+
function mergeAffected(parts) {
|
|
2226
|
+
const byType = /* @__PURE__ */ new Map();
|
|
2227
|
+
for (const part of parts) {
|
|
2228
|
+
for (const t of part.types) byType.set(t.type, (byType.get(t.type) ?? 0) + t.rows);
|
|
2229
|
+
}
|
|
2230
|
+
const types = [...byType].map(([type, rows]) => ({ type, rows }));
|
|
2231
|
+
return { rows: types.reduce((sum2, t) => sum2 + t.rows, 0), types };
|
|
2232
|
+
}
|
|
2233
|
+
function affectedOne(type, rows) {
|
|
2234
|
+
return rows > 0 ? { rows, types: [{ type, rows }] } : { rows: 0, types: [] };
|
|
2235
|
+
}
|
|
2236
|
+
var AFFECTED_NONE = { rows: 0, types: [] };
|
|
2158
2237
|
var ZERO_COST = { rows: 0, bytes: 0 };
|
|
2238
|
+
var ALWAYS_CHANGES = 0;
|
|
2239
|
+
var NEVER_CHANGES = -1;
|
|
2240
|
+
function foldChanges(a, b) {
|
|
2241
|
+
if (a === ALWAYS_CHANGES || b === ALWAYS_CHANGES) return ALWAYS_CHANGES;
|
|
2242
|
+
if (a < 0) return b;
|
|
2243
|
+
if (b < 0) return a;
|
|
2244
|
+
return Math.min(a, b);
|
|
2245
|
+
}
|
|
2159
2246
|
var EQ_SELECTIVITY = 0.33;
|
|
2160
2247
|
var RANGE_SELECTIVITY = 0.5;
|
|
2161
2248
|
var IN_SELECTIVITY = 0.5;
|
|
@@ -2177,6 +2264,7 @@ function rowsCost(rows, perRowBytes) {
|
|
|
2177
2264
|
return { rows: r, bytes: r * Math.max(0, perRowBytes) };
|
|
2178
2265
|
}
|
|
2179
2266
|
function bytesOfResolved(rt) {
|
|
2267
|
+
if (rt.kind === "field") return rt.field.bytes();
|
|
2180
2268
|
return asFieldType(rt)?.avgBytes() ?? 0;
|
|
2181
2269
|
}
|
|
2182
2270
|
function reportCostProblems(cost, constraints, p) {
|
|
@@ -2319,11 +2407,93 @@ var ROOT_VALIDATE_CONTEXT = {
|
|
|
2319
2407
|
inGroupBy: false
|
|
2320
2408
|
};
|
|
2321
2409
|
var Expr = class {
|
|
2410
|
+
// ─── Cost analysis surface (composed by the query cost model) ────────────
|
|
2411
|
+
//
|
|
2412
|
+
// These let the WHERE / index cost model in `queries/_cost.ts` ask each expr
|
|
2413
|
+
// about ITSELF instead of switching on its concrete class. Every default here
|
|
2414
|
+
// is the neutral answer; a kind that participates overrides the one method it
|
|
2415
|
+
// has an opinion about.
|
|
2416
|
+
/**
|
|
2417
|
+
* The fraction of scanned rows this predicate KEEPS when used as a WHERE /
|
|
2418
|
+
* HAVING / ON filter (SQL selectivity). `1` = no reduction (the neutral
|
|
2419
|
+
* default). Overridden by the concrete predicates (`comparison` branches on
|
|
2420
|
+
* its own op, `between` / `in` / `is-null` their fixed selectivity, `filters`
|
|
2421
|
+
* delegates to its supplied predicate). Index-covered equality is accounted
|
|
2422
|
+
* for separately by the cost model (via {@link indexProbe}); a predicate need
|
|
2423
|
+
* not discount for it here.
|
|
2424
|
+
*/
|
|
2425
|
+
selectivity(_ctx, _scope) {
|
|
2426
|
+
return 1;
|
|
2427
|
+
}
|
|
2428
|
+
/**
|
|
2429
|
+
* A per-SCANNED-ROW byte penalty this node implies beyond its value size — a
|
|
2430
|
+
* proxy for embedding / full-text scan work. `0` (neutral) by default;
|
|
2431
|
+
* `semantic` / `text-search` / `text-score` override. The cost model sums
|
|
2432
|
+
* this across a predicate tree ({@link totalScanRowPenalty}) and multiplies by
|
|
2433
|
+
* the scanned-row count.
|
|
2434
|
+
*/
|
|
2435
|
+
scanRowPenalty() {
|
|
2436
|
+
return 0;
|
|
2437
|
+
}
|
|
2438
|
+
/** This node's scan penalty summed over its whole subtree (per scanned row). */
|
|
2439
|
+
totalScanRowPenalty() {
|
|
2440
|
+
let total = 0;
|
|
2441
|
+
this.walk((e2) => {
|
|
2442
|
+
total += e2.scanRowPenalty();
|
|
2443
|
+
});
|
|
2444
|
+
return total;
|
|
2445
|
+
}
|
|
2446
|
+
/**
|
|
2447
|
+
* Flatten a conjunction: the AND-connected predicates this expr contributes to
|
|
2448
|
+
* a WHERE. A leaf reports `[this]`; a nested `and` (`((a AND b) AND c) AND d`)
|
|
2449
|
+
* flattens RECURSIVELY to `[a, b, c, d]`, so the index / selectivity model
|
|
2450
|
+
* sees every top-level conjunct regardless of nesting. A `filters` placeholder
|
|
2451
|
+
* expands to its execution-time predicate's conjuncts (or none). `ctx` /
|
|
2452
|
+
* `scope` are threaded so that expansion can consult the supplied filters.
|
|
2453
|
+
*/
|
|
2454
|
+
conjuncts(_ctx, _scope) {
|
|
2455
|
+
return [this];
|
|
2456
|
+
}
|
|
2457
|
+
/**
|
|
2458
|
+
* A SHALLOW index-scannable reading of THIS predicate: the column field-ref it
|
|
2459
|
+
* binds to a bounded value set plus that set's `arity` (`col = v` ⇒ 1;
|
|
2460
|
+
* `col IN (a, b, c)` ⇒ 3), or `undefined` when this predicate is not such a
|
|
2461
|
+
* binding. Overridden by `comparison` (`=`) and `in` (value list). Drives
|
|
2462
|
+
* index-prefix matching without the cost model inspecting operand internals.
|
|
2463
|
+
*/
|
|
2464
|
+
indexProbe() {
|
|
2465
|
+
return void 0;
|
|
2466
|
+
}
|
|
2467
|
+
/**
|
|
2468
|
+
* This expr AS a plain column field-ref, or `undefined` when it is anything
|
|
2469
|
+
* else. Overridden by `field-ref` to return itself. Lets the cost model treat
|
|
2470
|
+
* GROUP BY / index keys as columns without an `instanceof`.
|
|
2471
|
+
*/
|
|
2472
|
+
fieldRef() {
|
|
2473
|
+
return void 0;
|
|
2474
|
+
}
|
|
2475
|
+
/**
|
|
2476
|
+
* The operands of a disjunction (`OR`), or `undefined` when this is not one.
|
|
2477
|
+
* Overridden by `logical` (`or`). Lets the affected-row estimator union the
|
|
2478
|
+
* branches (index-merge) without inspecting the concrete class.
|
|
2479
|
+
*/
|
|
2480
|
+
orOperands() {
|
|
2481
|
+
return void 0;
|
|
2482
|
+
}
|
|
2483
|
+
/**
|
|
2484
|
+
* The registered DB FUNCTION this expr calls, or `undefined` when it is not a
|
|
2485
|
+
* call. Overridden by `function-call` / `aggregate` / `window` / tabular calls.
|
|
2486
|
+
* Lets `Query.references` enumerate invoked functions (and fold their
|
|
2487
|
+
* cost / `changes` / referenced Types) without an `instanceof`.
|
|
2488
|
+
*/
|
|
2489
|
+
functionRef() {
|
|
2490
|
+
return void 0;
|
|
2491
|
+
}
|
|
2322
2492
|
/** Sum the costs of this expr's immediate children (a cost building block). */
|
|
2323
|
-
childCost(
|
|
2493
|
+
childCost(ctx, scope) {
|
|
2324
2494
|
let c = ZERO_COST;
|
|
2325
2495
|
this.forEachChild((child) => {
|
|
2326
|
-
c = addCost(c, child.cost(
|
|
2496
|
+
c = addCost(c, child.cost(ctx, scope));
|
|
2327
2497
|
});
|
|
2328
2498
|
return c;
|
|
2329
2499
|
}
|
|
@@ -2432,8 +2602,8 @@ var BoolExpr = class extends Expr {
|
|
|
2432
2602
|
* override this when they imply extra work — `text-search` adds a scan
|
|
2433
2603
|
* penalty, `in` / `exists` add their subquery's scan cost.
|
|
2434
2604
|
*/
|
|
2435
|
-
cost(
|
|
2436
|
-
return this.childCost(
|
|
2605
|
+
cost(ctx, scope) {
|
|
2606
|
+
return this.childCost(ctx, scope);
|
|
2437
2607
|
}
|
|
2438
2608
|
/**
|
|
2439
2609
|
* Default boolean resolution: always a `bool` `ComputedResolved`, with
|
|
@@ -2890,7 +3060,8 @@ var LiteralExpr = class _LiteralExpr extends Expr {
|
|
|
2890
3060
|
return this.resolve(engine, scope);
|
|
2891
3061
|
}
|
|
2892
3062
|
/** Zero rows; cost is just the resolved value's byte size. */
|
|
2893
|
-
cost(
|
|
3063
|
+
cost(ctx, scope) {
|
|
3064
|
+
const engine = ctx.engine;
|
|
2894
3065
|
return { rows: 0, bytes: bytesOfResolved(this.resolve(engine, scope)) };
|
|
2895
3066
|
}
|
|
2896
3067
|
/** Evaluate to the wrapped constant value. */
|
|
@@ -3000,9 +3171,9 @@ var OutputRefExpr = class _OutputRefExpr extends Expr {
|
|
|
3000
3171
|
return resolved;
|
|
3001
3172
|
}
|
|
3002
3173
|
/** Delegate to the target's cost (zero when the reference is unbound). */
|
|
3003
|
-
cost(
|
|
3174
|
+
cost(ctx, scope) {
|
|
3004
3175
|
const target = scope.output(this.name);
|
|
3005
|
-
return target ? target.cost(
|
|
3176
|
+
return target ? target.cost(ctx, scope) : ZERO_COST;
|
|
3006
3177
|
}
|
|
3007
3178
|
/** Re-evaluate the referenced output expr over the same row / group. */
|
|
3008
3179
|
async evaluate(ctx, row, group) {
|
|
@@ -3530,6 +3701,18 @@ var QueryOrder = class _QueryOrder {
|
|
|
3530
3701
|
(v) => new _QueryOrder(v.expr, v.dir, v.nulls),
|
|
3531
3702
|
{ optional: ["nulls"], aid: "Order" }
|
|
3532
3703
|
);
|
|
3704
|
+
/**
|
|
3705
|
+
* The per-row cost of this ORDER BY term — just its sort expression's cost.
|
|
3706
|
+
* Mirrors {@link SorterExpr.cost} so a SELECT can cost every `order` entry
|
|
3707
|
+
* uniformly (concrete term or dynamic sorter) without a type check.
|
|
3708
|
+
*/
|
|
3709
|
+
cost(ctx, scope) {
|
|
3710
|
+
return this.expr.cost(ctx, scope);
|
|
3711
|
+
}
|
|
3712
|
+
/** The exprs this term reads for `references` — a concrete term is just its own expr. */
|
|
3713
|
+
referenceExprs(_spec) {
|
|
3714
|
+
return [this.expr];
|
|
3715
|
+
}
|
|
3533
3716
|
/** Serialize back to an `OrderDef`, omitting `nulls` when unset. */
|
|
3534
3717
|
toJSON() {
|
|
3535
3718
|
const def = { expr: this.expr.toJSON(), dir: this.dir };
|
|
@@ -3717,9 +3900,39 @@ var SorterExpr = class _SorterExpr extends Expr {
|
|
|
3717
3900
|
async evaluate(_ctx, _row, _group) {
|
|
3718
3901
|
return Value.null();
|
|
3719
3902
|
}
|
|
3720
|
-
/**
|
|
3721
|
-
|
|
3722
|
-
|
|
3903
|
+
/**
|
|
3904
|
+
* A sorter's cost is the cost of the catalog entries it could sort BY: the
|
|
3905
|
+
* caller's runtime selection ({@link CostContext.sort}) when supplied, else its
|
|
3906
|
+
* `defaultSort`, else — as a worst case — its WHOLE catalog (any entry could be
|
|
3907
|
+
* chosen at execution time). Each contributes its expr's own cost, so a sort
|
|
3908
|
+
* key that is a SUBQUERY makes the sorter expensive (evaluated per sorted row
|
|
3909
|
+
* by the SELECT), while sorting by a plain column stays cheap.
|
|
3910
|
+
*/
|
|
3911
|
+
cost(ctx, scope) {
|
|
3912
|
+
let c = ZERO_COST;
|
|
3913
|
+
for (const expr of this.chosenSortExprs(ctx)) c = addCost(c, expr.cost(ctx, scope));
|
|
3914
|
+
return c;
|
|
3915
|
+
}
|
|
3916
|
+
/**
|
|
3917
|
+
* The catalog exprs a cost estimate should charge for: the caller's selected
|
|
3918
|
+
* sorts (when a runtime `sort` is supplied), else the `defaultSort`'s sorts,
|
|
3919
|
+
* else every catalog entry (worst case). Selected names absent from the catalog
|
|
3920
|
+
* are skipped (they cost nothing here; a real run reports them loudly).
|
|
3921
|
+
*/
|
|
3922
|
+
chosenSortExprs(ctx) {
|
|
3923
|
+
return this.referenceExprs(ctx.sort);
|
|
3924
|
+
}
|
|
3925
|
+
/**
|
|
3926
|
+
* The catalog exprs a caller's `sort` selection reads (for cost / references):
|
|
3927
|
+
* the selected sorts when a `spec` is supplied, else the `defaultSort`'s sorts,
|
|
3928
|
+
* else every catalog entry (worst case). Selected names absent from the catalog
|
|
3929
|
+
* are skipped.
|
|
3930
|
+
*/
|
|
3931
|
+
referenceExprs(spec) {
|
|
3932
|
+
const pick = (entries) => entries.map((s) => this.sorts.get(s.sort)).filter((e2) => e2 !== void 0);
|
|
3933
|
+
if (spec && spec.length > 0) return pick(spec);
|
|
3934
|
+
if (this.defaultSort && this.defaultSort.length > 0) return pick(this.defaultSort);
|
|
3935
|
+
return [...this.sorts.values()];
|
|
3723
3936
|
}
|
|
3724
3937
|
/** 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
3938
|
toSQL(_dialect, _ctx) {
|
|
@@ -3882,8 +4095,12 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
|
|
|
3882
4095
|
return resolved;
|
|
3883
4096
|
}
|
|
3884
4097
|
/** Zero rows; cost is just the resolved field's byte size. */
|
|
3885
|
-
cost(
|
|
3886
|
-
return { rows: 0, bytes: bytesOfResolved(this.resolve(engine, scope)) };
|
|
4098
|
+
cost(ctx, scope) {
|
|
4099
|
+
return { rows: 0, bytes: bytesOfResolved(this.resolve(ctx.engine, scope)) };
|
|
4100
|
+
}
|
|
4101
|
+
/** A field-ref IS a plain column reference (drives GROUP BY / index-key costing). */
|
|
4102
|
+
fieldRef() {
|
|
4103
|
+
return this;
|
|
3887
4104
|
}
|
|
3888
4105
|
/** Read the field's runtime value, honoring backing (joins/compute/access security). */
|
|
3889
4106
|
async evaluate(ctx, row) {
|
|
@@ -4182,7 +4399,8 @@ var ParamExpr = class _ParamExpr extends Expr {
|
|
|
4182
4399
|
return this.resolve(engine, scope);
|
|
4183
4400
|
}
|
|
4184
4401
|
/** Zero rows; cost is just the resolved type's byte size. */
|
|
4185
|
-
cost(
|
|
4402
|
+
cost(ctx, scope) {
|
|
4403
|
+
const engine = ctx.engine;
|
|
4186
4404
|
return { rows: 0, bytes: bytesOfResolved(this.resolve(engine, scope)) };
|
|
4187
4405
|
}
|
|
4188
4406
|
/** Evaluate to the runtime-bound value for this param name. */
|
|
@@ -4325,8 +4543,8 @@ var BinaryExpr = class _BinaryExpr extends Expr {
|
|
|
4325
4543
|
return this.resolve(engine, scope);
|
|
4326
4544
|
}
|
|
4327
4545
|
/** Cost is the sum of the child operands' costs. */
|
|
4328
|
-
cost(
|
|
4329
|
-
return this.childCost(
|
|
4546
|
+
cost(ctx, scope) {
|
|
4547
|
+
return this.childCost(ctx, scope);
|
|
4330
4548
|
}
|
|
4331
4549
|
/** Evaluate both operands and apply the op (NULL-propagating; `+` concatenates non-numbers). */
|
|
4332
4550
|
async evaluate(ctx, row, group) {
|
|
@@ -4460,8 +4678,8 @@ var UnaryExpr = class _UnaryExpr extends Expr {
|
|
|
4460
4678
|
return this.resolve(engine, scope);
|
|
4461
4679
|
}
|
|
4462
4680
|
/** Cost is the operand's cost. */
|
|
4463
|
-
cost(
|
|
4464
|
-
return this.childCost(
|
|
4681
|
+
cost(ctx, scope) {
|
|
4682
|
+
return this.childCost(ctx, scope);
|
|
4465
4683
|
}
|
|
4466
4684
|
/** Evaluate the operand and apply the sign (NULL/non-numeric → NULL). */
|
|
4467
4685
|
async evaluate(ctx, row, group) {
|
|
@@ -4647,6 +4865,29 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
|
|
|
4647
4865
|
}
|
|
4648
4866
|
return this.resolve(engine, scope);
|
|
4649
4867
|
}
|
|
4868
|
+
/**
|
|
4869
|
+
* WHERE selectivity by operator: a range (`< <= > >=`) keeps ~half the rows;
|
|
4870
|
+
* equality and the equality-like ops (`= <> like notLike ilike`) keep ~a third.
|
|
4871
|
+
* An index-covered `=` is discounted separately by the cost model (via
|
|
4872
|
+
* {@link indexProbe}); this is the non-indexed fallback.
|
|
4873
|
+
*/
|
|
4874
|
+
selectivity() {
|
|
4875
|
+
switch (this.op) {
|
|
4876
|
+
case "<":
|
|
4877
|
+
case "<=":
|
|
4878
|
+
case ">":
|
|
4879
|
+
case ">=":
|
|
4880
|
+
return RANGE_SELECTIVITY;
|
|
4881
|
+
default:
|
|
4882
|
+
return EQ_SELECTIVITY;
|
|
4883
|
+
}
|
|
4884
|
+
}
|
|
4885
|
+
/** An `=` against a column is an index point-probe (arity 1); other ops are not. */
|
|
4886
|
+
indexProbe() {
|
|
4887
|
+
if (this.op !== "=") return void 0;
|
|
4888
|
+
const ref3 = this.left.fieldRef() ?? this.right.fieldRef();
|
|
4889
|
+
return ref3 ? { ref: ref3, arity: 1 } : void 0;
|
|
4890
|
+
}
|
|
4650
4891
|
/** Evaluate under 3VL: a NULL operand yields UNKNOWN; text compares case-insensitively unless a `sensitive` field is involved. */
|
|
4651
4892
|
async evaluateBool(ctx, row, group) {
|
|
4652
4893
|
const l = await this.left.evaluate(ctx, row, group);
|
|
@@ -4808,6 +5049,20 @@ var LogicalExpr = class _LogicalExpr extends BoolExpr {
|
|
|
4808
5049
|
forEachChild(visit) {
|
|
4809
5050
|
for (const o of this.operands) visit(o);
|
|
4810
5051
|
}
|
|
5052
|
+
/**
|
|
5053
|
+
* Flatten an `and` into its constituent conjuncts, RECURSIVELY — so
|
|
5054
|
+
* `((a AND b) AND c) AND d` yields `[a, b, c, d]` and the WHERE cost model sees
|
|
5055
|
+
* every top-level conjunct for selectivity / index matching. `or` / `not` are
|
|
5056
|
+
* opaque (a single conjunct — the default).
|
|
5057
|
+
*/
|
|
5058
|
+
conjuncts(ctx, scope) {
|
|
5059
|
+
if (this.op !== "and") return [this];
|
|
5060
|
+
return this.operands.flatMap((o) => o.conjuncts(ctx, scope));
|
|
5061
|
+
}
|
|
5062
|
+
/** An `or` exposes its operands so the affected-row estimator can union the branches. */
|
|
5063
|
+
orOperands() {
|
|
5064
|
+
return this.op === "or" ? this.operands : void 0;
|
|
5065
|
+
}
|
|
4811
5066
|
/** Validate that each operand is boolean (and that `not` has exactly one operand); resolves to bool. */
|
|
4812
5067
|
validateWalk(engine, scope, p, ctx) {
|
|
4813
5068
|
if (this.op === "not" && this.operands.length !== 1) {
|
|
@@ -5095,11 +5350,24 @@ var InExpr = class _InExpr extends BoolExpr {
|
|
|
5095
5350
|
return this.resolve(engine, scope);
|
|
5096
5351
|
}
|
|
5097
5352
|
/** Estimated cost: children plus the inner query's cost when this is the subquery form. */
|
|
5098
|
-
cost(
|
|
5099
|
-
let c = this.childCost(
|
|
5100
|
-
if (this.subquery) c = addCost(c, engine.parseQuery(this.subquery).cost(
|
|
5353
|
+
cost(ctx, scope) {
|
|
5354
|
+
let c = this.childCost(ctx, scope);
|
|
5355
|
+
if (this.subquery) c = addCost(c, ctx.engine.parseQuery(this.subquery).cost(ctx, scope.child()));
|
|
5101
5356
|
return c;
|
|
5102
5357
|
}
|
|
5358
|
+
/** Membership keeps ~half the rows (matches a non-indexed range's breadth). */
|
|
5359
|
+
selectivity() {
|
|
5360
|
+
return IN_SELECTIVITY;
|
|
5361
|
+
}
|
|
5362
|
+
/**
|
|
5363
|
+
* A `col IN (a, b, c)` value LIST against a column is an index point-probe of
|
|
5364
|
+
* arity = the list length (a `NOT IN` / subquery form is not a point-set).
|
|
5365
|
+
*/
|
|
5366
|
+
indexProbe() {
|
|
5367
|
+
if (!this.list || this.not) return void 0;
|
|
5368
|
+
const ref3 = this.value.fieldRef();
|
|
5369
|
+
return ref3 ? { ref: ref3, arity: this.list.length } : void 0;
|
|
5370
|
+
}
|
|
5103
5371
|
/** 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
5372
|
async evaluateBool(ctx, row, group) {
|
|
5105
5373
|
const v = await this.value.evaluate(ctx, row, group);
|
|
@@ -5263,6 +5531,10 @@ var BetweenExpr = class _BetweenExpr extends BoolExpr {
|
|
|
5263
5531
|
}
|
|
5264
5532
|
return this.resolve(engine, scope);
|
|
5265
5533
|
}
|
|
5534
|
+
/** A range test keeps ~half the rows (range selectivity). */
|
|
5535
|
+
selectivity() {
|
|
5536
|
+
return RANGE_SELECTIVITY;
|
|
5537
|
+
}
|
|
5266
5538
|
/** Evaluate `v >= lo AND v <= hi` under 3VL (a NULL bound makes that side UNKNOWN, but FALSE still dominates); negated for `NOT BETWEEN`. */
|
|
5267
5539
|
async evaluateBool(ctx, row, group) {
|
|
5268
5540
|
const v = await this.value.evaluate(ctx, row, group);
|
|
@@ -5373,6 +5645,10 @@ var IsNullExpr = class _IsNullExpr extends BoolExpr {
|
|
|
5373
5645
|
p.at("value", () => this.value.validateWalk(engine, scope, p, operandCtx(this.value, "is-null", ctx)));
|
|
5374
5646
|
return this.resolve(engine, scope);
|
|
5375
5647
|
}
|
|
5648
|
+
/** A null test keeps ~a third of the rows (equality-like selectivity). */
|
|
5649
|
+
selectivity() {
|
|
5650
|
+
return EQ_SELECTIVITY;
|
|
5651
|
+
}
|
|
5376
5652
|
/** Evaluate the operand and return whether it is (not) null. */
|
|
5377
5653
|
async evaluateBool(ctx, row, group) {
|
|
5378
5654
|
const v = await this.value.evaluate(ctx, row, group);
|
|
@@ -5520,8 +5796,9 @@ var ExistsExpr = class _ExistsExpr extends BoolExpr {
|
|
|
5520
5796
|
return this.resolve(engine, scope);
|
|
5521
5797
|
}
|
|
5522
5798
|
/** Estimated cost: the subquery's scan cost (its own output is a single boolean). */
|
|
5523
|
-
cost(
|
|
5524
|
-
|
|
5799
|
+
cost(ctx, scope) {
|
|
5800
|
+
const engine = ctx.engine;
|
|
5801
|
+
return engine.parseQuery(this.query).cost(ctx, scope.child());
|
|
5525
5802
|
}
|
|
5526
5803
|
/** Execute the correlated subquery and return whether it produced any rows (negated for `NOT EXISTS`). */
|
|
5527
5804
|
async evaluateBool(ctx, row) {
|
|
@@ -5907,8 +6184,8 @@ var CaseExpr = class _CaseExpr extends Expr {
|
|
|
5907
6184
|
return this.resolve(engine, scope);
|
|
5908
6185
|
}
|
|
5909
6186
|
/** Cost is the sum of the child branch costs. */
|
|
5910
|
-
cost(
|
|
5911
|
-
return this.childCost(
|
|
6187
|
+
cost(ctx, scope) {
|
|
6188
|
+
return this.childCost(ctx, scope);
|
|
5912
6189
|
}
|
|
5913
6190
|
/** Return the first matching branch's result, else the `else` result, else NULL. */
|
|
5914
6191
|
async evaluate(ctx, row, group) {
|
|
@@ -6207,8 +6484,12 @@ var AggregateExpr = class _AggregateExpr extends Expr {
|
|
|
6207
6484
|
return this.resolve(engine, scope);
|
|
6208
6485
|
}
|
|
6209
6486
|
/** Cost is the per-arg byte cost (or zero for the arg-less `count(*)`). */
|
|
6210
|
-
cost(
|
|
6211
|
-
return this.args.size === 0 ? { rows: 0, bytes: 0 } : this.childCost(
|
|
6487
|
+
cost(ctx, scope) {
|
|
6488
|
+
return this.args.size === 0 ? { rows: 0, bytes: 0 } : this.childCost(ctx, scope);
|
|
6489
|
+
}
|
|
6490
|
+
/** This expr calls the aggregate function `fn`. */
|
|
6491
|
+
functionRef() {
|
|
6492
|
+
return this.fn;
|
|
6212
6493
|
}
|
|
6213
6494
|
/** Collect each group row's named args (deduped when DISTINCT) and run the registered aggregate. */
|
|
6214
6495
|
async evaluate(ctx, row, group) {
|
|
@@ -6450,8 +6731,12 @@ var WindowExpr = class _WindowExpr extends Expr {
|
|
|
6450
6731
|
return this.resolve(engine, scope);
|
|
6451
6732
|
}
|
|
6452
6733
|
/** Cost is the sum of the child (args/partition/order) costs. */
|
|
6453
|
-
cost(
|
|
6454
|
-
return this.childCost(
|
|
6734
|
+
cost(ctx, scope) {
|
|
6735
|
+
return this.childCost(ctx, scope);
|
|
6736
|
+
}
|
|
6737
|
+
/** This expr calls the window function `fn`. */
|
|
6738
|
+
functionRef() {
|
|
6739
|
+
return this.fn;
|
|
6455
6740
|
}
|
|
6456
6741
|
/** Stable string key of the partition-by values for a row. */
|
|
6457
6742
|
async partitionKey(ctx, row) {
|
|
@@ -6667,9 +6952,15 @@ var FunctionCallExpr = class _FunctionCallExpr extends Expr {
|
|
|
6667
6952
|
observeNamedParams(this.args, fn2, scope, here);
|
|
6668
6953
|
return fn2.resolveOutput(argTypes);
|
|
6669
6954
|
}
|
|
6670
|
-
/** Cost is the
|
|
6671
|
-
cost(
|
|
6672
|
-
|
|
6955
|
+
/** Cost is the argument child costs plus any intrinsic cost the function declares. */
|
|
6956
|
+
cost(ctx, scope) {
|
|
6957
|
+
const args = this.childCost(ctx, scope);
|
|
6958
|
+
const fn2 = ctx.engine.lookupFunction(this.fn);
|
|
6959
|
+
return fn2 ? addCost(args, fn2.cost) : args;
|
|
6960
|
+
}
|
|
6961
|
+
/** This expr calls the scalar function `fn`. */
|
|
6962
|
+
functionRef() {
|
|
6963
|
+
return this.fn;
|
|
6673
6964
|
}
|
|
6674
6965
|
/** Evaluate the named args and run the registered scalar function. */
|
|
6675
6966
|
async evaluate(ctx, row, group) {
|
|
@@ -6793,10 +7084,16 @@ var TabularFunctionCallExpr = class _TabularFunctionCallExpr extends Expr {
|
|
|
6793
7084
|
return this.resolve(engine, scope);
|
|
6794
7085
|
}
|
|
6795
7086
|
/** Cost is the output type's row cardinality plus the argument child costs. */
|
|
6796
|
-
cost(
|
|
7087
|
+
cost(ctx, scope) {
|
|
7088
|
+
const engine = ctx.engine;
|
|
6797
7089
|
const out = this.resolve(engine, scope);
|
|
6798
7090
|
const base = out.kind === "type" ? { rows: out.type.count, bytes: out.type.count * out.type.bytes } : { rows: 0, bytes: 0 };
|
|
6799
|
-
|
|
7091
|
+
const fn2 = engine.lookupFunction(this.fn);
|
|
7092
|
+
return addCost(addCost(base, this.childCost(ctx, scope)), fn2 ? fn2.cost : { rows: 0, bytes: 0 });
|
|
7093
|
+
}
|
|
7094
|
+
/** This expr calls the tabular function `fn`. */
|
|
7095
|
+
functionRef() {
|
|
7096
|
+
return this.fn;
|
|
6800
7097
|
}
|
|
6801
7098
|
/**
|
|
6802
7099
|
* Invoke the function's registered runtime implementation to produce rows.
|
|
@@ -7053,9 +7350,17 @@ var SemanticExpr = class _SemanticExpr extends Expr {
|
|
|
7053
7350
|
p.error("semantic.query-not-semantic", `Field '${q.field}' of '${type.name}' is not semantic.`);
|
|
7054
7351
|
}
|
|
7055
7352
|
}
|
|
7056
|
-
/**
|
|
7057
|
-
cost(
|
|
7058
|
-
return
|
|
7353
|
+
/** A semantic predicate's own value cost is just its operands' (a boolean). */
|
|
7354
|
+
cost(ctx, scope) {
|
|
7355
|
+
return this.childCost(ctx, scope);
|
|
7356
|
+
}
|
|
7357
|
+
/**
|
|
7358
|
+
* Each SCANNED row pays an embedding penalty (a proxy for the similarity
|
|
7359
|
+
* work). Applied per scanned row by the WHERE cost model, rather than folded
|
|
7360
|
+
* once into the value cost (where it was swallowed as a zero-row contribution).
|
|
7361
|
+
*/
|
|
7362
|
+
scanRowPenalty() {
|
|
7363
|
+
return SEMANTIC_ROW_PENALTY;
|
|
7059
7364
|
}
|
|
7060
7365
|
/**
|
|
7061
7366
|
* Embed the query side into a vector (null when unavailable), using the
|
|
@@ -7435,9 +7740,13 @@ var TextSearchExpr = class _TextSearchExpr extends BoolExpr {
|
|
|
7435
7740
|
}
|
|
7436
7741
|
return this.resolve(engine, scope);
|
|
7437
7742
|
}
|
|
7438
|
-
/**
|
|
7439
|
-
cost(
|
|
7440
|
-
return
|
|
7743
|
+
/** A text-search predicate's own value cost is just its operands' (a boolean). */
|
|
7744
|
+
cost(ctx, scope) {
|
|
7745
|
+
return this.childCost(ctx, scope);
|
|
7746
|
+
}
|
|
7747
|
+
/** Each SCANNED row pays a full-text scan penalty (applied per row by the WHERE cost model). */
|
|
7748
|
+
scanRowPenalty() {
|
|
7749
|
+
return TEXT_SEARCH_ROW_PENALTY;
|
|
7441
7750
|
}
|
|
7442
7751
|
/**
|
|
7443
7752
|
* Basic token match: the searched text matches when it contains every
|
|
@@ -7585,9 +7894,13 @@ var TextScoreExpr = class _TextScoreExpr extends Expr {
|
|
|
7585
7894
|
}
|
|
7586
7895
|
return this.resolve(engine, scope);
|
|
7587
7896
|
}
|
|
7588
|
-
/**
|
|
7589
|
-
cost(
|
|
7590
|
-
return
|
|
7897
|
+
/** A text-score's own value cost is just its operands' (it produces a number). */
|
|
7898
|
+
cost(ctx, scope) {
|
|
7899
|
+
return this.childCost(ctx, scope);
|
|
7900
|
+
}
|
|
7901
|
+
/** Scoring implies a full-text scan penalty per scanned row (applied by the WHERE cost model). */
|
|
7902
|
+
scanRowPenalty() {
|
|
7903
|
+
return TEXT_SEARCH_ROW_PENALTY;
|
|
7591
7904
|
}
|
|
7592
7905
|
/**
|
|
7593
7906
|
* A deterministic in-memory relevance in [0, 1]: the FRACTION of the query's
|
|
@@ -7726,6 +8039,28 @@ var FiltersExpr = class _FiltersExpr extends BoolExpr {
|
|
|
7726
8039
|
}
|
|
7727
8040
|
return boolResult([], false, false);
|
|
7728
8041
|
}
|
|
8042
|
+
// ─── Cost ──────────────────────────────────────────────────────────────────
|
|
8043
|
+
/**
|
|
8044
|
+
* Cost of the EXECUTION-TIME predicate bound to this source (from
|
|
8045
|
+
* {@link CostContext.filters}) — so a subquery inside a supplied filter is real
|
|
8046
|
+
* work that raises the estimate. With no predicate supplied the placeholder is
|
|
8047
|
+
* NEUTRAL (zero cost). Its per-row selectivity / penalty / index-probes flow
|
|
8048
|
+
* separately through {@link conjuncts} (the WHERE cost model expands them).
|
|
8049
|
+
*/
|
|
8050
|
+
cost(ctx, scope) {
|
|
8051
|
+
const pred = ctx.filters?.get(this.source);
|
|
8052
|
+
return pred ? pred.cost(ctx, scope) : ZERO_COST;
|
|
8053
|
+
}
|
|
8054
|
+
/**
|
|
8055
|
+
* Expand to the supplied predicate's OWN conjuncts, so the WHERE cost model
|
|
8056
|
+
* applies the real filter's selectivity / index-probes / scan penalties as if
|
|
8057
|
+
* it had been authored inline. With no predicate supplied this contributes NO
|
|
8058
|
+
* conjunct (a neutral, always-true placeholder).
|
|
8059
|
+
*/
|
|
8060
|
+
conjuncts(ctx, scope) {
|
|
8061
|
+
const pred = ctx.filters?.get(this.source);
|
|
8062
|
+
return pred ? pred.conjuncts(ctx, scope) : [];
|
|
8063
|
+
}
|
|
7729
8064
|
// ─── Evaluation ────────────────────────────────────────────────────────────
|
|
7730
8065
|
/**
|
|
7731
8066
|
* Evaluate the execution-supplied bool expr for this source (TRUE when none).
|
|
@@ -7865,8 +8200,9 @@ var SubqueryExpr = class _SubqueryExpr extends Expr {
|
|
|
7865
8200
|
return p.at("query", () => validateSubqueryOutput(engine, scope, p, ctx, this.query));
|
|
7866
8201
|
}
|
|
7867
8202
|
/** Cost of running the inner query in a child scope. */
|
|
7868
|
-
cost(
|
|
7869
|
-
|
|
8203
|
+
cost(ctx, scope) {
|
|
8204
|
+
const engine = ctx.engine;
|
|
8205
|
+
return engine.parseQuery(this.query).cost(ctx, scope.child());
|
|
7870
8206
|
}
|
|
7871
8207
|
/** Execute the subquery (correlated to `row` when present) and return its first field. */
|
|
7872
8208
|
async evaluate(ctx, row) {
|
|
@@ -7967,7 +8303,8 @@ var ExcludedExpr = class _ExcludedExpr extends Expr {
|
|
|
7967
8303
|
return resolved;
|
|
7968
8304
|
}
|
|
7969
8305
|
/** Byte cost of the resolved field value (no rows). */
|
|
7970
|
-
cost(
|
|
8306
|
+
cost(ctx, scope) {
|
|
8307
|
+
const engine = ctx.engine;
|
|
7971
8308
|
return { rows: 0, bytes: bytesOfResolved(this.resolve(engine, scope)) };
|
|
7972
8309
|
}
|
|
7973
8310
|
/** Read the proposed row's value for this field (null when absent). */
|
|
@@ -8030,6 +8367,49 @@ function exprDefSchema(opts = {}) {
|
|
|
8030
8367
|
}
|
|
8031
8368
|
|
|
8032
8369
|
// src/queries/query.ts
|
|
8370
|
+
function mergeReferences(parts) {
|
|
8371
|
+
const types = /* @__PURE__ */ new Set();
|
|
8372
|
+
const functions = /* @__PURE__ */ new Set();
|
|
8373
|
+
const fields = /* @__PURE__ */ new Map();
|
|
8374
|
+
for (const part of parts) {
|
|
8375
|
+
for (const t of part.types) types.add(t);
|
|
8376
|
+
for (const f of part.functions) functions.add(f);
|
|
8377
|
+
for (const fld of part.fields) fields.set(`${fld.type}.${fld.field}`, fld);
|
|
8378
|
+
}
|
|
8379
|
+
return { types: [...types], fields: [...fields.values()], functions: [...functions] };
|
|
8380
|
+
}
|
|
8381
|
+
var ReferenceCollector = class {
|
|
8382
|
+
constructor(engine, scope, seedTypes) {
|
|
8383
|
+
this.engine = engine;
|
|
8384
|
+
this.scope = scope;
|
|
8385
|
+
for (const t of seedTypes) this.types.add(t);
|
|
8386
|
+
}
|
|
8387
|
+
engine;
|
|
8388
|
+
scope;
|
|
8389
|
+
types = /* @__PURE__ */ new Set();
|
|
8390
|
+
fields = /* @__PURE__ */ new Map();
|
|
8391
|
+
functions = /* @__PURE__ */ new Set();
|
|
8392
|
+
/** Inspect ONE expr node: note a function call (+ Types it reads) and, when scoped, a field-ref. */
|
|
8393
|
+
note(n) {
|
|
8394
|
+
const fn2 = n.functionRef();
|
|
8395
|
+
if (fn2 !== void 0) {
|
|
8396
|
+
this.functions.add(fn2);
|
|
8397
|
+
const f = this.engine.lookupFunction(fn2);
|
|
8398
|
+
if (f) for (const t of f.references) this.types.add(t);
|
|
8399
|
+
}
|
|
8400
|
+
if (!this.scope) return;
|
|
8401
|
+
const fr = n.fieldRef();
|
|
8402
|
+
if (!fr) return;
|
|
8403
|
+
const rt = fr.resolve(this.engine, this.scope);
|
|
8404
|
+
if (rt.kind === "field") {
|
|
8405
|
+
this.types.add(rt.type.name);
|
|
8406
|
+
this.fields.set(`${rt.type.name}.${rt.field.name}`, { type: rt.type.name, field: rt.field.name });
|
|
8407
|
+
}
|
|
8408
|
+
}
|
|
8409
|
+
result() {
|
|
8410
|
+
return { types: [...this.types], fields: [...this.fields.values()], functions: [...this.functions] };
|
|
8411
|
+
}
|
|
8412
|
+
};
|
|
8033
8413
|
var Query = class {
|
|
8034
8414
|
/**
|
|
8035
8415
|
* Resolve this query's output as a single `ResolvedType`: the lone field's
|
|
@@ -8175,6 +8555,57 @@ var Query = class {
|
|
|
8175
8555
|
});
|
|
8176
8556
|
return out;
|
|
8177
8557
|
}
|
|
8558
|
+
/**
|
|
8559
|
+
* Estimate the SIZE OF THE RESULT this query returns — output `rows` (capped by
|
|
8560
|
+
* a literal or param-resolved LIMIT / OFFSET) sized by the PROJECTION width,
|
|
8561
|
+
* not the whole scanned row. Distinct from {@link cost} (the WORK to produce
|
|
8562
|
+
* it). The base default is the processing cost; `SelectQuery` / set-operations
|
|
8563
|
+
* / CTEs refine it.
|
|
8564
|
+
*/
|
|
8565
|
+
outputCost(ctx, scope) {
|
|
8566
|
+
return this.cost(ctx, scope);
|
|
8567
|
+
}
|
|
8568
|
+
/**
|
|
8569
|
+
* Estimate the rows this statement MUTATES — a total plus a per-Type breakdown
|
|
8570
|
+
* ({@link Affected}). A read-only query is `{ rows: 0, types: [] }` (the
|
|
8571
|
+
* default); INSERT / UPDATE / DELETE name their target Type, and a CTE
|
|
8572
|
+
* statement SUMS its data-modifying entries plus the final query per Type.
|
|
8573
|
+
*/
|
|
8574
|
+
affected(_ctx, _scope) {
|
|
8575
|
+
return AFFECTED_NONE;
|
|
8576
|
+
}
|
|
8577
|
+
/**
|
|
8578
|
+
* Enumerate what this query READS — the {@link QueryReferences} of Types,
|
|
8579
|
+
* specific fields, and DB functions it touches — INCLUDING execution-time
|
|
8580
|
+
* `filters` predicates and the `sort`-selected sorter catalog exprs (both from
|
|
8581
|
+
* `ctx`). Drives `engine.changeInterval` (freshness). The base collects Types
|
|
8582
|
+
* (from {@link referencedTypes}) + functions (+ any Types a function reads);
|
|
8583
|
+
* `SelectQuery` / set-ops / CTEs override to add the specific FIELDS read,
|
|
8584
|
+
* resolved against their bound scope ({@link referenceScope}).
|
|
8585
|
+
*/
|
|
8586
|
+
references(engine, scope, ctx) {
|
|
8587
|
+
const c = new ReferenceCollector(engine, this.referenceScope(engine, scope), this.referencedTypes());
|
|
8588
|
+
this.forEachReferenceNode(ctx, (n) => c.note(n));
|
|
8589
|
+
if (ctx.filters) for (const pred of ctx.filters.values()) pred.walk((n) => c.note(n));
|
|
8590
|
+
return c.result();
|
|
8591
|
+
}
|
|
8592
|
+
/**
|
|
8593
|
+
* The bound scope a `references` walk resolves its field-refs against, or
|
|
8594
|
+
* `undefined` when this query has no meaningful binding (so field-refs are not
|
|
8595
|
+
* resolved — only Types + functions are collected). Overridden by queries that
|
|
8596
|
+
* bind sources (`SelectQuery` returns its sorter scope).
|
|
8597
|
+
*/
|
|
8598
|
+
referenceScope(_engine, _scope) {
|
|
8599
|
+
return void 0;
|
|
8600
|
+
}
|
|
8601
|
+
/**
|
|
8602
|
+
* Visit every expr NODE `references` should inspect. The default recurses every
|
|
8603
|
+
* clause expr ({@link walkExprs}); `SelectQuery` overrides to expand a `sorter`
|
|
8604
|
+
* to only its `ctx.sort`-SELECTED catalog exprs (not the whole catalog).
|
|
8605
|
+
*/
|
|
8606
|
+
forEachReferenceNode(_ctx, visit) {
|
|
8607
|
+
this.walkExprs(visit);
|
|
8608
|
+
}
|
|
8178
8609
|
/**
|
|
8179
8610
|
* Emit this query as a leading-`WITH`-free BODY plus the TOP-LEVEL CTE
|
|
8180
8611
|
* definitions it would otherwise prepend itself. The default returns no CTEs
|
|
@@ -8843,20 +9274,21 @@ function scanCost(type) {
|
|
|
8843
9274
|
function floor1(n) {
|
|
8844
9275
|
return Math.max(1, n);
|
|
8845
9276
|
}
|
|
8846
|
-
function
|
|
8847
|
-
|
|
8848
|
-
if (cmp.right instanceof FieldRefExpr) return cmp.right;
|
|
8849
|
-
return void 0;
|
|
9277
|
+
function conjunctsOf(ctx, scope, where) {
|
|
9278
|
+
return where.flatMap((w) => [...w.conjuncts(ctx, scope)]);
|
|
8850
9279
|
}
|
|
8851
|
-
function
|
|
8852
|
-
const
|
|
8853
|
-
for (const
|
|
8854
|
-
|
|
8855
|
-
|
|
8856
|
-
if (fr) refs.push(fr);
|
|
8857
|
-
}
|
|
9280
|
+
function probesOf(conjuncts) {
|
|
9281
|
+
const probes = [];
|
|
9282
|
+
for (const c of conjuncts) {
|
|
9283
|
+
const probe = c.indexProbe();
|
|
9284
|
+
if (probe) probes.push(probe);
|
|
8858
9285
|
}
|
|
8859
|
-
return
|
|
9286
|
+
return probes;
|
|
9287
|
+
}
|
|
9288
|
+
function indexPartDigests(type) {
|
|
9289
|
+
const digests = /* @__PURE__ */ new Set();
|
|
9290
|
+
for (const idx of type.indexes) for (const part of idx.parts) digests.add(part.digest);
|
|
9291
|
+
return digests;
|
|
8860
9292
|
}
|
|
8861
9293
|
function bestPrefixReduction(type, refs) {
|
|
8862
9294
|
if (refs.length === 0) return void 0;
|
|
@@ -8868,85 +9300,126 @@ function bestPrefixReduction(type, refs) {
|
|
|
8868
9300
|
}
|
|
8869
9301
|
return best;
|
|
8870
9302
|
}
|
|
8871
|
-
function
|
|
8872
|
-
|
|
8873
|
-
|
|
8874
|
-
|
|
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);
|
|
9303
|
+
function indexArityFactor(partDigests, probes) {
|
|
9304
|
+
let factor = 1;
|
|
9305
|
+
for (const pr of probes) {
|
|
9306
|
+
if (pr.arity > 1 && partDigests.has(exprDigest(pr.ref.toJSON()))) factor *= pr.arity;
|
|
8881
9307
|
}
|
|
8882
|
-
|
|
8883
|
-
|
|
8884
|
-
|
|
9308
|
+
return factor;
|
|
9309
|
+
}
|
|
9310
|
+
function applyWhere(ctx, scope, base, type, where, perRowBytes) {
|
|
9311
|
+
const conjuncts = conjunctsOf(ctx, scope, where);
|
|
9312
|
+
const rows = reduceRows(ctx, scope, type, base.rows, conjuncts);
|
|
9313
|
+
const penalty = conjuncts.reduce((sum2, c) => sum2 + c.totalScanRowPenalty(), 0) * base.rows;
|
|
9314
|
+
return { rows, bytes: rows * perRowBytes + penalty };
|
|
9315
|
+
}
|
|
9316
|
+
function reduceRows(ctx, scope, type, baseRows, conjuncts) {
|
|
9317
|
+
const probes = probesOf(conjuncts);
|
|
9318
|
+
const partDigests = indexPartDigests(type);
|
|
9319
|
+
const reduction = bestPrefixReduction(type, probes.map((p) => p.ref));
|
|
9320
|
+
let rows = baseRows;
|
|
9321
|
+
for (const c of conjuncts) {
|
|
9322
|
+
const probe = c.indexProbe();
|
|
9323
|
+
if (reduction !== void 0 && probe && partDigests.has(exprDigest(probe.ref.toJSON()))) continue;
|
|
9324
|
+
rows = floor1(rows * c.selectivity(ctx, scope));
|
|
9325
|
+
}
|
|
9326
|
+
if (reduction !== void 0) rows = Math.min(rows, floor1(reduction * indexArityFactor(partDigests, probes)));
|
|
8885
9327
|
return rows;
|
|
8886
9328
|
}
|
|
8887
|
-
function
|
|
8888
|
-
|
|
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;
|
|
9329
|
+
function matchedRows(ctx, scope, type, where) {
|
|
9330
|
+
return andMatch(ctx, scope, type, type.count, conjunctsOf(ctx, scope, where));
|
|
8896
9331
|
}
|
|
8897
|
-
function
|
|
8898
|
-
|
|
8899
|
-
const
|
|
8900
|
-
|
|
8901
|
-
for (const
|
|
8902
|
-
|
|
8903
|
-
|
|
8904
|
-
|
|
9332
|
+
function andMatch(ctx, scope, type, base, conjuncts) {
|
|
9333
|
+
const ors = conjuncts.filter((c) => c.orOperands() !== void 0);
|
|
9334
|
+
const rest = conjuncts.filter((c) => c.orOperands() === void 0);
|
|
9335
|
+
let rows = reduceRows(ctx, scope, type, base, rest);
|
|
9336
|
+
for (const or2 of ors) rows = floor1(rows * orFraction(ctx, scope, type, or2));
|
|
9337
|
+
return rows;
|
|
9338
|
+
}
|
|
9339
|
+
function orFraction(ctx, scope, type, orExpr) {
|
|
9340
|
+
let none = 1;
|
|
9341
|
+
for (const operand of orExpr.orOperands()) {
|
|
9342
|
+
const branch = andMatch(ctx, scope, type, type.count, operand.conjuncts(ctx, scope));
|
|
9343
|
+
none *= 1 - branch / type.count;
|
|
9344
|
+
}
|
|
9345
|
+
return 1 - none;
|
|
8905
9346
|
}
|
|
8906
9347
|
function distinctEstimate(type, groupBy, scannedRows) {
|
|
8907
9348
|
if (groupBy.length === 1) {
|
|
8908
|
-
const
|
|
8909
|
-
if (
|
|
8910
|
-
const reduction = bestPrefixReduction(type, [
|
|
9349
|
+
const ref3 = groupBy[0].fieldRef();
|
|
9350
|
+
if (ref3) {
|
|
9351
|
+
const reduction = bestPrefixReduction(type, [ref3]);
|
|
8911
9352
|
if (reduction !== void 0) return Math.max(1, reduction);
|
|
8912
9353
|
}
|
|
8913
9354
|
}
|
|
8914
9355
|
return Math.max(1, Math.ceil(Math.sqrt(Math.max(1, scannedRows))));
|
|
8915
9356
|
}
|
|
9357
|
+
function coveredScanBytes(ctx, scope, fromType, fromAlias, fields, where) {
|
|
9358
|
+
const refs = [];
|
|
9359
|
+
let simple = true;
|
|
9360
|
+
const collect = (e2) => {
|
|
9361
|
+
e2.walk((n) => {
|
|
9362
|
+
if (n.cost(ctx, scope).rows > 0) simple = false;
|
|
9363
|
+
const r = n.fieldRef();
|
|
9364
|
+
if (!r) return;
|
|
9365
|
+
if (r.source !== fromAlias) simple = false;
|
|
9366
|
+
else refs.push(r);
|
|
9367
|
+
});
|
|
9368
|
+
};
|
|
9369
|
+
for (const e2 of fields) collect(e2);
|
|
9370
|
+
for (const w of where) collect(w);
|
|
9371
|
+
if (!simple || refs.length === 0) return void 0;
|
|
9372
|
+
const refDigests = new Set(refs.map((r) => exprDigest(r.toJSON())));
|
|
9373
|
+
const probes = probesOf(conjunctsOf(ctx, scope, where));
|
|
9374
|
+
if (probes.length === 0) return void 0;
|
|
9375
|
+
for (const idx of fromType.indexes) {
|
|
9376
|
+
const partDigests = indexPartDigestsOf(idx.parts);
|
|
9377
|
+
const allColumnsIndexed = [...refDigests].every((d) => partDigests.has(d));
|
|
9378
|
+
const whereProbesIndex = probes.some((p) => partDigests.has(exprDigest(p.ref.toJSON())));
|
|
9379
|
+
if (allColumnsIndexed && whereProbesIndex) return idx.bytes(fromType);
|
|
9380
|
+
}
|
|
9381
|
+
return void 0;
|
|
9382
|
+
}
|
|
9383
|
+
function indexPartDigestsOf(parts) {
|
|
9384
|
+
return new Set(parts.map((p) => p.digest));
|
|
9385
|
+
}
|
|
8916
9386
|
function fanOutCost(exprCost, runs) {
|
|
8917
9387
|
if (exprCost.rows <= 0) return ZERO_COST;
|
|
8918
9388
|
const n = Math.max(0, runs);
|
|
8919
9389
|
return { rows: exprCost.rows * n, bytes: exprCost.bytes * n };
|
|
8920
9390
|
}
|
|
8921
|
-
function backingCost(
|
|
9391
|
+
function backingCost(ctx, scope, fieldExprs, fromType, outputRows) {
|
|
9392
|
+
const engine = ctx.engine;
|
|
8922
9393
|
let cost = ZERO_COST;
|
|
8923
9394
|
const rlsPred = engine.backing(fromType.name)?.rls()?.expr?.(fromType.name);
|
|
8924
9395
|
if (rlsPred !== void 0 && typeof rlsPred !== "boolean") {
|
|
8925
|
-
cost = addCost(cost, rlsPred.cost(
|
|
9396
|
+
cost = addCost(cost, rlsPred.cost(ctx, scope));
|
|
8926
9397
|
}
|
|
8927
9398
|
const counted = /* @__PURE__ */ new Set();
|
|
8928
9399
|
for (const expr of fieldExprs) {
|
|
8929
9400
|
expr.walk((e2) => {
|
|
8930
|
-
|
|
8931
|
-
|
|
9401
|
+
const ref3 = e2.fieldRef();
|
|
9402
|
+
if (!ref3) return;
|
|
9403
|
+
const bound = scope.lookup(ref3.source);
|
|
8932
9404
|
if (!bound || bound.kind !== "type") return;
|
|
8933
|
-
const names = engine.fieldBacking(bound.type.name,
|
|
9405
|
+
const names = engine.fieldBacking(bound.type.name, ref3.field)?.joins;
|
|
8934
9406
|
if (!names) return;
|
|
8935
9407
|
for (const name of names) {
|
|
8936
|
-
const alias = joinAlias(
|
|
9408
|
+
const alias = joinAlias(ref3.source, name);
|
|
8937
9409
|
if (counted.has(alias)) continue;
|
|
8938
9410
|
counted.add(alias);
|
|
8939
9411
|
const jb = engine.joinBacking(bound.type.name, name);
|
|
8940
9412
|
if (!jb?.expr) continue;
|
|
8941
|
-
cost = addCost(cost, joinSpecCost(
|
|
9413
|
+
cost = addCost(cost, joinSpecCost(ctx, scope, ref3.source, jb.expr(ref3.source), outputRows));
|
|
8942
9414
|
}
|
|
8943
9415
|
});
|
|
8944
9416
|
}
|
|
8945
9417
|
return cost;
|
|
8946
9418
|
}
|
|
8947
|
-
function joinSpecCost(
|
|
9419
|
+
function joinSpecCost(ctx, scope, outer, spec, outputRows) {
|
|
9420
|
+
const engine = ctx.engine;
|
|
8948
9421
|
if (spec.kind === "lateral") {
|
|
8949
|
-
const inner = engine.coerceQuery(spec.query(outer)).cost(
|
|
9422
|
+
const inner = engine.coerceQuery(spec.query(outer)).cost(ctx, scope.child());
|
|
8950
9423
|
const runs = Math.max(0, outputRows);
|
|
8951
9424
|
return { rows: inner.rows * runs, bytes: inner.bytes * runs };
|
|
8952
9425
|
}
|
|
@@ -9860,6 +10333,24 @@ var SelectQuery = class _SelectQuery extends Query {
|
|
|
9860
10333
|
filterScope(engine, scope) {
|
|
9861
10334
|
return this.bind(engine, scope).scope;
|
|
9862
10335
|
}
|
|
10336
|
+
/** Resolve `references` field-refs against FROM + joins + this SELECT's outputs. */
|
|
10337
|
+
referenceScope(engine, scope) {
|
|
10338
|
+
return this.sorterScope(engine, scope);
|
|
10339
|
+
}
|
|
10340
|
+
/**
|
|
10341
|
+
* Visit the nodes `references` inspects: every field / WHERE / GROUP BY /
|
|
10342
|
+
* HAVING / join-`and` expr, plus — for each `order` entry — only the exprs its
|
|
10343
|
+
* `ctx.sort` SELECTION reads (a `sorter` expands to its selected / default /
|
|
10344
|
+
* whole catalog, never blindly all of it).
|
|
10345
|
+
*/
|
|
10346
|
+
forEachReferenceNode(ctx, visit) {
|
|
10347
|
+
for (const c of this.fields) c.expr.walk(visit);
|
|
10348
|
+
for (const w of this.where) w.walk(visit);
|
|
10349
|
+
for (const g of this.groupBy) g.walk(visit);
|
|
10350
|
+
for (const h of this.having) h.walk(visit);
|
|
10351
|
+
for (const o of this.order) for (const e2 of o.referenceExprs(ctx.sort)) e2.walk(visit);
|
|
10352
|
+
for (const j of this.joins) if (j.and) j.and.walk(visit);
|
|
10353
|
+
}
|
|
9863
10354
|
/**
|
|
9864
10355
|
* The scope a `sorter`'s catalog exprs resolve in for `sorters()` introspection:
|
|
9865
10356
|
* FROM + joins PLUS this SELECT's outputs (so an `output`-ref sort resolves),
|
|
@@ -9953,7 +10444,15 @@ var SelectQuery = class _SelectQuery extends Query {
|
|
|
9953
10444
|
* distinct groups (the upstream scan work is unchanged).
|
|
9954
10445
|
* - LIMIT caps OUTPUT rows. ASSUMPTION: a literal LIMIT also caps how many
|
|
9955
10446
|
* times a select-position subquery runs (it is evaluated once per RETURNED
|
|
9956
|
-
* row)
|
|
10447
|
+
* row).
|
|
10448
|
+
* - ORDER BY evaluates each order term (a concrete term or an EXPANDED
|
|
10449
|
+
* `sorter`) once per row reaching the sort — the PRE-LIMIT output count — so
|
|
10450
|
+
* a subquery inside a sort key (or a runtime-selected sorter entry) is real
|
|
10451
|
+
* per-row work; a plain-column sort adds nothing. We do not model an ORDER
|
|
10452
|
+
* BY forcing a larger upstream scan.
|
|
10453
|
+
* - INDEX-ONLY (covered) scan: with no joins / grouping / distinct / aggregate,
|
|
10454
|
+
* when every column referenced in SELECT + WHERE is a part of one index the
|
|
10455
|
+
* WHERE probes, the scan is sized by the index ENTRY bytes, not full rows.
|
|
9957
10456
|
* - PER-OUTER-ROW work: a subquery / EXISTS / IN-subquery in a SELECT item
|
|
9958
10457
|
* runs ONCE PER OUTPUT ROW, so its cost is multiplied by the output row
|
|
9959
10458
|
* count; the same expr in WHERE / HAVING is treated as uncorrelated and
|
|
@@ -9961,7 +10460,43 @@ var SelectQuery = class _SelectQuery extends Query {
|
|
|
9961
10460
|
* `backingCost` (a LATERAL multiplies per outer row; a shared relation join
|
|
9962
10461
|
* is counted once).
|
|
9963
10462
|
*/
|
|
9964
|
-
cost(
|
|
10463
|
+
cost(ctx, scope) {
|
|
10464
|
+
const { inner, fromType, perRowBytes, matchedRows: matchedRows2 } = this.matchedEstimate(ctx, scope);
|
|
10465
|
+
const preLimitRows = matchedRows2;
|
|
10466
|
+
const limit = this.boundValue(this.limit, ctx);
|
|
10467
|
+
const outputRows = limit !== void 0 ? Math.min(matchedRows2, limit) : matchedRows2;
|
|
10468
|
+
let cost = { rows: outputRows, bytes: outputRows * perRowBytes };
|
|
10469
|
+
for (const c of this.fields) cost = addCost(cost, fanOutCost(c.expr.cost(ctx, inner), outputRows));
|
|
10470
|
+
for (const w of this.where) cost = addCost(cost, fanOutCost(w.cost(ctx, inner), 1));
|
|
10471
|
+
for (const h of this.having) cost = addCost(cost, fanOutCost(h.cost(ctx, inner), 1));
|
|
10472
|
+
for (const o of this.order) cost = addCost(cost, fanOutCost(o.cost(ctx, inner), preLimitRows));
|
|
10473
|
+
cost = addCost(cost, backingCost(ctx, inner, this.fields.map((c) => c.expr), fromType, outputRows));
|
|
10474
|
+
return cost;
|
|
10475
|
+
}
|
|
10476
|
+
/**
|
|
10477
|
+
* Estimate the RESULT SIZE this SELECT returns: the delivered row count (after
|
|
10478
|
+
* WHERE / GROUP / DISTINCT, then OFFSET dropped and LIMIT capped — each a
|
|
10479
|
+
* literal or a `ctx.params`-resolved value) sized by the PROJECTION width — the
|
|
10480
|
+
* sum of the selected columns' byte widths, NOT the whole scanned row. Contrast
|
|
10481
|
+
* {@link cost}, which totals the WORK (fan-out, subquery scans, penalties).
|
|
10482
|
+
*/
|
|
10483
|
+
outputCost(ctx, scope) {
|
|
10484
|
+
const { inner, matchedRows: matchedRows2 } = this.matchedEstimate(ctx, scope);
|
|
10485
|
+
const available = Math.max(0, matchedRows2 - (this.boundValue(this.offset, ctx) ?? 0));
|
|
10486
|
+
const limit = this.boundValue(this.limit, ctx);
|
|
10487
|
+
const rows = limit !== void 0 ? Math.min(available, limit) : available;
|
|
10488
|
+
const width = this.fields.reduce((w, c) => w + bytesOfResolved(c.expr.resolve(ctx.engine, inner)), 0);
|
|
10489
|
+
return { rows, bytes: rows * width };
|
|
10490
|
+
}
|
|
10491
|
+
/**
|
|
10492
|
+
* The shared row estimate both {@link cost} and {@link outputCost} build on:
|
|
10493
|
+
* base scan × join fan-out, reduced by WHERE (index / selectivity), then
|
|
10494
|
+
* collapsed by GROUP BY / a bare aggregate / DISTINCT — the PRE-LIMIT matched
|
|
10495
|
+
* row count — plus the (possibly index-only) per-row scan byte width and the
|
|
10496
|
+
* bound inner scope.
|
|
10497
|
+
*/
|
|
10498
|
+
matchedEstimate(ctx, scope) {
|
|
10499
|
+
const engine = ctx.engine;
|
|
9965
10500
|
const { scope: inner, aliasTypes } = this.bind(engine, scope);
|
|
9966
10501
|
const fromType = this.from.resolvedType(engine, inner).type;
|
|
9967
10502
|
let rows = fromType.count;
|
|
@@ -9971,10 +10506,14 @@ var SelectQuery = class _SelectQuery extends Query {
|
|
|
9971
10506
|
const plan = join2.buildPlan(engine, aliasTypes);
|
|
9972
10507
|
if (plan) for (const hop of plan) perRowBytes += hop.targetType.bytes;
|
|
9973
10508
|
}
|
|
10509
|
+
if (!this.joins.length && !this.groupBy.length && !this.distinct && !this.fields.some((c) => c.expr.containsAggregate())) {
|
|
10510
|
+
const covered = coveredScanBytes(ctx, inner, fromType, this.from.alias, this.fields.map((c) => c.expr), this.where);
|
|
10511
|
+
if (covered !== void 0) perRowBytes = covered;
|
|
10512
|
+
}
|
|
9974
10513
|
const baseScan = scanCost(fromType);
|
|
9975
10514
|
baseScan.rows = rows;
|
|
9976
10515
|
baseScan.bytes = rows * perRowBytes;
|
|
9977
|
-
let cost = applyWhere(baseScan, fromType, this.where, perRowBytes);
|
|
10516
|
+
let cost = applyWhere(ctx, inner, baseScan, fromType, this.where, perRowBytes);
|
|
9978
10517
|
if (this.groupBy.length) {
|
|
9979
10518
|
const distinct = distinctEstimate(fromType, this.groupBy, cost.rows);
|
|
9980
10519
|
cost = { rows: distinct, bytes: distinct * perRowBytes };
|
|
@@ -9984,16 +10523,14 @@ var SelectQuery = class _SelectQuery extends Query {
|
|
|
9984
10523
|
const distinct = distinctEstimate(fromType, this.fields.map((c) => c.expr), cost.rows);
|
|
9985
10524
|
cost = { rows: distinct, bytes: distinct * perRowBytes };
|
|
9986
10525
|
}
|
|
9987
|
-
|
|
9988
|
-
|
|
9989
|
-
|
|
9990
|
-
|
|
9991
|
-
|
|
9992
|
-
|
|
9993
|
-
|
|
9994
|
-
|
|
9995
|
-
cost = addCost(cost, backingCost(engine, inner, this.fields.map((c) => c.expr), fromType, outputRows));
|
|
9996
|
-
return cost;
|
|
10526
|
+
return { inner, fromType, perRowBytes, matchedRows: cost.rows };
|
|
10527
|
+
}
|
|
10528
|
+
/** Resolve a LIMIT / OFFSET bound to a number: a literal, else a `ctx.params` value, else undefined. */
|
|
10529
|
+
boundValue(v, ctx) {
|
|
10530
|
+
if (v === void 0) return void 0;
|
|
10531
|
+
if (typeof v === "number") return v;
|
|
10532
|
+
const raw2 = ctx.params?.[v.name];
|
|
10533
|
+
return typeof raw2 === "number" ? raw2 : void 0;
|
|
9997
10534
|
}
|
|
9998
10535
|
// ─── Execution ─────────────────────────────────────────────────────────
|
|
9999
10536
|
/** Root Type for join planning (FROM source's type). */
|
|
@@ -10753,14 +11290,19 @@ var InsertQuery = class _InsertQuery extends Query {
|
|
|
10753
11290
|
return [...out];
|
|
10754
11291
|
}
|
|
10755
11292
|
/** Estimate `{ rows, bytes }`: the VALUES row count (or the source query's rows) at the target's per-row size. */
|
|
10756
|
-
cost(
|
|
10757
|
-
const type = engine.type(this.into);
|
|
11293
|
+
cost(ctx, scope) {
|
|
11294
|
+
const type = ctx.engine.type(this.into);
|
|
10758
11295
|
const perRow = type ? type.bytes : 0;
|
|
10759
11296
|
let rows = 0;
|
|
10760
11297
|
if (this.rows) rows = this.rows.length;
|
|
10761
|
-
else if (this.select) rows = this.select.cost(
|
|
11298
|
+
else if (this.select) rows = this.select.cost(ctx, scope).rows;
|
|
10762
11299
|
return { rows, bytes: rows * perRow };
|
|
10763
11300
|
}
|
|
11301
|
+
/** Rows this INSERT adds (on `into`): the VALUES row count, or the source SELECT's output rows. */
|
|
11302
|
+
affected(ctx, scope) {
|
|
11303
|
+
const rows = this.rows ? this.rows.length : this.select ? this.select.outputCost(ctx, scope).rows : 0;
|
|
11304
|
+
return affectedOne(this.into, rows);
|
|
11305
|
+
}
|
|
10764
11306
|
/** Materialize rows into the target's `TypeState`, applying ON CONFLICT, then project RETURNING. */
|
|
10765
11307
|
async execute(ctx) {
|
|
10766
11308
|
const engine = ctx.engine;
|
|
@@ -11100,7 +11642,8 @@ var UpdateQuery = class _UpdateQuery extends Query {
|
|
|
11100
11642
|
return [this.type];
|
|
11101
11643
|
}
|
|
11102
11644
|
/** Estimate `{ rows, bytes }`: the target scan × join fan-out, reduced by WHERE. */
|
|
11103
|
-
cost(
|
|
11645
|
+
cost(ctx, scope) {
|
|
11646
|
+
const engine = ctx.engine;
|
|
11104
11647
|
const type = engine.type(this.type);
|
|
11105
11648
|
if (!type) return { rows: 0, bytes: 0 };
|
|
11106
11649
|
const { aliasTypes } = this.bind(engine, scope);
|
|
@@ -11114,7 +11657,13 @@ var UpdateQuery = class _UpdateQuery extends Query {
|
|
|
11114
11657
|
const baseScan = scanCost(type);
|
|
11115
11658
|
baseScan.rows = rows;
|
|
11116
11659
|
baseScan.bytes = rows * perRowBytes;
|
|
11117
|
-
return applyWhere(baseScan, type, this.where, perRowBytes);
|
|
11660
|
+
return applyWhere(ctx, scope, baseScan, type, this.where, perRowBytes);
|
|
11661
|
+
}
|
|
11662
|
+
/** Rows this UPDATE mutates: the target type's rows matching WHERE (index / selectivity / OR-aware). */
|
|
11663
|
+
affected(ctx, scope) {
|
|
11664
|
+
const type = ctx.engine.type(this.type);
|
|
11665
|
+
if (!type) return AFFECTED_NONE;
|
|
11666
|
+
return affectedOne(this.type, matchedRows(ctx, scope, type, this.where));
|
|
11118
11667
|
}
|
|
11119
11668
|
/** Expand joins, filter by WHERE, apply SET to each matched target row, then project RETURNING. */
|
|
11120
11669
|
async execute(ctx) {
|
|
@@ -11381,7 +11930,8 @@ var DeleteQuery = class _DeleteQuery extends Query {
|
|
|
11381
11930
|
return [this.from];
|
|
11382
11931
|
}
|
|
11383
11932
|
/** Estimate `{ rows, bytes }`: the target scan × join fan-out, reduced by WHERE. */
|
|
11384
|
-
cost(
|
|
11933
|
+
cost(ctx, scope) {
|
|
11934
|
+
const engine = ctx.engine;
|
|
11385
11935
|
const type = engine.type(this.from);
|
|
11386
11936
|
if (!type) return { rows: 0, bytes: 0 };
|
|
11387
11937
|
const { aliasTypes } = this.bind(engine, scope);
|
|
@@ -11395,7 +11945,13 @@ var DeleteQuery = class _DeleteQuery extends Query {
|
|
|
11395
11945
|
const baseScan = scanCost(type);
|
|
11396
11946
|
baseScan.rows = rows;
|
|
11397
11947
|
baseScan.bytes = rows * perRowBytes;
|
|
11398
|
-
return applyWhere(baseScan, type, this.where, perRowBytes);
|
|
11948
|
+
return applyWhere(ctx, scope, baseScan, type, this.where, perRowBytes);
|
|
11949
|
+
}
|
|
11950
|
+
/** Rows this DELETE removes: the target type's rows matching WHERE (index / selectivity / OR-aware). */
|
|
11951
|
+
affected(ctx, scope) {
|
|
11952
|
+
const type = ctx.engine.type(this.from);
|
|
11953
|
+
if (!type) return AFFECTED_NONE;
|
|
11954
|
+
return affectedOne(this.from, matchedRows(ctx, scope, type, this.where));
|
|
11399
11955
|
}
|
|
11400
11956
|
/** Expand joins, filter by WHERE, project RETURNING (pre-removal), then delete the matched rows. */
|
|
11401
11957
|
async execute(ctx) {
|
|
@@ -11420,7 +11976,7 @@ var DeleteQuery = class _DeleteQuery extends Query {
|
|
|
11420
11976
|
}
|
|
11421
11977
|
const defaults = this.activeDefaults(engine, aliasTypes);
|
|
11422
11978
|
const targets = [];
|
|
11423
|
-
const
|
|
11979
|
+
const matchedRows2 = [];
|
|
11424
11980
|
const seen = /* @__PURE__ */ new Set();
|
|
11425
11981
|
for (const row of rows) {
|
|
11426
11982
|
if (defaults.length && !await rowPassesDefaultConditions(defaults, row, ctx)) continue;
|
|
@@ -11429,9 +11985,9 @@ var DeleteQuery = class _DeleteQuery extends Query {
|
|
|
11429
11985
|
if (!target || seen.has(target)) continue;
|
|
11430
11986
|
seen.add(target);
|
|
11431
11987
|
targets.push(target);
|
|
11432
|
-
|
|
11988
|
+
matchedRows2.push(row);
|
|
11433
11989
|
}
|
|
11434
|
-
const outRows = await this.projectReturning(ctx,
|
|
11990
|
+
const outRows = await this.projectReturning(ctx, matchedRows2);
|
|
11435
11991
|
for (const target of targets) deleteRecord(state, target);
|
|
11436
11992
|
return makeResult("delete", outRows, fields, targets.length);
|
|
11437
11993
|
}
|
|
@@ -11657,32 +12213,49 @@ var SetOperationQuery = class _SetOperationQuery extends Query {
|
|
|
11657
12213
|
if (this.limit !== void 0 && typeof this.limit !== "number") params.observe(this.limit.name, numeric3, ["limit"]);
|
|
11658
12214
|
if (this.offset !== void 0 && typeof this.offset !== "number") params.observe(this.offset.name, numeric3, ["offset"]);
|
|
11659
12215
|
}
|
|
11660
|
-
/** Estimate `{ rows, bytes }`: combine both arms per operation, then cap by
|
|
11661
|
-
cost(
|
|
11662
|
-
|
|
11663
|
-
|
|
11664
|
-
|
|
12216
|
+
/** Estimate the WORK `{ rows, bytes }`: combine both arms' cost per operation, then cap by LIMIT. */
|
|
12217
|
+
cost(ctx, scope) {
|
|
12218
|
+
return this.capByLimit(this.combineBranches(this.left.cost(ctx, scope), this.right.cost(ctx, scope)), ctx);
|
|
12219
|
+
}
|
|
12220
|
+
/** Estimate the RESULT SIZE: combine both arms' `outputCost` per operation, then cap by LIMIT. */
|
|
12221
|
+
outputCost(ctx, scope) {
|
|
12222
|
+
return this.capByLimit(this.combineBranches(this.left.outputCost(ctx, scope), this.right.outputCost(ctx, scope)), ctx);
|
|
12223
|
+
}
|
|
12224
|
+
/** Reads = the union of BOTH arms' references. */
|
|
12225
|
+
references(engine, scope, ctx) {
|
|
12226
|
+
return mergeReferences([this.left.references(engine, scope, ctx), this.right.references(engine, scope, ctx)]);
|
|
12227
|
+
}
|
|
12228
|
+
/** Combine the two arms' costs per the set operation (UNION sums, INTERSECT mins, EXCEPT keeps left). */
|
|
12229
|
+
combineBranches(l, r) {
|
|
11665
12230
|
switch (this.kind) {
|
|
11666
12231
|
case "union":
|
|
11667
|
-
|
|
11668
|
-
break;
|
|
12232
|
+
return addCost(l, r);
|
|
11669
12233
|
case "intersect":
|
|
11670
|
-
|
|
11671
|
-
break;
|
|
12234
|
+
return { rows: Math.min(l.rows, r.rows), bytes: Math.min(l.bytes, r.bytes) };
|
|
11672
12235
|
case "except":
|
|
11673
|
-
|
|
11674
|
-
break;
|
|
12236
|
+
return l;
|
|
11675
12237
|
/* v8 ignore next 2 -- exhaustive over SetKind; unreachable */
|
|
11676
12238
|
default:
|
|
11677
12239
|
return assertNever6(this.kind);
|
|
11678
12240
|
}
|
|
11679
|
-
|
|
12241
|
+
}
|
|
12242
|
+
/** Cap a combined cost by the set-level LIMIT (a literal or a `ctx.params`-resolved value). */
|
|
12243
|
+
capByLimit(combined, ctx) {
|
|
12244
|
+
const limit = this.boundValue(this.limit, ctx);
|
|
12245
|
+
if (limit !== void 0 && combined.rows > 0) {
|
|
11680
12246
|
const perRow = combined.bytes / combined.rows;
|
|
11681
|
-
const rows = Math.min(combined.rows,
|
|
11682
|
-
|
|
12247
|
+
const rows = Math.min(combined.rows, limit);
|
|
12248
|
+
return { rows, bytes: rows * perRow };
|
|
11683
12249
|
}
|
|
11684
12250
|
return combined;
|
|
11685
12251
|
}
|
|
12252
|
+
/** Resolve a LIMIT bound to a number: a literal, else a `ctx.params` value, else undefined. */
|
|
12253
|
+
boundValue(v, ctx) {
|
|
12254
|
+
if (v === void 0) return void 0;
|
|
12255
|
+
if (typeof v === "number") return v;
|
|
12256
|
+
const raw2 = ctx.params?.[v.name];
|
|
12257
|
+
return typeof raw2 === "number" ? raw2 : void 0;
|
|
12258
|
+
}
|
|
11686
12259
|
/** Run both arms, combine per the set operation, de-dup unless `all`, then apply set-level ORDER BY / OFFSET / LIMIT. */
|
|
11687
12260
|
async execute(ctx) {
|
|
11688
12261
|
const leftRes = await ctx.withNonRoot(() => this.left.execute(ctx));
|
|
@@ -11818,6 +12391,12 @@ var CTEEntryImpl = class _CTEEntryImpl {
|
|
|
11818
12391
|
collectReferenced(out, cteNames) {
|
|
11819
12392
|
for (const t of this.query.referencedTypes()) if (!cteNames.has(t)) out.add(t);
|
|
11820
12393
|
}
|
|
12394
|
+
affected(ctx, scope) {
|
|
12395
|
+
return this.query.affected(ctx, scope);
|
|
12396
|
+
}
|
|
12397
|
+
references(engine, scope, ctx) {
|
|
12398
|
+
return this.query.references(engine, scope, ctx);
|
|
12399
|
+
}
|
|
11821
12400
|
async execute(ctx) {
|
|
11822
12401
|
const res = await ctx.withNonRoot(() => this.query.execute(ctx));
|
|
11823
12402
|
ctx.ctes.set(this.name, [...res.rows]);
|
|
@@ -11853,6 +12432,12 @@ var CTERecursiveEntryImpl = class _CTERecursiveEntryImpl {
|
|
|
11853
12432
|
for (const t of this.base.referencedTypes()) if (!cteNames.has(t)) out.add(t);
|
|
11854
12433
|
for (const t of this.recursiveArm.referencedTypes()) if (!cteNames.has(t)) out.add(t);
|
|
11855
12434
|
}
|
|
12435
|
+
affected(ctx, scope) {
|
|
12436
|
+
return mergeAffected([this.base.affected(ctx, scope), this.recursiveArm.affected(ctx, scope)]);
|
|
12437
|
+
}
|
|
12438
|
+
references(engine, scope, ctx) {
|
|
12439
|
+
return mergeReferences([this.base.references(engine, scope, ctx), this.recursiveArm.references(engine, scope, ctx)]);
|
|
12440
|
+
}
|
|
11856
12441
|
async execute(ctx) {
|
|
11857
12442
|
const baseRes = await ctx.withNonRoot(() => this.base.execute(ctx));
|
|
11858
12443
|
let all = [...baseRes.rows];
|
|
@@ -12069,8 +12654,22 @@ var CTEStatementQuery = class _CTEStatementQuery extends Query {
|
|
|
12069
12654
|
return [...out];
|
|
12070
12655
|
}
|
|
12071
12656
|
/** Estimate `{ rows, bytes }` — the final query's cost, with CTE names bound. */
|
|
12072
|
-
cost(
|
|
12073
|
-
return this.final.cost(
|
|
12657
|
+
cost(ctx, scope) {
|
|
12658
|
+
return this.final.cost(ctx, this.bind(ctx.engine, scope));
|
|
12659
|
+
}
|
|
12660
|
+
/** The RESULT SIZE is the final query's output cost, with CTE names bound. */
|
|
12661
|
+
outputCost(ctx, scope) {
|
|
12662
|
+
return this.final.outputCost(ctx, this.bind(ctx.engine, scope));
|
|
12663
|
+
}
|
|
12664
|
+
/** Rows mutated: every data-modifying CTE entry plus the final query, summed per Type. */
|
|
12665
|
+
affected(ctx, scope) {
|
|
12666
|
+
const bound = this.bind(ctx.engine, scope);
|
|
12667
|
+
return mergeAffected([this.final.affected(ctx, bound), ...this.ctes.map((e2) => e2.affected(ctx, bound))]);
|
|
12668
|
+
}
|
|
12669
|
+
/** Reads = the final query's plus every entry's references (Types / fields / functions). */
|
|
12670
|
+
references(engine, scope, ctx) {
|
|
12671
|
+
const bound = this.bind(engine, scope);
|
|
12672
|
+
return mergeReferences([this.final.references(engine, bound, ctx), ...this.ctes.map((e2) => e2.references(engine, bound, ctx))]);
|
|
12074
12673
|
}
|
|
12075
12674
|
/** Evaluate each CTE in order (populating `ctx.ctes`), then run the final query. */
|
|
12076
12675
|
async execute(ctx) {
|
|
@@ -12161,9 +12760,13 @@ var ExprQuery = class _ExprQuery extends Query {
|
|
|
12161
12760
|
referencedTypes() {
|
|
12162
12761
|
return [];
|
|
12163
12762
|
}
|
|
12763
|
+
/** Walk the single output expression (so `references` sees its functions). */
|
|
12764
|
+
walkExprs(visit) {
|
|
12765
|
+
this.expr.walk(visit);
|
|
12766
|
+
}
|
|
12164
12767
|
/** Estimate `{ rows, bytes }` — exactly one row sized by the expression's resolved type. */
|
|
12165
|
-
cost(
|
|
12166
|
-
return { rows: 1, bytes: bytesOfResolved(this.expr.resolve(engine, scope)) };
|
|
12768
|
+
cost(ctx, scope) {
|
|
12769
|
+
return { rows: 1, bytes: bytesOfResolved(this.expr.resolve(ctx.engine, scope)) };
|
|
12167
12770
|
}
|
|
12168
12771
|
/** Evaluate the expression into a single `{ value }` output row. */
|
|
12169
12772
|
async execute(ctx) {
|
|
@@ -12962,6 +13565,10 @@ function scalar2(name, instructions, params, output2, run, sql, rawArgs, example
|
|
|
12962
13565
|
run: { shape: "scalar", run }
|
|
12963
13566
|
};
|
|
12964
13567
|
}
|
|
13568
|
+
var ONE_DAY_MS = 864e5;
|
|
13569
|
+
function withChanges(builtin, changes) {
|
|
13570
|
+
return { ...builtin, def: { ...builtin.def, changes } };
|
|
13571
|
+
}
|
|
12965
13572
|
var SCALARS = [
|
|
12966
13573
|
scalar2(
|
|
12967
13574
|
"concat",
|
|
@@ -13233,7 +13840,7 @@ var SCALARS = [
|
|
|
13233
13840
|
scalar2("pi", "The constant \u03C0.", [], NUMBER, () => Value.of(Math.PI)),
|
|
13234
13841
|
scalar2("degrees", "Convert radians to degrees.", [{ name: "value", type: NUMBER }], NUMBER, (a) => numeric(arg(a, "value"), (n) => n * 180 / Math.PI)),
|
|
13235
13842
|
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())),
|
|
13843
|
+
withChanges(scalar2("random", "Random number in [0, 1).", [], NUMBER, () => Value.of(Math.random())), 0),
|
|
13237
13844
|
scalar2("sin", "Sine (radians).", [{ name: "value", type: NUMBER }], NUMBER, (a) => numeric(arg(a, "value"), Math.sin)),
|
|
13238
13845
|
scalar2("cos", "Cosine (radians).", [{ name: "value", type: NUMBER }], NUMBER, (a) => numeric(arg(a, "value"), Math.cos)),
|
|
13239
13846
|
scalar2("tan", "Tangent (radians).", [{ name: "value", type: NUMBER }], NUMBER, (a) => numeric(arg(a, "value"), Math.tan)),
|
|
@@ -13260,19 +13867,19 @@ var SCALARS = [
|
|
|
13260
13867
|
// Emitted (both dialects) as `(CASE WHEN condition THEN then ELSE else END)`.
|
|
13261
13868
|
(a) => arg(a, "condition").toBoolean() ? arg(a, "then") : arg(a, "else")
|
|
13262
13869
|
),
|
|
13263
|
-
scalar2("now", "Current timestamp.", [], { kind: "timestamp" }, () => Value.of((/* @__PURE__ */ new Date()).toISOString())),
|
|
13264
|
-
scalar2("currentDate", "Today\u2019s date.", [], { kind: "date" }, () => {
|
|
13870
|
+
withChanges(scalar2("now", "Current timestamp.", [], { kind: "timestamp" }, () => Value.of((/* @__PURE__ */ new Date()).toISOString())), 0),
|
|
13871
|
+
withChanges(scalar2("currentDate", "Today\u2019s date.", [], { kind: "date" }, () => {
|
|
13265
13872
|
const iso = (/* @__PURE__ */ new Date()).toISOString();
|
|
13266
13873
|
return Value.of(iso.split("T")[0] ?? iso);
|
|
13267
|
-
}),
|
|
13874
|
+
}), ONE_DAY_MS),
|
|
13268
13875
|
// ─── Group 2a: date / time ─────────────────────────────────────────────────
|
|
13269
13876
|
// Temporal inputs are typed `any` (an ISO date/timestamp string OR a temporal
|
|
13270
13877
|
// field), so a `date` value is accepted wherever a `timestamp` is. The FIELD
|
|
13271
13878
|
// arg of the four selectors is a `rawArgs` inline literal (emitted as an
|
|
13272
13879
|
// `EXTRACT`/`date_part` field, never a bind param). `currentTime`/…, the
|
|
13273
13880
|
// `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())),
|
|
13881
|
+
withChanges(scalar2("currentTime", "Current time of day (HH:MM:SS).", [], TEXT, () => Value.of((/* @__PURE__ */ new Date()).toISOString().slice(11, 19))), 0),
|
|
13882
|
+
withChanges(scalar2("currentTimestamp", "Current timestamp.", [], TIMESTAMP, () => Value.of((/* @__PURE__ */ new Date()).toISOString())), 0),
|
|
13276
13883
|
scalar2(
|
|
13277
13884
|
"datePart",
|
|
13278
13885
|
"Numeric component named by `field` (year/month/day/dow/\u2026) of `d`.",
|
|
@@ -13847,6 +14454,22 @@ var Registry = class {
|
|
|
13847
14454
|
fieldTypeClassList() {
|
|
13848
14455
|
return Array.from(this.fieldTypeClasses.values());
|
|
13849
14456
|
}
|
|
14457
|
+
/** Registry-level default average bytes per field-type kind (a `Field` with no explicit `bytes` falls back here). */
|
|
14458
|
+
defaultFieldTypeBytes = /* @__PURE__ */ new Map();
|
|
14459
|
+
/**
|
|
14460
|
+
* Configure the default average stored bytes for a field-type KIND — the
|
|
14461
|
+
* fallback a `Field` of that kind uses when it declares no explicit `bytes`
|
|
14462
|
+
* (before the field type's own {@link FieldType.avgBytes}). Lets a deployment
|
|
14463
|
+
* tune byte-cost estimates centrally (e.g. "our `text` averages 128 bytes").
|
|
14464
|
+
*/
|
|
14465
|
+
setDefaultFieldBytes(kind, bytes) {
|
|
14466
|
+
this.defaultFieldTypeBytes.set(kind, bytes);
|
|
14467
|
+
return this;
|
|
14468
|
+
}
|
|
14469
|
+
/** The configured default bytes for a field-type kind, or `undefined` when unset. */
|
|
14470
|
+
defaultFieldBytes(kind) {
|
|
14471
|
+
return this.defaultFieldTypeBytes.get(kind);
|
|
14472
|
+
}
|
|
13850
14473
|
/** Parse a `FieldTypeDef` into a `FieldType` instance by dispatching on kind. */
|
|
13851
14474
|
parseFieldType(json) {
|
|
13852
14475
|
const cls = this.fieldTypeClasses.get(json.kind);
|
|
@@ -14647,6 +15270,16 @@ var QueryFunction = class _QueryFunction {
|
|
|
14647
15270
|
*/
|
|
14648
15271
|
unaggregate;
|
|
14649
15272
|
unaggregateEmpty;
|
|
15273
|
+
/** Intrinsic per-call cost this function adds beyond its args (default none). */
|
|
15274
|
+
cost;
|
|
15275
|
+
/**
|
|
15276
|
+
* Milliseconds between changes to this function's RESULT independent of the
|
|
15277
|
+
* data (`0` = always — `now()`; `-1` = pure/never — the default; `86400000` =
|
|
15278
|
+
* daily — `currentDate()`). Folded into `engine.changeInterval`.
|
|
15279
|
+
*/
|
|
15280
|
+
changes;
|
|
15281
|
+
/** Type names this function internally READS (a UDF over a table); folded into cost / references. */
|
|
15282
|
+
references;
|
|
14650
15283
|
/** Construct from already-parsed parts; use `from` to build from JSON. */
|
|
14651
15284
|
constructor(spec) {
|
|
14652
15285
|
this.name = spec.name;
|
|
@@ -14659,6 +15292,9 @@ var QueryFunction = class _QueryFunction {
|
|
|
14659
15292
|
this.examples = spec.examples;
|
|
14660
15293
|
this.unaggregate = spec.unaggregate;
|
|
14661
15294
|
this.unaggregateEmpty = spec.unaggregateEmpty;
|
|
15295
|
+
this.cost = spec.cost ?? ZERO_COST;
|
|
15296
|
+
this.changes = spec.changes ?? NEVER_CHANGES;
|
|
15297
|
+
this.references = spec.references ?? [];
|
|
14662
15298
|
}
|
|
14663
15299
|
/** Build a runtime function from its JSON, parsing field/Type references. */
|
|
14664
15300
|
static from(json, registry) {
|
|
@@ -14692,7 +15328,10 @@ var QueryFunction = class _QueryFunction {
|
|
|
14692
15328
|
instructions: json.instructions,
|
|
14693
15329
|
examples: json.examples,
|
|
14694
15330
|
unaggregate: json.unaggregate,
|
|
14695
|
-
unaggregateEmpty: json.unaggregateEmpty
|
|
15331
|
+
unaggregateEmpty: json.unaggregateEmpty,
|
|
15332
|
+
cost: json.cost,
|
|
15333
|
+
changes: json.changes,
|
|
15334
|
+
references: json.references
|
|
14696
15335
|
});
|
|
14697
15336
|
}
|
|
14698
15337
|
/**
|
|
@@ -14720,7 +15359,11 @@ var QueryFunction = class _QueryFunction {
|
|
|
14720
15359
|
...this.instructions ? { instructions: this.instructions } : {},
|
|
14721
15360
|
...this.examples ? { examples: this.examples } : {},
|
|
14722
15361
|
...this.unaggregate ? { unaggregate: this.unaggregate } : {},
|
|
14723
|
-
...this.unaggregateEmpty ? { unaggregateEmpty: this.unaggregateEmpty } : {}
|
|
15362
|
+
...this.unaggregateEmpty ? { unaggregateEmpty: this.unaggregateEmpty } : {},
|
|
15363
|
+
// Estimation metadata — emitted only when set away from the neutral default.
|
|
15364
|
+
...this.cost.rows !== 0 || this.cost.bytes !== 0 ? { cost: this.cost } : {},
|
|
15365
|
+
...this.changes !== NEVER_CHANGES ? { changes: this.changes } : {},
|
|
15366
|
+
...this.references.length > 0 ? { references: [...this.references] } : {}
|
|
14724
15367
|
};
|
|
14725
15368
|
}
|
|
14726
15369
|
/**
|
|
@@ -15038,7 +15681,7 @@ var QueryEngine = class {
|
|
|
15038
15681
|
* supplied, the estimated `cost` is checked too and `cost.rows-exceeded` /
|
|
15039
15682
|
* `cost.bytes-exceeded` problems are appended (opt-in).
|
|
15040
15683
|
*/
|
|
15041
|
-
validateQuery(query, scope, constraints) {
|
|
15684
|
+
validateQuery(query, scope, constraints, options) {
|
|
15042
15685
|
const q = this.toQuery(query);
|
|
15043
15686
|
const s = scope ?? this.globalScope();
|
|
15044
15687
|
const p = new Problems();
|
|
@@ -15048,12 +15691,78 @@ var QueryEngine = class {
|
|
|
15048
15691
|
const ex = this.executor(name);
|
|
15049
15692
|
ex?.validate?.(q, p);
|
|
15050
15693
|
}
|
|
15051
|
-
if (constraints) reportCostProblems(q.cost(this, s), constraints, p);
|
|
15694
|
+
if (constraints) reportCostProblems(q.cost(this.costContext(options), s), constraints, p);
|
|
15052
15695
|
return p;
|
|
15053
15696
|
}
|
|
15054
|
-
/**
|
|
15055
|
-
|
|
15056
|
-
|
|
15697
|
+
/**
|
|
15698
|
+
* Estimate a query's `{ rows, bytes }` cost against a scope (root if omitted).
|
|
15699
|
+
* `options` may supply the execution-time `filters` / `sort` the query is
|
|
15700
|
+
* costed WITH, so a `filters` / `sorter` placeholder weaves the real supplied
|
|
15701
|
+
* predicate / sort into the estimate (a subquery in a filter then raises the
|
|
15702
|
+
* cost, as it should).
|
|
15703
|
+
*/
|
|
15704
|
+
cost(query, scope, options) {
|
|
15705
|
+
return this.toQuery(query).cost(this.costContext(options), scope ?? this.globalScope());
|
|
15706
|
+
}
|
|
15707
|
+
/**
|
|
15708
|
+
* Estimate the SIZE OF THE RESULT a query hands back — `{ rows, bytes }` where
|
|
15709
|
+
* `rows` is the delivered row count (post-WHERE / GROUP / DISTINCT, capped by a
|
|
15710
|
+
* literal or `options.params`-resolved LIMIT / OFFSET) and `bytes` sizes those
|
|
15711
|
+
* rows by the PROJECTION width (the selected columns), not the whole scanned
|
|
15712
|
+
* row. Contrast {@link cost}, which estimates the WORK to produce the result.
|
|
15713
|
+
*/
|
|
15714
|
+
outputCost(query, scope, options) {
|
|
15715
|
+
return this.toQuery(query).outputCost(this.costContext(options), scope ?? this.globalScope());
|
|
15716
|
+
}
|
|
15717
|
+
/**
|
|
15718
|
+
* Estimate the rows a statement MUTATES — a total plus a per-Type breakdown
|
|
15719
|
+
* ({@link Affected}). An UPDATE / DELETE uses the target Type's indexes +
|
|
15720
|
+
* selectivity (OR-aware) to count the rows its WHERE matches; an INSERT counts
|
|
15721
|
+
* its VALUES / source rows; a CTE SUMS every data-modifying entry plus its
|
|
15722
|
+
* final query per Type. Read-only queries report `{ rows: 0, types: [] }`.
|
|
15723
|
+
* `options.params` resolves a param-bound LIMIT where used.
|
|
15724
|
+
*/
|
|
15725
|
+
affected(query, scope, options) {
|
|
15726
|
+
return this.toQuery(query).affected(this.costContext(options), scope ?? this.globalScope());
|
|
15727
|
+
}
|
|
15728
|
+
/**
|
|
15729
|
+
* Estimate how long (ms) until the DATA behind a query could change — a
|
|
15730
|
+
* freshness / cache-TTL signal. Uses {@link Query.references} (so it counts
|
|
15731
|
+
* ONLY the Types / fields the query actually reads, plus execution-time
|
|
15732
|
+
* `filters` / selected `sort` exprs and invoked functions) and folds their
|
|
15733
|
+
* `changes` rates: `0` (always changing) dominates, a negative (never) is
|
|
15734
|
+
* ignored, else the FASTEST positive interval wins. Each read Type contributes
|
|
15735
|
+
* its row-level rate; a read field with its OWN rate refines it; a called
|
|
15736
|
+
* function (e.g. `currentDate()`) contributes its volatility. A query over only
|
|
15737
|
+
* immutable data / pure literals returns `-1`.
|
|
15738
|
+
*/
|
|
15739
|
+
/**
|
|
15740
|
+
* Enumerate what a query READS — its {@link QueryReferences} of Types, specific
|
|
15741
|
+
* fields, and DB functions — including execution-time `filters` predicates and
|
|
15742
|
+
* the `sort`-selected sorter exprs (from `options`). Powers `changeInterval`
|
|
15743
|
+
* and lets a caller inspect the exact surface a query touches.
|
|
15744
|
+
*/
|
|
15745
|
+
references(query, scope, options) {
|
|
15746
|
+
this.registry.finalize();
|
|
15747
|
+
return this.toQuery(query).references(this, scope ?? this.globalScope(), this.costContext(options));
|
|
15748
|
+
}
|
|
15749
|
+
changeInterval(query, scope, options) {
|
|
15750
|
+
this.registry.finalize();
|
|
15751
|
+
const refs = this.toQuery(query).references(this, scope ?? this.globalScope(), this.costContext(options));
|
|
15752
|
+
let acc = NEVER_CHANGES;
|
|
15753
|
+
for (const name of refs.types) {
|
|
15754
|
+
const type = this.type(name);
|
|
15755
|
+
if (type) acc = foldChanges(acc, type.changes);
|
|
15756
|
+
}
|
|
15757
|
+
for (const ref3 of refs.fields) {
|
|
15758
|
+
const changes = this.type(ref3.type)?.field(ref3.field)?.changes();
|
|
15759
|
+
if (changes !== void 0) acc = foldChanges(acc, changes);
|
|
15760
|
+
}
|
|
15761
|
+
for (const name of refs.functions) {
|
|
15762
|
+
const fn2 = this.lookupFunction(name);
|
|
15763
|
+
if (fn2) acc = foldChanges(acc, fn2.changes);
|
|
15764
|
+
}
|
|
15765
|
+
return acc;
|
|
15057
15766
|
}
|
|
15058
15767
|
/**
|
|
15059
15768
|
* Check a query's estimated cost against `constraints`, returning any
|
|
@@ -15061,11 +15770,23 @@ var QueryEngine = class {
|
|
|
15061
15770
|
* A standalone entry point so callers can cost-bound a query without a full
|
|
15062
15771
|
* structural re-validation.
|
|
15063
15772
|
*/
|
|
15064
|
-
checkCost(query, constraints, scope) {
|
|
15773
|
+
checkCost(query, constraints, scope, options) {
|
|
15065
15774
|
const p = new Problems();
|
|
15066
|
-
reportCostProblems(this.cost(query, scope), constraints, p);
|
|
15775
|
+
reportCostProblems(this.cost(query, scope, options), constraints, p);
|
|
15067
15776
|
return p;
|
|
15068
15777
|
}
|
|
15778
|
+
/**
|
|
15779
|
+
* Build the {@link CostContext} for a cost walk from optional execution-time
|
|
15780
|
+
* selections: the `filters` map is parsed once (source → bound `Expr`) exactly
|
|
15781
|
+
* as `run` / `toSQL` do; `sort` is the dynamic-sort selection. With neither, a
|
|
15782
|
+
* bare `{ engine }` context is returned (placeholders stay neutral).
|
|
15783
|
+
*/
|
|
15784
|
+
costContext(options) {
|
|
15785
|
+
if (!options?.filters && !options?.sort && !options?.params) return { engine: this };
|
|
15786
|
+
const parsed = options.filters ? this.parseFilters(options.filters) : void 0;
|
|
15787
|
+
const filters2 = parsed ? new Map(Object.entries(parsed)) : void 0;
|
|
15788
|
+
return { engine: this, filters: filters2, sort: options.sort, params: options.params };
|
|
15789
|
+
}
|
|
15069
15790
|
async run(query, options, opts) {
|
|
15070
15791
|
const q = this.toQuery(query);
|
|
15071
15792
|
const ctx = new RuntimeContext(this, options);
|