@aeye/query 0.6.1 → 0.6.2
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/README.md +17 -0
- package/aeye-query.md +3 -2
- package/dist/index.d.ts +41 -2
- package/dist/index.js +40 -18
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -337,6 +337,16 @@ const result = await engine.run(query, { params, filters, includeTotal });
|
|
|
337
337
|
// result.total — pre-limit row count, when run with `includeTotal: true`
|
|
338
338
|
```
|
|
339
339
|
|
|
340
|
+
Each field's `type` is the full `ResolvedType`. A **computed** one carries
|
|
341
|
+
`aggregate` (does a group collapse happen anywhere in this expression?) and
|
|
342
|
+
`aggregateFn` — the APPLIED aggregate's name, present exactly when the value IS
|
|
343
|
+
one aggregate call. `sum(hours) as total_hours` reports `aggregateFn: 'sum'`
|
|
344
|
+
under any alias; `max(a) - min(b)` reports `aggregate: true` with NO
|
|
345
|
+
`aggregateFn` (it contains aggregates but is none); a window over an
|
|
346
|
+
aggregate-shaped function reports neither. Read it rather than inferring the
|
|
347
|
+
function from the output column NAME, which cannot see through an alias and
|
|
348
|
+
mistakes `hours * 2 as count` for an aggregate.
|
|
349
|
+
|
|
340
350
|
Everything composes around that one call:
|
|
341
351
|
|
|
342
352
|
- **Params.** A `param` (`{ kind: 'param', name }`) infers its type from how it
|
|
@@ -850,6 +860,13 @@ identifier; suffixed `_2`, `_3`, … on collision with a param the query already
|
|
|
850
860
|
uses). Failure cases (`drill.no-aggregation` / `non-invertible` /
|
|
851
861
|
`having-aggregate` / `window-unsupported`) return LLM-friendly `Problems`.
|
|
852
862
|
|
|
863
|
+
Each aggregate is replaced by its underlying row-level expression, and `count(*)`
|
|
864
|
+
— which has no single value — expands to the FROM type's fields MINUS the ones
|
|
865
|
+
the SELECT already projects itself. So `SELECT status, count(*) … GROUP BY status`
|
|
866
|
+
drills to `status` plus the remaining columns, with the group key projected ONCE.
|
|
867
|
+
The skip is keyed on the EXPRESSION (its canonical form), never on the output
|
|
868
|
+
name: two different expressions may legitimately share a name.
|
|
869
|
+
|
|
853
870
|
## Cost & estimation
|
|
854
871
|
|
|
855
872
|
Bottom-up estimates driven by each Type's cardinality (`count` rows, `bytes`
|
package/aeye-query.md
CHANGED
|
@@ -106,7 +106,7 @@ Types and fields declare **what write operations are possible**, and the model f
|
|
|
106
106
|
- **Field flags** — `insertable` / `updatable` on a `FieldDef` (default **true**). A field whose `FieldBacking.compute` is set defaults to `insertable:false, updatable:false` (override with an explicit flag). Validation rejects a listed non-insertable field (`insert.field-readonly`) / an assigned non-updatable field (`update.field-readonly`); the paired schema offers only insertable `fields` / updatable `set` fields.
|
|
107
107
|
- **Insert-requiredness (THE rule)** — a field is REQUIRED on insert iff it is **insertable AND non-nullable AND has no default AND is not computed**; otherwise optional (nullable / has-default) or excluded (non-insertable). One shared helper (`requiredOnInsert`) drives both the schema (required-vs-optional in paired mode) and validation (`insert.missing-required`, which lists the missing names).
|
|
108
108
|
- **Defaults** — `FieldBacking.default` is a `Value` or a factory `() => Value | Promise<Value>`. Its **presence alone** makes the field optional-on-insert (there is no `hasDefault` flag). At **runtime** an omitted defaulted field is materialized (the value is evaluated / the factory awaited, per row) into the inserted record. In **SQL** the column is simply left out of the INSERT and the database's own column `DEFAULT` fills it — so a JS-factory default is a runtime-only concern.
|
|
109
|
-
- **A write CELL carries a JSON value or an expression** — `WriteValueDef = JsonValue | ExprDef`. A raw SCALAR or a whole DOCUMENT (object / array, for a `json` / `array` column) becomes a literal; a `{ kind }` object is read as an EXPRESSION only when the kind names a REGISTERED expr kind, so a settings blob carrying a `kind` key stays data. An absent key OR a JSON `null` OMITS the field (its default fills in / it stays unset); `{ kind:"literal", value:null }` is the only way to set SQL NULL. A
|
|
109
|
+
- **A write CELL carries a JSON value or an expression** — `WriteValueDef = JsonValue | ExprDef`. A raw SCALAR or a whole DOCUMENT (object / array, for a `json` / `array` column) becomes a literal; a `{ kind }` object is read as an EXPRESSION only when the kind names a REGISTERED expr kind, so a settings blob carrying a `kind` key stays data. An absent key OR a JSON `null` OMITS the field (its default fills in / it stays unset); `{ kind:"literal", value:null }` is the only way to set SQL NULL. A value written to a `json` / `array` column is JSON-ENCODED and bound as ONE parameter cast to the COLUMN's type (`Dialect.jsonValue`) — Postgres `CAST($1 AS jsonb)`, or `ARRAY[$1,$2]::text[]` for a native array column, which cannot take JSON text. The COLUMN decides, not the value's shape, so a JSON *scalar* into a `json` column (`"a bare string"`, `42`) is encoded and cast like any document rather than bound raw. SQL NULL is the exception: a null literal and an unbound param bind NULL, never the JSON value `null`. A param bound to a document is bound, never silently NULL.
|
|
110
110
|
- **A write value is checked against its COLUMN** — the cell's expr is walked in the target's scope, a `param` cell is OBSERVED against the column's field type (which is the only place a write param's type can come from), and a value of an incompatible category is refused (`write.type`). A RELATION column is exempt: what you write to it is the target's identity, not a value of the relation's own category.
|
|
111
111
|
- **Expr restrictions** — `FieldDef.exprs` is `{ not: ExprKind[] }` (exclude these kinds) or `{ only: ExprKind[] }` (allow exactly these). It can only NARROW what the field TYPE already permits. `field.allowsExpr(kind)` respects both the type floor and the restriction. Validation rejects a denied kind at the field's use site (`field.expr-denied`) — checked on a standalone `field-ref` (gated as `field-ref`), on each gating operator's DIRECT field-ref operand (gated as `comparison` / `between` / `in` / `is-null` / `array-op`), and on the field-naming exprs (`text-search` / `text-score` / `semantic` / `filters`). The paired schema omits an excluded field from the relevant enum and gates a kind away entirely when every candidate field excludes it.
|
|
112
112
|
|
|
@@ -189,9 +189,10 @@ const result = await engine.run(query, { params, filters, includeTotal });
|
|
|
189
189
|
// result.total — pre-limit count, when run with includeTotal: true
|
|
190
190
|
```
|
|
191
191
|
|
|
192
|
+
- **An output field's `type`** is the full `ResolvedType`. A COMPUTED one carries `aggregate` (does a group collapse happen anywhere in this expression?) and `aggregateFn` — the APPLIED aggregate's name, present exactly when the value IS one aggregate call. `sum(hours) as total_hours` reports `aggregateFn: 'sum'` under any alias; `max(a) - min(b)` reports `aggregate: true` with NO `aggregateFn` (it contains aggregates but is none); a window over an aggregate-shaped function reports neither. Read it rather than inferring the function from the output column NAME, which cannot see through an alias and mistakes `hours * 2 as count` for an aggregate.
|
|
192
193
|
- **`includeTotal`** is an execution-time option (not a `SelectDef` field): `run` captures the pre-limit count; `toSQL(query, dialect, { includeTotal: true })` emits `COUNT(*) OVER () AS "$total"`.
|
|
193
194
|
- **`autoPaginate(query)`** adds `limit`/`offset` as bind params idempotently, so paging is just supplying values: `run(paged, { params: { limit, offset } })`.
|
|
194
|
-
- **Drill-down.** `drillDown(query, engine)` rebuilds the underlying-rows query behind an aggregate, parameterized (each GROUP BY key pinned to a bind param) — returns `{ query, params, warnings }`. `drillDownInto(query, groupRow, engine)` extracts one aggregated row's key values; then it is the same `run` call. Failures return LLM-friendly `Problems` (`drill.no-aggregation` / `non-invertible` / `having-aggregate` / `window-unsupported`).
|
|
195
|
+
- **Drill-down.** `drillDown(query, engine)` rebuilds the underlying-rows query behind an aggregate, parameterized (each GROUP BY key pinned to a bind param) — returns `{ query, params, warnings }`. `drillDownInto(query, groupRow, engine)` extracts one aggregated row's key values; then it is the same `run` call. Each aggregate becomes its row-level expression; `count(*)` expands to the FROM type's fields MINUS the ones the SELECT already projects (matched on the EXPRESSION, not the output name), so a group key is projected once. Failures return LLM-friendly `Problems` (`drill.no-aggregation` / `non-invertible` / `having-aggregate` / `window-unsupported`).
|
|
195
196
|
- **Standalone exprs.** `engine.evaluateExpr(expr, row?)` evaluates an `Expr`/`ExprDef` against a row; `engine.exprToSQL(expr, dialect)` emits `{ sql, params }` (params never interpolated).
|
|
196
197
|
|
|
197
198
|
### SQL conversion
|
package/dist/index.d.ts
CHANGED
|
@@ -1447,6 +1447,34 @@ interface ComputedResolved {
|
|
|
1447
1447
|
nullable: boolean;
|
|
1448
1448
|
/** Whether this computation is (or contains) an aggregate. */
|
|
1449
1449
|
aggregate: boolean;
|
|
1450
|
+
/**
|
|
1451
|
+
* The APPLIED aggregate function's name (`'sum'`, `'count'`, …) — present
|
|
1452
|
+
* exactly when this value IS one aggregate call, absent when it merely
|
|
1453
|
+
* CONTAINS one (`max(a) - min(b)` is `aggregate: true` with no single applied
|
|
1454
|
+
* function) and absent for every non-aggregate.
|
|
1455
|
+
*
|
|
1456
|
+
* It is a SIBLING of `aggregate` rather than a widening of it because the two
|
|
1457
|
+
* answer different questions: `aggregate` is a property of the whole SUBTREE
|
|
1458
|
+
* ("does a group collapse happen in here?", which drives placement validation
|
|
1459
|
+
* and grouping), while this is a property of ONE node. Folding them into
|
|
1460
|
+
* `false | string` would force a meaningless value for every composite.
|
|
1461
|
+
*
|
|
1462
|
+
* WHY IT EXISTS. Without it, a consumer labelling a computed column has to
|
|
1463
|
+
* recover the function from the column's OUTPUT NAME — `fieldNameOf` is
|
|
1464
|
+
* `as ?? (field-ref ? field : aggregate ? fn : col<i>)`, so an UNALIASED
|
|
1465
|
+
* aggregate's output name IS its function name — and then confirm that name
|
|
1466
|
+
* against the function catalog. That is evidence rather than fact, and it has
|
|
1467
|
+
* two dead spots: an ALIASED aggregate (`sum(hours) as total_hours`) cannot be
|
|
1468
|
+
* recovered at all, and a non-aggregate aliased onto a function name
|
|
1469
|
+
* (`hours * 2 as count`) is a false positive that only `aggregate` then
|
|
1470
|
+
* rejects. Reading this closes both.
|
|
1471
|
+
*
|
|
1472
|
+
* A WINDOW is deliberately excluded, even over an aggregate-shaped function
|
|
1473
|
+
* (`sum(x) OVER (…)`): it is per-row, collapses nothing, and already reports
|
|
1474
|
+
* `aggregate: false`. A scalar `function-call` does not set it either — this
|
|
1475
|
+
* names the aggregate that was APPLIED, not any function that was called.
|
|
1476
|
+
*/
|
|
1477
|
+
aggregateFn?: string;
|
|
1450
1478
|
}
|
|
1451
1479
|
/** The discriminated union of every expression / source resolution outcome. */
|
|
1452
1480
|
type ResolvedType = TypeResolved | FieldResolved | ComputedResolved;
|
|
@@ -3340,7 +3368,17 @@ declare class AggregateExpr extends Expr {
|
|
|
3340
3368
|
static toSchema(opts: SchemaOptions): z.ZodTypeAny;
|
|
3341
3369
|
protected aggregateHere(): boolean;
|
|
3342
3370
|
forEachChild(visit: (child: Expr) => void): void;
|
|
3343
|
-
/**
|
|
3371
|
+
/**
|
|
3372
|
+
* Resolve to the function's declared output type, marked aggregate and nullable
|
|
3373
|
+
* (except `count`), and carrying the APPLIED function's name.
|
|
3374
|
+
*
|
|
3375
|
+
* `aggregateFn` is set on BOTH roads — including the unknown-function fallback,
|
|
3376
|
+
* where the name is still the fact of what was written even though the
|
|
3377
|
+
* resolution is a placeholder. This is the ONE node that can answer "which
|
|
3378
|
+
* aggregate is this?": every wrapping expr reports `aggregate: true` from its
|
|
3379
|
+
* children without a single applied function, and `Function.resolveOutput`
|
|
3380
|
+
* never sets it, so nothing propagates a stale name upward.
|
|
3381
|
+
*/
|
|
3344
3382
|
resolve(engine: QueryEngine, scope: QueryScope): ResolvedType;
|
|
3345
3383
|
/** Validate aggregate placement (not in WHERE, not nested) and the function's own named-arg checks. */
|
|
3346
3384
|
validateWalk(engine: QueryEngine, scope: QueryScope, p: Problems, ctx: ValidateContext): ResolvedType;
|
|
@@ -9574,7 +9612,8 @@ declare function autoPaginate(select: SelectQuery | SelectDef, opts?: AutoPagina
|
|
|
9574
9612
|
* AGGREGATED query's OUTPUT field that carries that key's value per row.
|
|
9575
9613
|
* No `groupRow`, no literals.
|
|
9576
9614
|
* 3. Replace each aggregate SELECT item with its underlying non-aggregated
|
|
9577
|
-
* expr: `sum(o.total)` → `o.total`, `count(*)` →
|
|
9615
|
+
* expr: `sum(o.total)` → `o.total`, `count(*)` → every FROM field the SELECT
|
|
9616
|
+
* does not already project itself (so a group key is not duplicated). An
|
|
9578
9617
|
* aggregate over a non-field argument (a literal / param) is
|
|
9579
9618
|
* `drill.non-invertible` (names the offending alias).
|
|
9580
9619
|
* 4. Drop GROUP BY / HAVING. A HAVING clause that references group keys (no
|
package/dist/index.js
CHANGED
|
@@ -3060,8 +3060,9 @@ import { z as z15 } from "zod";
|
|
|
3060
3060
|
|
|
3061
3061
|
// src/exprs/_shared.ts
|
|
3062
3062
|
import { z as z14 } from "zod";
|
|
3063
|
-
function computed(fieldType, sources, nullable, aggregate2) {
|
|
3064
|
-
|
|
3063
|
+
function computed(fieldType, sources, nullable, aggregate2, aggregateFn) {
|
|
3064
|
+
const rt = { kind: "computed", fieldType, sources, nullable, aggregate: aggregate2 };
|
|
3065
|
+
return aggregateFn === void 0 ? rt : { ...rt, aggregateFn };
|
|
3065
3066
|
}
|
|
3066
3067
|
function boolResult(sources, nullable, aggregate2 = false) {
|
|
3067
3068
|
return computed(new BoolFieldType(), sources, nullable, aggregate2);
|
|
@@ -7132,16 +7133,26 @@ var AggregateExpr = class _AggregateExpr extends Expr {
|
|
|
7132
7133
|
forEachChild(visit) {
|
|
7133
7134
|
for (const a of this.args.values()) visit(a);
|
|
7134
7135
|
}
|
|
7135
|
-
/**
|
|
7136
|
+
/**
|
|
7137
|
+
* Resolve to the function's declared output type, marked aggregate and nullable
|
|
7138
|
+
* (except `count`), and carrying the APPLIED function's name.
|
|
7139
|
+
*
|
|
7140
|
+
* `aggregateFn` is set on BOTH roads — including the unknown-function fallback,
|
|
7141
|
+
* where the name is still the fact of what was written even though the
|
|
7142
|
+
* resolution is a placeholder. This is the ONE node that can answer "which
|
|
7143
|
+
* aggregate is this?": every wrapping expr reports `aggregate: true` from its
|
|
7144
|
+
* children without a single applied function, and `Function.resolveOutput`
|
|
7145
|
+
* never sets it, so nothing propagates a stale name upward.
|
|
7146
|
+
*/
|
|
7136
7147
|
resolve(engine, scope) {
|
|
7137
7148
|
const fn2 = engine.lookupFunction(this.fn);
|
|
7138
7149
|
if (!fn2) {
|
|
7139
|
-
return computed(new NumberFieldType(), [], true, true);
|
|
7150
|
+
return computed(new NumberFieldType(), [], true, true, this.fn);
|
|
7140
7151
|
}
|
|
7141
7152
|
const base = fn2.resolveOutput(resolveNamedArgs(this.args, engine, scope));
|
|
7142
7153
|
if (base.kind !== "computed") return base;
|
|
7143
7154
|
const nullable = this.fn !== "count";
|
|
7144
|
-
return { ...base, nullable, aggregate: true };
|
|
7155
|
+
return { ...base, nullable, aggregate: true, aggregateFn: this.fn };
|
|
7145
7156
|
}
|
|
7146
7157
|
/** Validate aggregate placement (not in WHERE, not nested) and the function's own named-arg checks. */
|
|
7147
7158
|
validateWalk(engine, scope, p, ctx) {
|
|
@@ -9996,16 +10007,19 @@ function validateWriteValue(engine, scope, p, ctx, field, expr) {
|
|
|
9996
10007
|
}
|
|
9997
10008
|
}
|
|
9998
10009
|
function writeCellSql(expr, field, dialect, ctx) {
|
|
9999
|
-
const
|
|
10000
|
-
|
|
10001
|
-
|
|
10002
|
-
function writeDocument(expr, ctx) {
|
|
10003
|
-
if (expr instanceof LiteralExpr) {
|
|
10004
|
-
return expr.value !== null && typeof expr.value === "object" ? expr.value : void 0;
|
|
10010
|
+
const value2 = writeCellValue(expr, ctx);
|
|
10011
|
+
if (value2 !== void 0 && value2 !== null && (typeof value2 === "object" || isJsonColumn(field))) {
|
|
10012
|
+
return dialect.jsonValue(value2, field?.fieldType);
|
|
10005
10013
|
}
|
|
10014
|
+
return expr.toSQL(dialect, ctx);
|
|
10015
|
+
}
|
|
10016
|
+
function isJsonColumn(field) {
|
|
10017
|
+
return field?.fieldType.resolve() === "json";
|
|
10018
|
+
}
|
|
10019
|
+
function writeCellValue(expr, ctx) {
|
|
10020
|
+
if (expr instanceof LiteralExpr) return expr.value;
|
|
10006
10021
|
if (expr instanceof ParamExpr && Object.prototype.hasOwnProperty.call(ctx.params, expr.name)) {
|
|
10007
|
-
|
|
10008
|
-
return bound !== null && bound !== void 0 && typeof bound === "object" ? bound : void 0;
|
|
10022
|
+
return ctx.params[expr.name];
|
|
10009
10023
|
}
|
|
10010
10024
|
return void 0;
|
|
10011
10025
|
}
|
|
@@ -17439,14 +17453,18 @@ function uniqueParamName(field, taken) {
|
|
|
17439
17453
|
taken.add(name);
|
|
17440
17454
|
return name;
|
|
17441
17455
|
}
|
|
17442
|
-
function expandStar(select, engine) {
|
|
17456
|
+
function expandStar(select, engine, projected) {
|
|
17443
17457
|
const from = select.from;
|
|
17444
17458
|
if (from.sourceKind !== "type" || from.typeName === void 0) return void 0;
|
|
17445
17459
|
const type = engine.type(from.typeName);
|
|
17446
17460
|
if (!type) return void 0;
|
|
17447
|
-
|
|
17448
|
-
|
|
17449
|
-
|
|
17461
|
+
const fields = [];
|
|
17462
|
+
for (const f of type.fields) {
|
|
17463
|
+
const expr = { kind: "field-ref", source: from.alias, field: f.name };
|
|
17464
|
+
if (projected.has(exprDigest(expr))) continue;
|
|
17465
|
+
fields.push({ expr });
|
|
17466
|
+
}
|
|
17467
|
+
return fields;
|
|
17450
17468
|
}
|
|
17451
17469
|
function drillDown(select, engine) {
|
|
17452
17470
|
const sq = expandSelectOutputs(asSelectQuery(select, engine), engine);
|
|
@@ -17479,6 +17497,10 @@ function drillDown(select, engine) {
|
|
|
17479
17497
|
canon: canonicalize(c.expr),
|
|
17480
17498
|
name: nameOf(c.expr, c.as, i)
|
|
17481
17499
|
}));
|
|
17500
|
+
const projected = /* @__PURE__ */ new Set();
|
|
17501
|
+
sq.fields.forEach((c, i) => {
|
|
17502
|
+
if (!c.expr.containsAggregate()) projected.add(colInfo[i].canon);
|
|
17503
|
+
});
|
|
17482
17504
|
const taken = referencedParamNames(sq);
|
|
17483
17505
|
const params = [];
|
|
17484
17506
|
const pinned = [];
|
|
@@ -17495,7 +17517,7 @@ function drillDown(select, engine) {
|
|
|
17495
17517
|
sq.fields.forEach((c, i) => {
|
|
17496
17518
|
const e2 = c.expr;
|
|
17497
17519
|
if (e2 instanceof AggregateExpr && e2.valueArg() === void 0) {
|
|
17498
|
-
const expanded = expandStar(sq, engine);
|
|
17520
|
+
const expanded = expandStar(sq, engine, projected);
|
|
17499
17521
|
if (!expanded) {
|
|
17500
17522
|
errors.at(
|
|
17501
17523
|
["fields", i],
|