@aeye/query 0.3.10 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -6
- package/aeye-query.md +3 -3
- package/dist/index.d.ts +60 -15
- package/dist/index.js +292 -41
- package/package.json +51 -51
package/README.md
CHANGED
|
@@ -45,6 +45,17 @@ automatically gain the matching has-many field pointing back. The join key on
|
|
|
45
45
|
either side resolves through each Type's *identity field* (the field of its
|
|
46
46
|
first unique single-field index, else the field named `id`).
|
|
47
47
|
|
|
48
|
+
A relation field can be **compared directly to a value** in `= <> in notIn`,
|
|
49
|
+
where the value is an object keyed by the target's **primary key** (single or
|
|
50
|
+
composite) — `{ kind: 'comparison', op: '=', left: relRef, right: { kind:
|
|
51
|
+
'param', name: 'u' } }` with `:u = { id: 5 }` (a single-key relation also
|
|
52
|
+
accepts a bare scalar). A **belongs-to** matches its FK columns; a **has-many**
|
|
53
|
+
matches by **membership** — `= value` is a correlated `EXISTS` testing that the
|
|
54
|
+
value's key is in the related set (`<>` / `notIn` → `NOT EXISTS`). Two relations
|
|
55
|
+
of the same target compare by their FK key (`order.customer = invoice.customer`);
|
|
56
|
+
a has-many may not be compared to another relation. Ordering / LIKE on a relation
|
|
57
|
+
is rejected — a relation compares by identity, not order.
|
|
58
|
+
|
|
48
59
|
Indexes are **composite**: an ordered list of parts, each with a prefix
|
|
49
60
|
distinct-row `count` (non-increasing); the index is unique iff its last part's
|
|
50
61
|
`count === 1`. Text matching is **case-insensitive by default** — set a text
|
|
@@ -839,17 +850,32 @@ identifier; suffixed `_2`, `_3`, … on collision with a param the query already
|
|
|
839
850
|
uses). Failure cases (`drill.no-aggregation` / `non-invertible` /
|
|
840
851
|
`having-aggregate` / `window-unsupported`) return LLM-friendly `Problems`.
|
|
841
852
|
|
|
842
|
-
## Cost
|
|
853
|
+
## Cost & estimation
|
|
843
854
|
|
|
844
|
-
|
|
845
|
-
indexes
|
|
855
|
+
Bottom-up estimates driven by each Type's cardinality (`count` rows, `bytes`
|
|
856
|
+
per row), its indexes + fixed **selectivity** for predicates (an indexed
|
|
857
|
+
equality narrows toward one row; a non-indexed one applies `EQ_SELECTIVITY`),
|
|
858
|
+
and per-Type / per-field `changes` rates. Five estimators hang off the engine:
|
|
846
859
|
|
|
847
860
|
```ts
|
|
848
|
-
const cost
|
|
849
|
-
const
|
|
850
|
-
//
|
|
861
|
+
const cost = engine.cost(select); // { rows, bytes } — WORK to produce the result (scanned rows)
|
|
862
|
+
const output = engine.outputCost(select); // { rows, bytes } — SIZE of the result (delivered rows × projection width)
|
|
863
|
+
const affected = engine.affected(update); // { rows, types: [{ type, rows }] } — rows an INSERT/UPDATE/DELETE (or CTE) mutates
|
|
864
|
+
const refs = engine.references(select); // { types, fields, functions } — exactly what the query READS
|
|
865
|
+
const ttl = engine.changeInterval(select); // ms until the data behind it could change (0 = always, -1 = never, else fastest rate)
|
|
866
|
+
|
|
867
|
+
// Constraints reject over-budget queries during validation:
|
|
868
|
+
const problems = engine.validateQuery(select, undefined, { maxRows: 100, maxBytes: 1_000_000 });
|
|
869
|
+
// → cost.rows-exceeded / cost.bytes-exceeded when the estimate blows past a cap
|
|
851
870
|
```
|
|
852
871
|
|
|
872
|
+
`cost` estimates work (OR-aware, index-probe driven); `outputCost` sizes the
|
|
873
|
+
delivered result (post-WHERE/GROUP/DISTINCT, capped by LIMIT/OFFSET);
|
|
874
|
+
`affected` counts mutated rows per Type; `references` powers `changeInterval`,
|
|
875
|
+
which folds the read Types' / fields' / functions' `changes` rates into a single
|
|
876
|
+
freshness / cache-TTL signal. All accept the same execution-time
|
|
877
|
+
`options.params` / `filters` / `sort` so the estimate reflects what actually runs.
|
|
878
|
+
|
|
853
879
|
## Functions
|
|
854
880
|
|
|
855
881
|
All four function shapes are uniform: declare a `FunctionDef` (name, shape,
|
package/aeye-query.md
CHANGED
|
@@ -47,11 +47,11 @@ Every kind is one branch of the `ExprDef` union. Availability in the LLM schema
|
|
|
47
47
|
| `relation-path` | Walks relation fields from a source (optionally ending at a scalar); planner synthesizes the joins. |
|
|
48
48
|
| `binary` | Arithmetic `left <op> right` (`+ - * / %`). |
|
|
49
49
|
| `unary` | `<op> operand` (`-` / `+`). |
|
|
50
|
-
| `comparison` | `left <op> right` → boolean (`= <> < <= > >=`, `like`, `notLike`, `ilike`). |
|
|
50
|
+
| `comparison` | `left <op> right` → boolean (`= <> < <= > >=`, `like`, `notLike`, `ilike`). A RELATION operand compares by identity in `=`/`<>` only: RHS a same-target relation (FK key) or a `{ pk }` value param; a has-many compares by membership (correlated `EXISTS`). |
|
|
51
51
|
| `logical` | Boolean connective `and` / `or` / `not` over operands. |
|
|
52
52
|
| `is-null` | `value IS [NOT] NULL`. |
|
|
53
53
|
| `between` | `value BETWEEN lower AND upper` (negatable). |
|
|
54
|
-
| `in` | `value IN (list \| subquery)` (negatable). |
|
|
54
|
+
| `in` | `value IN (list \| subquery)` (negatable). A RELATION `value` matches list `{ pk }` values by FK key (belongs-to) or membership (has-many). |
|
|
55
55
|
| `case` | `CASE WHEN … THEN … [ELSE …] END`. |
|
|
56
56
|
| `function-call` | A scalar function call by name with named args. |
|
|
57
57
|
| `aggregate` | An aggregate function over a group (`count(*)` = empty args); optional `distinct`. |
|
|
@@ -89,7 +89,7 @@ Everything is referenced by its **Type name** — there is no alias to invent or
|
|
|
89
89
|
- **Single-expression query** — `{ kind: 'expr', expr }` for a scalar computation.
|
|
90
90
|
- **Params** — `{ kind: 'param', name }` infers its type from use; bound at run/emit via `options.params`. Introspect with `query.params(engine)` → `ParamDef[]`.
|
|
91
91
|
- **Filters** — a `filters` placeholder (`{ source, fields? }`) is authored by the LLM but the **predicate is supplied at execution time** by the developer: `options.filters` is a `Record<source, boolean Expr | ExprDef | null>`. The placeholder evaluates/emits it (vacuously `TRUE` when none). Introspect exposed sources + fields with `query.filters(engine)` → `Record<source, { fields: QueryField[] }>` (name + resolved type + nullability + kind, restricted to any `fields` allowlist); `query.filterSources()` lists targetable sources.
|
|
92
|
-
- **Cost** —
|
|
92
|
+
- **Cost & estimation** — bottom-up estimates driven by Type `count`/`bytes`, indexes + selectivity, and per-Type/field `changes` rates. `engine.cost(query)` → `{ rows, bytes }` (the WORK to produce the result); `engine.outputCost(query)` → `{ rows, bytes }` (the SIZE of the result — delivered rows × projection width); `engine.affected(query)` → `{ rows, types[] }` (rows an INSERT/UPDATE/DELETE or CTE mutates, OR-aware via indexes); `engine.references(query)` → `{ types, fields, functions }` (exactly what the query reads, incl. execution-time `filters`/`sort` and called functions); `engine.changeInterval(query)` → ms until the data behind it could change (freshness/cache-TTL: `0` = always, `-1` = never, else the fastest read rate). `validateQuery(query, _, { maxRows, maxBytes })` rejects over-budget queries (`cost.rows-exceeded` / `cost.bytes-exceeded`).
|
|
93
93
|
|
|
94
94
|
## Write model & permissions
|
|
95
95
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1267,22 +1267,37 @@ declare abstract class Dialect implements DialectEntry {
|
|
|
1267
1267
|
* comparison is compared by FK key and a relation-vs-scalar comparison is
|
|
1268
1268
|
* rejected (`compare.relation-vs-value`).
|
|
1269
1269
|
*/
|
|
1270
|
+
/**
|
|
1271
|
+
* One join-key column pair of a relation, oriented to the relation's own side:
|
|
1272
|
+
* `local` a column on the relation's SOURCE side, `foreign` the matching column
|
|
1273
|
+
* on the TARGET (the target's PK field for a belongs-to). `keyType` is the
|
|
1274
|
+
* scalar value type flowing across it — used to type a bind param and to
|
|
1275
|
+
* validate a supplied relation VALUE's field.
|
|
1276
|
+
*/
|
|
1277
|
+
interface RelationKeyPair {
|
|
1278
|
+
readonly local: string;
|
|
1279
|
+
readonly foreign: string;
|
|
1280
|
+
readonly keyType: FieldType;
|
|
1281
|
+
}
|
|
1270
1282
|
interface RelationResolved {
|
|
1271
1283
|
/** The bound source the relation field is read from. */
|
|
1272
1284
|
readonly source: string;
|
|
1273
1285
|
/** The relation field's name on that source. */
|
|
1274
1286
|
readonly field: string;
|
|
1275
|
-
/** The LOCAL key column carrying the value a comparison
|
|
1287
|
+
/** The LOCAL key column carrying the value a comparison compares by (`keys[0].local`). */
|
|
1276
1288
|
readonly keyField: string;
|
|
1277
1289
|
/**
|
|
1278
|
-
* The SCALAR field type of the relation's key VALUE (
|
|
1279
|
-
* target's identity value; a has-many keys on this
|
|
1280
|
-
* bind param compared against the relation be typed
|
|
1281
|
-
* comparison read as an id compare.
|
|
1290
|
+
* The SCALAR field type of the relation's (leading) key VALUE (`keys[0].keyType`).
|
|
1291
|
+
* A belongs-to holds the target's identity value; a has-many keys on this
|
|
1292
|
+
* Type's identity. Lets a bind param compared against the relation be typed.
|
|
1282
1293
|
*/
|
|
1283
1294
|
readonly keyType: FieldType;
|
|
1284
1295
|
/** The relation's target Type name (its `to`). */
|
|
1285
1296
|
readonly to: string;
|
|
1297
|
+
/** Cardinality: `1` = belongs-to (single target row), `>1` = has-many (a set). */
|
|
1298
|
+
readonly count: number;
|
|
1299
|
+
/** The ORDERED join-key pairs (composite-capable) driving relation comparison lowering. */
|
|
1300
|
+
readonly keys: readonly RelationKeyPair[];
|
|
1286
1301
|
}
|
|
1287
1302
|
/** A resolved value that is an entire Type (a whole row/source). */
|
|
1288
1303
|
interface TypeResolved {
|
|
@@ -1923,6 +1938,18 @@ declare class RelationFieldType extends FieldType {
|
|
|
1923
1938
|
* declaring Type's name in camelCase.
|
|
1924
1939
|
*/
|
|
1925
1940
|
resolveKey(relationFieldName: string, thisType: Type, targetType: Type): RelationKey;
|
|
1941
|
+
/**
|
|
1942
|
+
* The UNALIASED, ordered join-key column pairs for this relation — the
|
|
1943
|
+
* composite/backing-aware generalization of {@link resolveKey}. Each pair is
|
|
1944
|
+
* `{ local, foreign }`: `local` a column on THIS Type's side, `foreign` the
|
|
1945
|
+
* matching column on the TARGET (the target's PK field for a belongs-to). Uses
|
|
1946
|
+
* the field's `RelationBacking.keys` when declared, else the single
|
|
1947
|
+
* name-convention pair. Drives relation comparison lowering (`= <> in`).
|
|
1948
|
+
*/
|
|
1949
|
+
resolveKeys(engine: QueryEngine, relationFieldName: string, thisType: Type, targetType: Type): {
|
|
1950
|
+
local: string;
|
|
1951
|
+
foreign: string;
|
|
1952
|
+
}[];
|
|
1926
1953
|
/**
|
|
1927
1954
|
* Resolve the full join `ON` for this relation hop, consulting the field's
|
|
1928
1955
|
* DEV-SIDE `RelationBacking` (physical FK columns / custom predicate) and
|
|
@@ -2545,7 +2572,7 @@ declare class ComparisonExpr extends BoolExpr {
|
|
|
2545
2572
|
readonly right: Expr;
|
|
2546
2573
|
static readonly KIND: "comparison";
|
|
2547
2574
|
/** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
|
|
2548
|
-
static readonly INSTRUCTIONS: "`left <op> right` \u2192 boolean (`= <> < <= > >=`, `like`, `notLike`, `ilike`).
|
|
2575
|
+
static readonly INSTRUCTIONS: "`left <op> right` \u2192 boolean (`= <> < <= > >=`, `like`, `notLike`, `ilike`). A RELATION field-ref compares by IDENTITY with `=`/`<>` ONLY (ordering / LIKE on a relation is rejected). Its RHS may be (a) another relation of the SAME target \u2014 compared by FK key (`order.customer = invoice.customer`); or (b) a `{ pk }` VALUE param keyed by the target's primary-key fields (`assignedUser = :u` with `:u = {id:5}`); a single-key relation also accepts a bare scalar param. A BELONGS-TO compares the FK columns; a HAS-MANY compares by MEMBERSHIP \u2014 `= value` is TRUE when the value's key is in the related set (correlated EXISTS), `<>` is NOT EXISTS; a has-many may not be compared to another relation. Do NOT compare a relation to a scalar id COLUMN/field-ref (the correlation bug) \u2014 JOIN the relation (`joins:[{on:{kind:'relation',source,field,as}}]`) and compare the joined key.";
|
|
2549
2576
|
readonly kind: "comparison";
|
|
2550
2577
|
/** Wrap `left <op> right` as a scalar comparison predicate. */
|
|
2551
2578
|
constructor(op: ComparisonOp, left: Expr, right: Expr);
|
|
@@ -2678,7 +2705,7 @@ declare class InExpr extends BoolExpr {
|
|
|
2678
2705
|
readonly not: boolean;
|
|
2679
2706
|
static readonly KIND: "in";
|
|
2680
2707
|
/** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
|
|
2681
|
-
static readonly INSTRUCTIONS: "`value IN (list | subquery)` (negatable via `not`): membership test. `in` is EITHER an explicit array of value exprs OR a subquery projecting exactly ONE field (correlated or not). To project a value across a relation, add a `relation` join
|
|
2708
|
+
static readonly INSTRUCTIONS: "`value IN (list | subquery)` (negatable via `not`): membership test. `in` is EITHER an explicit array of value exprs OR a subquery projecting exactly ONE field (correlated or not). When `value` is a RELATION field-ref, the list holds `{ pk }` VALUE params (or bare scalars for a single-key relation): a belongs-to matches by FK key, a has-many by MEMBERSHIP (\u2208 the related set); `NOT IN` negates. To project a value across a relation in the SUBQUERY form, add a `relation` join and field-ref the joined alias \u2014 do NOT project/compare a relation field-ref as a scalar id. To correlate the subquery, JOIN the relation and compare the joined key to the outer scalar. Set `not:true` for NOT IN.";
|
|
2682
2709
|
/**
|
|
2683
2710
|
* Worked examples (see `ExprClass.EXAMPLES`) — the two `in` shapes: an explicit
|
|
2684
2711
|
* value LIST, and a single-field SUBQUERY that crosses a relation via a
|
|
@@ -3929,7 +3956,7 @@ declare class JoinCtePlanner {
|
|
|
3929
3956
|
/** The RLS predicate provider, folded into every planned join / CTE. */
|
|
3930
3957
|
readonly rls: RlsProvider | undefined;
|
|
3931
3958
|
/** Bound param values, so RLS predicates with params emit real bindings. */
|
|
3932
|
-
readonly params: Readonly<Record<string,
|
|
3959
|
+
readonly params: Readonly<Record<string, SqlParamValue>>;
|
|
3933
3960
|
/**
|
|
3934
3961
|
* Implicit-join mode: lower every required join to a FROM/USING source item
|
|
3935
3962
|
* plus a WHERE-able key predicate (instead of a `JOIN … ON …` clause). Set
|
|
@@ -3960,7 +3987,7 @@ declare class JoinCtePlanner {
|
|
|
3960
3987
|
/** The RLS predicate provider, folded into every planned join / CTE. */
|
|
3961
3988
|
rls: RlsProvider | undefined,
|
|
3962
3989
|
/** Bound param values, so RLS predicates with params emit real bindings. */
|
|
3963
|
-
params?: Readonly<Record<string,
|
|
3990
|
+
params?: Readonly<Record<string, SqlParamValue>>,
|
|
3964
3991
|
/**
|
|
3965
3992
|
* Implicit-join mode: lower every required join to a FROM/USING source item
|
|
3966
3993
|
* plus a WHERE-able key predicate (instead of a `JOIN … ON …` clause). Set
|
|
@@ -4027,6 +4054,13 @@ declare class JoinCtePlanner {
|
|
|
4027
4054
|
|
|
4028
4055
|
/** A value that may be bound as a SQL parameter. */
|
|
4029
4056
|
type SqlValue = string | number | boolean | null;
|
|
4057
|
+
/**
|
|
4058
|
+
* A supplied param value: a bindable scalar, OR a RELATION KEY object (`{ pk }`
|
|
4059
|
+
* keyed by the target's PK field names) used on the RHS of a relation
|
|
4060
|
+
* comparison (`assignedUser = { id: 5 }`). A relation comparison decomposes the
|
|
4061
|
+
* object into per-column binds; a scalar binds directly.
|
|
4062
|
+
*/
|
|
4063
|
+
type SqlParamValue = SqlValue | Readonly<Record<string, SqlValue>>;
|
|
4030
4064
|
/** A rendered SQL string plus its ordered bind parameters. */
|
|
4031
4065
|
interface RenderedSql {
|
|
4032
4066
|
/** The flat SQL string with dialect-numbered placeholders. */
|
|
@@ -4099,8 +4133,8 @@ declare class SqlContext {
|
|
|
4099
4133
|
readonly rls: RlsProvider | undefined;
|
|
4100
4134
|
/** True while emitting inside an aggregate's argument (fan-out routing). */
|
|
4101
4135
|
readonly inAggregate: boolean;
|
|
4102
|
-
/** Bound parameter VALUES (param name →
|
|
4103
|
-
readonly params: Readonly<Record<string,
|
|
4136
|
+
/** Bound parameter VALUES (param name → scalar, or a relation `{ pk }` object), for `param` emission. */
|
|
4137
|
+
readonly params: Readonly<Record<string, SqlParamValue>>;
|
|
4104
4138
|
/**
|
|
4105
4139
|
* Execution-time filter EXPRS (already parsed), keyed by source name — read
|
|
4106
4140
|
* by a `filters` placeholder's `toSQL`. Propagates to nested levels (a
|
|
@@ -4142,8 +4176,8 @@ declare class SqlContext {
|
|
|
4142
4176
|
rls: RlsProvider | undefined,
|
|
4143
4177
|
/** True while emitting inside an aggregate's argument (fan-out routing). */
|
|
4144
4178
|
inAggregate?: boolean,
|
|
4145
|
-
/** Bound parameter VALUES (param name →
|
|
4146
|
-
params?: Readonly<Record<string,
|
|
4179
|
+
/** Bound parameter VALUES (param name → scalar, or a relation `{ pk }` object), for `param` emission. */
|
|
4180
|
+
params?: Readonly<Record<string, SqlParamValue>>,
|
|
4147
4181
|
/**
|
|
4148
4182
|
* Execution-time filter EXPRS (already parsed), keyed by source name — read
|
|
4149
4183
|
* by a `filters` placeholder's `toSQL`. Propagates to nested levels (a
|
|
@@ -5093,6 +5127,17 @@ declare class Type implements Node {
|
|
|
5093
5127
|
* a clear error. Relations resolve their keys through this.
|
|
5094
5128
|
*/
|
|
5095
5129
|
identityField(): Field;
|
|
5130
|
+
/**
|
|
5131
|
+
* The ordered PRIMARY KEY fields of this Type — generalizing {@link
|
|
5132
|
+
* identityField} to COMPOSITE keys: the single identity field (a single-part
|
|
5133
|
+
* unique index's field, else `id`) when present, else the fields of the first
|
|
5134
|
+
* multi-part UNIQUE index (last part `count === 1`) whose every part is a
|
|
5135
|
+
* field-ref. Relations map their key columns to these; a relation VALUE is
|
|
5136
|
+
* keyed by these field names. Throws when none exists.
|
|
5137
|
+
*/
|
|
5138
|
+
primaryKey(): Field[];
|
|
5139
|
+
/** The single identity field: the first single-part unique index's field, else `id`, else undefined. */
|
|
5140
|
+
private singleIdentity;
|
|
5096
5141
|
/**
|
|
5097
5142
|
* Fields eligible for semantic-aware querying: text fields flagged
|
|
5098
5143
|
* `semantic` or `search`, plus all relation fields (which can drive
|
|
@@ -5614,7 +5659,7 @@ declare class QueryEngine {
|
|
|
5614
5659
|
*/
|
|
5615
5660
|
toSQL(query: Query | QueryDef, dialect: string | Dialect, opts?: {
|
|
5616
5661
|
rls?: RlsProvider;
|
|
5617
|
-
params?: Readonly<Record<string,
|
|
5662
|
+
params?: Readonly<Record<string, SqlParamValue>>;
|
|
5618
5663
|
filters?: Record<string, ExprDef | Expr | null>;
|
|
5619
5664
|
sort?: SortSelectionDef[];
|
|
5620
5665
|
includeTotal?: boolean;
|
|
@@ -5659,7 +5704,7 @@ declare class QueryEngine {
|
|
|
5659
5704
|
*/
|
|
5660
5705
|
exprToSQL(expr: Expr | ExprDef, dialect: string | Dialect, opts?: {
|
|
5661
5706
|
rls?: RlsProvider;
|
|
5662
|
-
params?: Readonly<Record<string,
|
|
5707
|
+
params?: Readonly<Record<string, SqlParamValue>>;
|
|
5663
5708
|
filters?: Record<string, ExprDef | Expr | null>;
|
|
5664
5709
|
}): RenderedSql;
|
|
5665
5710
|
}
|
package/dist/index.js
CHANGED
|
@@ -1182,18 +1182,18 @@ async function resolveSemanticRun(semantic2, alias, row, queryVector, ctx) {
|
|
|
1182
1182
|
function readFieldText(row, alias, field) {
|
|
1183
1183
|
const rec = row[alias];
|
|
1184
1184
|
if (!rec) return "";
|
|
1185
|
-
const
|
|
1186
|
-
if (typeof
|
|
1187
|
-
if (Array.isArray(
|
|
1185
|
+
const cell2 = rec[field];
|
|
1186
|
+
if (typeof cell2 === "string") return cell2;
|
|
1187
|
+
if (Array.isArray(cell2)) return cell2.filter((x) => typeof x === "string").join(" ");
|
|
1188
1188
|
return "";
|
|
1189
1189
|
}
|
|
1190
1190
|
function readFieldVector(row, alias, field) {
|
|
1191
1191
|
const rec = row[alias];
|
|
1192
1192
|
if (!rec) return null;
|
|
1193
|
-
const
|
|
1194
|
-
if (!Array.isArray(
|
|
1193
|
+
const cell2 = rec[field];
|
|
1194
|
+
if (!Array.isArray(cell2)) return null;
|
|
1195
1195
|
const out = [];
|
|
1196
|
-
for (const v of
|
|
1196
|
+
for (const v of cell2) {
|
|
1197
1197
|
if (typeof v !== "number") return null;
|
|
1198
1198
|
out.push(v);
|
|
1199
1199
|
}
|
|
@@ -1295,6 +1295,32 @@ var RelationFieldType = class _RelationFieldType extends FieldType {
|
|
|
1295
1295
|
foreignField: fk
|
|
1296
1296
|
};
|
|
1297
1297
|
}
|
|
1298
|
+
/**
|
|
1299
|
+
* The UNALIASED, ordered join-key column pairs for this relation — the
|
|
1300
|
+
* composite/backing-aware generalization of {@link resolveKey}. Each pair is
|
|
1301
|
+
* `{ local, foreign }`: `local` a column on THIS Type's side, `foreign` the
|
|
1302
|
+
* matching column on the TARGET (the target's PK field for a belongs-to). Uses
|
|
1303
|
+
* the field's `RelationBacking.keys` when declared, else the single
|
|
1304
|
+
* name-convention pair. Drives relation comparison lowering (`= <> in`).
|
|
1305
|
+
*/
|
|
1306
|
+
resolveKeys(engine, relationFieldName, thisType, targetType) {
|
|
1307
|
+
const forward = this.count === 1;
|
|
1308
|
+
let backing;
|
|
1309
|
+
if (forward) {
|
|
1310
|
+
backing = engine.fieldBacking(thisType.name, relationFieldName)?.relation;
|
|
1311
|
+
} else if (this.inverseVia !== void 0) {
|
|
1312
|
+
backing = engine.fieldBacking(targetType.name, this.inverseVia)?.relation;
|
|
1313
|
+
}
|
|
1314
|
+
if (backing?.keys && backing.keys.length > 0) {
|
|
1315
|
+
const targetIdentity = backing.keys.some((k) => k.foreign === void 0) ? (
|
|
1316
|
+
/* v8 ignore next -- a forward=false (has-many) key omitting `foreign` is not reachable via the tested inverse backings */
|
|
1317
|
+
(forward ? targetType : thisType).identityField().name
|
|
1318
|
+
) : "";
|
|
1319
|
+
return relationKeyColumns(backing.keys, forward, targetIdentity).map((p) => ({ local: p.localField, foreign: p.foreignField }));
|
|
1320
|
+
}
|
|
1321
|
+
const single = this.resolveKey(relationFieldName, thisType, targetType);
|
|
1322
|
+
return [{ local: single.localField, foreign: single.foreignField }];
|
|
1323
|
+
}
|
|
1298
1324
|
/**
|
|
1299
1325
|
* Resolve the full join `ON` for this relation hop, consulting the field's
|
|
1300
1326
|
* DEV-SIDE `RelationBacking` (physical FK columns / custom predicate) and
|
|
@@ -1950,6 +1976,9 @@ var Index = class _Index {
|
|
|
1950
1976
|
|
|
1951
1977
|
// src/type.ts
|
|
1952
1978
|
import { z as z12 } from "zod";
|
|
1979
|
+
function noKeyMessage(typeName) {
|
|
1980
|
+
return `Type '${typeName}' needs a primary key (a unique index or an 'id' field) to participate in relations.`;
|
|
1981
|
+
}
|
|
1953
1982
|
var Type = class _Type {
|
|
1954
1983
|
/** Type name (unique within the registry). */
|
|
1955
1984
|
name;
|
|
@@ -2012,6 +2041,31 @@ var Type = class _Type {
|
|
|
2012
2041
|
* a clear error. Relations resolve their keys through this.
|
|
2013
2042
|
*/
|
|
2014
2043
|
identityField() {
|
|
2044
|
+
const single = this.singleIdentity();
|
|
2045
|
+
if (single) return single;
|
|
2046
|
+
throw new QueryTypeError({ path: [], code: "type.no-identity", severity: "error", message: noKeyMessage(this.name) });
|
|
2047
|
+
}
|
|
2048
|
+
/**
|
|
2049
|
+
* The ordered PRIMARY KEY fields of this Type — generalizing {@link
|
|
2050
|
+
* identityField} to COMPOSITE keys: the single identity field (a single-part
|
|
2051
|
+
* unique index's field, else `id`) when present, else the fields of the first
|
|
2052
|
+
* multi-part UNIQUE index (last part `count === 1`) whose every part is a
|
|
2053
|
+
* field-ref. Relations map their key columns to these; a relation VALUE is
|
|
2054
|
+
* keyed by these field names. Throws when none exists.
|
|
2055
|
+
*/
|
|
2056
|
+
primaryKey() {
|
|
2057
|
+
const single = this.singleIdentity();
|
|
2058
|
+
if (single) return [single];
|
|
2059
|
+
for (const idx of this.indexes) {
|
|
2060
|
+
const last = idx.parts[idx.parts.length - 1];
|
|
2061
|
+
if (!last || last.count !== 1) continue;
|
|
2062
|
+
const fields = idx.parts.map((p) => p.expr.kind === "field-ref" ? this.field(p.expr.field) : void 0);
|
|
2063
|
+
if (fields.every((f) => f !== void 0)) return fields;
|
|
2064
|
+
}
|
|
2065
|
+
throw new QueryTypeError({ path: [], code: "type.no-identity", severity: "error", message: noKeyMessage(this.name) });
|
|
2066
|
+
}
|
|
2067
|
+
/** The single identity field: the first single-part unique index's field, else `id`, else undefined. */
|
|
2068
|
+
singleIdentity() {
|
|
2015
2069
|
for (const idx of this.indexes) {
|
|
2016
2070
|
if (idx.parts.length !== 1) continue;
|
|
2017
2071
|
const part = idx.parts[0];
|
|
@@ -2020,14 +2074,7 @@ var Type = class _Type {
|
|
|
2020
2074
|
const field = this.field(part.expr.field);
|
|
2021
2075
|
if (field) return field;
|
|
2022
2076
|
}
|
|
2023
|
-
|
|
2024
|
-
if (byName) return byName;
|
|
2025
|
-
throw new QueryTypeError({
|
|
2026
|
-
path: [],
|
|
2027
|
-
code: "type.no-identity",
|
|
2028
|
-
severity: "error",
|
|
2029
|
-
message: `Type '${this.name}' needs an identity field (a unique single-field index or an 'id' field) to participate in relations.`
|
|
2030
|
-
});
|
|
2077
|
+
return this.field("id");
|
|
2031
2078
|
}
|
|
2032
2079
|
/**
|
|
2033
2080
|
* Fields eligible for semantic-aware querying: text fields flagged
|
|
@@ -4039,9 +4086,25 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
|
|
|
4039
4086
|
);
|
|
4040
4087
|
return textResult([], true);
|
|
4041
4088
|
}
|
|
4042
|
-
const
|
|
4043
|
-
|
|
4044
|
-
|
|
4089
|
+
const keys = ft.resolveKeys(engine, this.field, ownerType, target).map((kp) => {
|
|
4090
|
+
const tf = target.field(kp.foreign);
|
|
4091
|
+
let keyType;
|
|
4092
|
+
if (tf && !(tf.fieldType instanceof RelationFieldType)) {
|
|
4093
|
+
keyType = tf.fieldType;
|
|
4094
|
+
} else {
|
|
4095
|
+
keyType = (ft.count === 1 ? target : ownerType).identityField().fieldType;
|
|
4096
|
+
}
|
|
4097
|
+
return { local: kp.local, foreign: kp.foreign, keyType };
|
|
4098
|
+
});
|
|
4099
|
+
const relation = {
|
|
4100
|
+
source: this.source,
|
|
4101
|
+
field: this.field,
|
|
4102
|
+
keyField: keys[0].local,
|
|
4103
|
+
keyType: keys[0].keyType,
|
|
4104
|
+
to: ft.to,
|
|
4105
|
+
count: ft.count,
|
|
4106
|
+
keys
|
|
4107
|
+
};
|
|
4045
4108
|
const resolved = {
|
|
4046
4109
|
kind: "type",
|
|
4047
4110
|
type: target,
|
|
@@ -4409,7 +4472,8 @@ var ParamExpr = class _ParamExpr extends Expr {
|
|
|
4409
4472
|
}
|
|
4410
4473
|
/** Emit as a bound SqlText param slot (null until a value is supplied). */
|
|
4411
4474
|
toSQL(_dialect, ctx) {
|
|
4412
|
-
const
|
|
4475
|
+
const raw2 = Object.prototype.hasOwnProperty.call(ctx.params, this.name) ? ctx.params[this.name] : null;
|
|
4476
|
+
const value2 = raw2 !== null && typeof raw2 === "object" ? null : raw2;
|
|
4413
4477
|
return SqlText.param(value2);
|
|
4414
4478
|
}
|
|
4415
4479
|
/** Serialize back to its JSON ExprDef. */
|
|
@@ -4710,6 +4774,151 @@ var UnaryExpr = class _UnaryExpr extends Expr {
|
|
|
4710
4774
|
// src/exprs/comparison.ts
|
|
4711
4775
|
import { z as z20 } from "zod";
|
|
4712
4776
|
|
|
4777
|
+
// src/runtime/tri.ts
|
|
4778
|
+
function not3(a) {
|
|
4779
|
+
return a === void 0 ? void 0 : !a;
|
|
4780
|
+
}
|
|
4781
|
+
function and3(a, b) {
|
|
4782
|
+
if (a === false || b === false) return false;
|
|
4783
|
+
if (a === void 0 || b === void 0) return void 0;
|
|
4784
|
+
return true;
|
|
4785
|
+
}
|
|
4786
|
+
function or3(a, b) {
|
|
4787
|
+
if (a === true || b === true) return true;
|
|
4788
|
+
if (a === void 0 || b === void 0) return void 0;
|
|
4789
|
+
return false;
|
|
4790
|
+
}
|
|
4791
|
+
function triOf(v) {
|
|
4792
|
+
return v.isNull() ? void 0 : v.toBoolean();
|
|
4793
|
+
}
|
|
4794
|
+
|
|
4795
|
+
// src/exprs/_relation-compare.ts
|
|
4796
|
+
var HAS_MANY_ALIAS = "__rel";
|
|
4797
|
+
function relationCompare(operand, engine, typeOf) {
|
|
4798
|
+
const ref3 = operand.fieldRef();
|
|
4799
|
+
if (!ref3) return void 0;
|
|
4800
|
+
const owner = typeOf(ref3.source);
|
|
4801
|
+
if (!owner) return void 0;
|
|
4802
|
+
const field = owner.field(ref3.field);
|
|
4803
|
+
if (!field || !(field.fieldType instanceof RelationFieldType)) return void 0;
|
|
4804
|
+
const ft = field.fieldType;
|
|
4805
|
+
const target = engine.type(ft.to);
|
|
4806
|
+
if (!target) return void 0;
|
|
4807
|
+
return { source: ref3.source, keys: ft.resolveKeys(engine, ref3.field, owner, target), count: ft.count, target };
|
|
4808
|
+
}
|
|
4809
|
+
function runtimeTypeOf(ctx) {
|
|
4810
|
+
return (s) => ctx.sourceType(s) ?? ctx.engine.type(s);
|
|
4811
|
+
}
|
|
4812
|
+
function sqlTypeOf(ctx) {
|
|
4813
|
+
return (s) => {
|
|
4814
|
+
const b = ctx.scope.lookup(s);
|
|
4815
|
+
return b && b.kind === "type" ? b.type : void 0;
|
|
4816
|
+
};
|
|
4817
|
+
}
|
|
4818
|
+
function column(row, source, name, ctx) {
|
|
4819
|
+
const rec = row[source] ?? ctx.correlation?.[source];
|
|
4820
|
+
if (!rec) return Value.null();
|
|
4821
|
+
return cell(rec, name);
|
|
4822
|
+
}
|
|
4823
|
+
async function tuple(operand, rel, keys, row, ctx, group) {
|
|
4824
|
+
if (rel) return rel.keys.map((k) => column(row, rel.source, k.local, ctx));
|
|
4825
|
+
const v = await operand.evaluate(ctx, row, group);
|
|
4826
|
+
if (v.isNull()) return keys.map(() => Value.null());
|
|
4827
|
+
const raw2 = v.raw;
|
|
4828
|
+
if (raw2 !== null && typeof raw2 === "object" && !Array.isArray(raw2)) {
|
|
4829
|
+
const obj2 = raw2;
|
|
4830
|
+
return keys.map((k) => Value.of(obj2[k.foreign] ?? null));
|
|
4831
|
+
}
|
|
4832
|
+
return [v];
|
|
4833
|
+
}
|
|
4834
|
+
function eq3(a, b) {
|
|
4835
|
+
if (a.isNull() || b.isNull()) return void 0;
|
|
4836
|
+
return a.compareTo(b) === 0;
|
|
4837
|
+
}
|
|
4838
|
+
function cell(rec, name) {
|
|
4839
|
+
return Value.of(rec[name] ?? null);
|
|
4840
|
+
}
|
|
4841
|
+
async function evaluateRelationCompare(op, left, right, leftRel, rightRel, row, ctx, group) {
|
|
4842
|
+
const keys = (leftRel ?? rightRel).keys;
|
|
4843
|
+
const lt2 = await tuple(left, leftRel, keys, row, ctx, group);
|
|
4844
|
+
const rt = await tuple(right, rightRel, keys, row, ctx, group);
|
|
4845
|
+
let acc = true;
|
|
4846
|
+
for (let i = 0; i < keys.length; i++) acc = and3(acc, eq3(lt2[i], rt[i]));
|
|
4847
|
+
return op === "=" ? acc : not3(acc);
|
|
4848
|
+
}
|
|
4849
|
+
async function valueTuple(value2, pkFields, row, ctx, group) {
|
|
4850
|
+
const v = await value2.evaluate(ctx, row, group);
|
|
4851
|
+
if (v.isNull()) return pkFields.map(() => Value.null());
|
|
4852
|
+
const raw2 = v.raw;
|
|
4853
|
+
if (raw2 !== null && typeof raw2 === "object" && !Array.isArray(raw2)) {
|
|
4854
|
+
const obj2 = raw2;
|
|
4855
|
+
return pkFields.map((f) => Value.of(obj2[f] ?? null));
|
|
4856
|
+
}
|
|
4857
|
+
return [v];
|
|
4858
|
+
}
|
|
4859
|
+
async function evaluateHasMany(op, rel, value2, row, ctx, group) {
|
|
4860
|
+
const pkFields = rel.target.primaryKey().map((f) => f.name);
|
|
4861
|
+
const outer = rel.keys.map((k) => column(row, rel.source, k.local, ctx));
|
|
4862
|
+
const pkVals = await valueTuple(value2, pkFields, row, ctx, group);
|
|
4863
|
+
if (outer.some((v) => v.isNull()) || pkVals.some((v) => v.isNull())) return op !== "=";
|
|
4864
|
+
const rows = (await ctx.typeState(rel.target)).current;
|
|
4865
|
+
const found = rows.some(
|
|
4866
|
+
(tr) => rel.keys.every((k, i) => eq3(cell(tr, k.foreign), outer[i]) === true) && pkFields.every((f, i) => eq3(cell(tr, f), pkVals[i]) === true)
|
|
4867
|
+
);
|
|
4868
|
+
return op === "=" ? found : !found;
|
|
4869
|
+
}
|
|
4870
|
+
function tupleSql(operand, rel, keys, dialect, ctx) {
|
|
4871
|
+
if (rel) return rel.keys.map((k) => new FieldRefExpr(rel.source, k.local).toSQL(dialect, ctx));
|
|
4872
|
+
if (operand instanceof ParamExpr) {
|
|
4873
|
+
const pv = ctx.params[operand.name];
|
|
4874
|
+
if (pv !== null && pv !== void 0 && typeof pv === "object") {
|
|
4875
|
+
const obj2 = pv;
|
|
4876
|
+
return keys.map((k) => SqlText.param(obj2[k.foreign] ?? null));
|
|
4877
|
+
}
|
|
4878
|
+
return [SqlText.param(pv ?? null)];
|
|
4879
|
+
}
|
|
4880
|
+
return [operand.toSQL(dialect, ctx)];
|
|
4881
|
+
}
|
|
4882
|
+
function emitRelationCompare(op, left, right, leftRel, rightRel, dialect, ctx) {
|
|
4883
|
+
const keys = (leftRel ?? rightRel).keys;
|
|
4884
|
+
const ls = tupleSql(left, leftRel, keys, dialect, ctx);
|
|
4885
|
+
const rs = tupleSql(right, rightRel, keys, dialect, ctx);
|
|
4886
|
+
const eqs = keys.map((_, i) => SqlText.join([ls[i], SqlText.raw("="), rs[i]], " "));
|
|
4887
|
+
const anded = SqlText.join(eqs, " AND ").parens();
|
|
4888
|
+
return op === "=" ? anded : SqlText.concat([SqlText.raw("NOT "), anded]);
|
|
4889
|
+
}
|
|
4890
|
+
function valueComponentsSql(value2, pkFields, ctx) {
|
|
4891
|
+
if (!(value2 instanceof ParamExpr)) return pkFields.map(() => null);
|
|
4892
|
+
const pv = ctx.params[value2.name];
|
|
4893
|
+
if (pv !== null && pv !== void 0 && typeof pv === "object") {
|
|
4894
|
+
const obj2 = pv;
|
|
4895
|
+
return pkFields.map((f) => obj2[f] ?? null);
|
|
4896
|
+
}
|
|
4897
|
+
return [pv ?? null];
|
|
4898
|
+
}
|
|
4899
|
+
function emitHasMany(op, rel, value2, dialect, ctx) {
|
|
4900
|
+
const pkFields = rel.target.primaryKey().map((f) => f.name);
|
|
4901
|
+
const comps = valueComponentsSql(value2, pkFields, ctx);
|
|
4902
|
+
const eq2 = (left, right) => ({ kind: "comparison", op: "=", left, right });
|
|
4903
|
+
const col = (source, field) => ({ kind: "field-ref", source, field });
|
|
4904
|
+
const where = [
|
|
4905
|
+
// Correlation: each has-many key joins the target's FK-back column to this row's identity.
|
|
4906
|
+
...rel.keys.map((k) => eq2(col(HAS_MANY_ALIAS, k.foreign), col(rel.source, k.local))),
|
|
4907
|
+
// Membership: the target's PK equals the value's components.
|
|
4908
|
+
...pkFields.map((pk, i) => eq2(col(HAS_MANY_ALIAS, pk), { kind: "literal", value: comps[i] ?? null }))
|
|
4909
|
+
];
|
|
4910
|
+
const def = {
|
|
4911
|
+
kind: "select",
|
|
4912
|
+
// Project the target's PK column (a bare ref, no bound param) — EXISTS
|
|
4913
|
+
// ignores the projected value, and `SELECT 1` would bind a stray literal.
|
|
4914
|
+
fields: [{ expr: col(HAS_MANY_ALIAS, pkFields[0]) }],
|
|
4915
|
+
from: { kind: "aliased", type: rel.target.name, as: HAS_MANY_ALIAS },
|
|
4916
|
+
where
|
|
4917
|
+
};
|
|
4918
|
+
const sub2 = emitSubquerySQL(dialect, ctx, def);
|
|
4919
|
+
return SqlText.concat([SqlText.raw(op === "=" ? "EXISTS " : "NOT EXISTS "), sub2]);
|
|
4920
|
+
}
|
|
4921
|
+
|
|
4713
4922
|
// src/exprs/_field-guard.ts
|
|
4714
4923
|
function operandCtx(operand, kind, ctx, relationOk = false) {
|
|
4715
4924
|
if (!(operand instanceof FieldRefExpr)) return ctx;
|
|
@@ -4779,7 +4988,7 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
|
|
|
4779
4988
|
right;
|
|
4780
4989
|
static KIND = "comparison";
|
|
4781
4990
|
/** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
|
|
4782
|
-
static INSTRUCTIONS = "`left <op> right` \u2192 boolean (`= <> < <= > >=`, `like`, `notLike`, `ilike`).
|
|
4991
|
+
static INSTRUCTIONS = "`left <op> right` \u2192 boolean (`= <> < <= > >=`, `like`, `notLike`, `ilike`). A RELATION field-ref compares by IDENTITY with `=`/`<>` ONLY (ordering / LIKE on a relation is rejected). Its RHS may be (a) another relation of the SAME target \u2014 compared by FK key (`order.customer = invoice.customer`); or (b) a `{ pk }` VALUE param keyed by the target's primary-key fields (`assignedUser = :u` with `:u = {id:5}`); a single-key relation also accepts a bare scalar param. A BELONGS-TO compares the FK columns; a HAS-MANY compares by MEMBERSHIP \u2014 `= value` is TRUE when the value's key is in the related set (correlated EXISTS), `<>` is NOT EXISTS; a has-many may not be compared to another relation. Do NOT compare a relation to a scalar id COLUMN/field-ref (the correlation bug) \u2014 JOIN the relation (`joins:[{on:{kind:'relation',source,field,as}}]`) and compare the joined key.";
|
|
4783
4992
|
kind = _ComparisonExpr.KIND;
|
|
4784
4993
|
/** Reconstruct a ComparisonExpr from its JSON def (validates `kind`, recurses into operands via `registry.parseExpr`). */
|
|
4785
4994
|
static from(json, registry) {
|
|
@@ -4831,6 +5040,18 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
|
|
|
4831
5040
|
const r = p.at("right", () => this.right.validateWalk(engine, scope, p, operandCtx(this.right, "comparison", ctx, true)));
|
|
4832
5041
|
const lft = asFieldType(l);
|
|
4833
5042
|
const rft = asFieldType(r);
|
|
5043
|
+
if (this.op !== "=" && this.op !== "<>" && (relationOf(l) || relationOf(r))) {
|
|
5044
|
+
p.error("comparison.relation-order", `A relation compares by identity \u2014 use '=' or '<>', not '${this.op}'.`);
|
|
5045
|
+
}
|
|
5046
|
+
const lRel = relationOf(l);
|
|
5047
|
+
const rRel = relationOf(r);
|
|
5048
|
+
if (lRel && rRel && (lRel.count > 1 || rRel.count > 1)) {
|
|
5049
|
+
const set = lRel.count > 1 ? lRel : rRel;
|
|
5050
|
+
p.error(
|
|
5051
|
+
"comparison.relation-set",
|
|
5052
|
+
`Has-many relation '${set.source}.${set.field}' compares against a value (its members' key), not another relation ('${(set === lRel ? rRel : lRel).source}.${(set === lRel ? rRel : lRel).field}').`
|
|
5053
|
+
);
|
|
5054
|
+
}
|
|
4834
5055
|
if (LIKE_OPS.has(this.op)) {
|
|
4835
5056
|
if (!exempt2(this.left) && categoryOf(l) !== "text") {
|
|
4836
5057
|
p.at(
|
|
@@ -4890,6 +5111,16 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
|
|
|
4890
5111
|
}
|
|
4891
5112
|
/** Evaluate under 3VL: a NULL operand yields UNKNOWN; text compares case-insensitively unless a `sensitive` field is involved. */
|
|
4892
5113
|
async evaluateBool(ctx, row, group) {
|
|
5114
|
+
if (this.op === "=" || this.op === "<>") {
|
|
5115
|
+
const typeOf = runtimeTypeOf(ctx);
|
|
5116
|
+
const leftRel = relationCompare(this.left, ctx.engine, typeOf);
|
|
5117
|
+
const rightRel = relationCompare(this.right, ctx.engine, typeOf);
|
|
5118
|
+
if (leftRel && leftRel.count > 1) return evaluateHasMany(this.op, leftRel, this.right, row, ctx, group);
|
|
5119
|
+
if (rightRel && rightRel.count > 1) return evaluateHasMany(this.op, rightRel, this.left, row, ctx, group);
|
|
5120
|
+
if (leftRel || rightRel) {
|
|
5121
|
+
return evaluateRelationCompare(this.op, this.left, this.right, leftRel, rightRel, row, ctx, group);
|
|
5122
|
+
}
|
|
5123
|
+
}
|
|
4893
5124
|
const l = await this.left.evaluate(ctx, row, group);
|
|
4894
5125
|
const r = await this.right.evaluate(ctx, row, group);
|
|
4895
5126
|
if (l.isNull() || r.isNull()) return void 0;
|
|
@@ -4927,6 +5158,16 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
|
|
|
4927
5158
|
}
|
|
4928
5159
|
/** Emit as a SqlText fragment (ILIKE delegates to the dialect; case-insensitive text wraps both operands in `LOWER(...)`). */
|
|
4929
5160
|
toSQL(dialect, ctx) {
|
|
5161
|
+
if (this.op === "=" || this.op === "<>") {
|
|
5162
|
+
const typeOf = sqlTypeOf(ctx);
|
|
5163
|
+
const leftRel = relationCompare(this.left, ctx.engine, typeOf);
|
|
5164
|
+
const rightRel = relationCompare(this.right, ctx.engine, typeOf);
|
|
5165
|
+
if (leftRel && leftRel.count > 1) return emitHasMany(this.op, leftRel, this.right, dialect, ctx);
|
|
5166
|
+
if (rightRel && rightRel.count > 1) return emitHasMany(this.op, rightRel, this.left, dialect, ctx);
|
|
5167
|
+
if (leftRel || rightRel) {
|
|
5168
|
+
return emitRelationCompare(this.op, this.left, this.right, leftRel, rightRel, dialect, ctx);
|
|
5169
|
+
}
|
|
5170
|
+
}
|
|
4930
5171
|
let left = this.left.toSQL(dialect, ctx);
|
|
4931
5172
|
let right = this.right.toSQL(dialect, ctx);
|
|
4932
5173
|
if (this.op === "ilike") return dialect.ilike(left, right);
|
|
@@ -4961,26 +5202,6 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
|
|
|
4961
5202
|
|
|
4962
5203
|
// src/exprs/logical.ts
|
|
4963
5204
|
import { z as z21 } from "zod";
|
|
4964
|
-
|
|
4965
|
-
// src/runtime/tri.ts
|
|
4966
|
-
function not3(a) {
|
|
4967
|
-
return a === void 0 ? void 0 : !a;
|
|
4968
|
-
}
|
|
4969
|
-
function and3(a, b) {
|
|
4970
|
-
if (a === false || b === false) return false;
|
|
4971
|
-
if (a === void 0 || b === void 0) return void 0;
|
|
4972
|
-
return true;
|
|
4973
|
-
}
|
|
4974
|
-
function or3(a, b) {
|
|
4975
|
-
if (a === true || b === true) return true;
|
|
4976
|
-
if (a === void 0 || b === void 0) return void 0;
|
|
4977
|
-
return false;
|
|
4978
|
-
}
|
|
4979
|
-
function triOf(v) {
|
|
4980
|
-
return v.isNull() ? void 0 : v.toBoolean();
|
|
4981
|
-
}
|
|
4982
|
-
|
|
4983
|
-
// src/exprs/logical.ts
|
|
4984
5205
|
var LOGICAL_OPS = ["and", "or", "not"];
|
|
4985
5206
|
var LogicalExpr = class _LogicalExpr extends BoolExpr {
|
|
4986
5207
|
/** Wrap a boolean connective (`and` / `or` / `not`) over its operands. */
|
|
@@ -5184,7 +5405,7 @@ var InExpr = class _InExpr extends BoolExpr {
|
|
|
5184
5405
|
not;
|
|
5185
5406
|
static KIND = "in";
|
|
5186
5407
|
/** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
|
|
5187
|
-
static INSTRUCTIONS = "`value IN (list | subquery)` (negatable via `not`): membership test. `in` is EITHER an explicit array of value exprs OR a subquery projecting exactly ONE field (correlated or not). To project a value across a relation, add a `relation` join
|
|
5408
|
+
static INSTRUCTIONS = "`value IN (list | subquery)` (negatable via `not`): membership test. `in` is EITHER an explicit array of value exprs OR a subquery projecting exactly ONE field (correlated or not). When `value` is a RELATION field-ref, the list holds `{ pk }` VALUE params (or bare scalars for a single-key relation): a belongs-to matches by FK key, a has-many by MEMBERSHIP (\u2208 the related set); `NOT IN` negates. To project a value across a relation in the SUBQUERY form, add a `relation` join and field-ref the joined alias \u2014 do NOT project/compare a relation field-ref as a scalar id. To correlate the subquery, JOIN the relation and compare the joined key to the outer scalar. Set `not:true` for NOT IN.";
|
|
5188
5409
|
/**
|
|
5189
5410
|
* Worked examples (see `ExprClass.EXAMPLES`) — the two `in` shapes: an explicit
|
|
5190
5411
|
* value LIST, and a single-field SUBQUERY that crosses a relation via a
|
|
@@ -5370,6 +5591,26 @@ var InExpr = class _InExpr extends BoolExpr {
|
|
|
5370
5591
|
}
|
|
5371
5592
|
/** Evaluate under 3VL: TRUE if any element equals the value; else UNKNOWN if the value or any element is NULL; else FALSE (negated for `NOT IN`). */
|
|
5372
5593
|
async evaluateBool(ctx, row, group) {
|
|
5594
|
+
const typeOf = runtimeTypeOf(ctx);
|
|
5595
|
+
const rel = relationCompare(this.value, ctx.engine, typeOf);
|
|
5596
|
+
if (rel && this.list) {
|
|
5597
|
+
if (rel.count > 1) {
|
|
5598
|
+
let found = false;
|
|
5599
|
+
for (const el of this.list) {
|
|
5600
|
+
if (await evaluateHasMany("=", rel, el, row, ctx, group)) {
|
|
5601
|
+
found = true;
|
|
5602
|
+
break;
|
|
5603
|
+
}
|
|
5604
|
+
}
|
|
5605
|
+
return this.not ? !found : found;
|
|
5606
|
+
}
|
|
5607
|
+
let acc = false;
|
|
5608
|
+
for (const el of this.list) {
|
|
5609
|
+
const elRel = relationCompare(el, ctx.engine, typeOf);
|
|
5610
|
+
acc = or3(acc, await evaluateRelationCompare("=", this.value, el, rel, elRel, row, ctx, group));
|
|
5611
|
+
}
|
|
5612
|
+
return this.not ? not3(acc) : acc;
|
|
5613
|
+
}
|
|
5373
5614
|
const v = await this.value.evaluate(ctx, row, group);
|
|
5374
5615
|
let matched = false;
|
|
5375
5616
|
let anyNull = v.isNull();
|
|
@@ -5399,6 +5640,15 @@ var InExpr = class _InExpr extends BoolExpr {
|
|
|
5399
5640
|
}
|
|
5400
5641
|
/** Emit as a SqlText fragment (`value [NOT] IN (...)` over a list or an emitted subquery). */
|
|
5401
5642
|
toSQL(dialect, ctx) {
|
|
5643
|
+
const typeOf = sqlTypeOf(ctx);
|
|
5644
|
+
const rel = relationCompare(this.value, ctx.engine, typeOf);
|
|
5645
|
+
if (rel && this.list) {
|
|
5646
|
+
const ors = rel.count > 1 ? this.list.map((el) => emitHasMany("=", rel, el, dialect, ctx)) : this.list.map(
|
|
5647
|
+
(el) => emitRelationCompare("=", this.value, el, rel, relationCompare(el, ctx.engine, typeOf), dialect, ctx)
|
|
5648
|
+
);
|
|
5649
|
+
const anded = SqlText.join(ors, " OR ").parens();
|
|
5650
|
+
return this.not ? SqlText.concat([SqlText.raw("NOT "), anded]) : anded;
|
|
5651
|
+
}
|
|
5402
5652
|
const rhs = this.list ? SqlText.join(this.list.map((e2) => e2.toSQL(dialect, ctx)), ", ").parens() : this.subquery ? emitSubquerySQL(dialect, ctx, this.subquery) : SqlText.raw("()");
|
|
5403
5653
|
return SqlText.join(
|
|
5404
5654
|
[this.value.toSQL(dialect, ctx), SqlText.raw(this.not ? "NOT IN" : "IN"), rhs],
|
|
@@ -9860,7 +10110,8 @@ function fieldReadonly(op, typeName, field) {
|
|
|
9860
10110
|
function boundSQL(v, ctx) {
|
|
9861
10111
|
if (v === void 0) return void 0;
|
|
9862
10112
|
if (typeof v === "number") return SqlText.raw(String(v));
|
|
9863
|
-
const
|
|
10113
|
+
const raw2 = Object.prototype.hasOwnProperty.call(ctx.params, v.name) ? ctx.params[v.name] : null;
|
|
10114
|
+
const value2 = raw2 !== null && typeof raw2 === "object" ? null : raw2;
|
|
9864
10115
|
return SqlText.param(value2);
|
|
9865
10116
|
}
|
|
9866
10117
|
|
package/package.json
CHANGED
|
@@ -1,51 +1,51 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@aeye/query",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Query - An LLM-friendly relational query language, runtime & SQL converter",
|
|
5
|
-
"type": "module",
|
|
6
|
-
"main": "dist/index.js",
|
|
7
|
-
"types": "dist/index.d.ts",
|
|
8
|
-
"exports": {
|
|
9
|
-
".": {
|
|
10
|
-
"source": "./src/index.ts",
|
|
11
|
-
"import": {
|
|
12
|
-
"types": "./dist/index.d.ts",
|
|
13
|
-
"default": "./dist/index.js"
|
|
14
|
-
},
|
|
15
|
-
"default": "./dist/index.js"
|
|
16
|
-
}
|
|
17
|
-
},
|
|
18
|
-
"scripts": {
|
|
19
|
-
"build": "tsup src/index.ts --format esm --dts",
|
|
20
|
-
"test": "vitest run",
|
|
21
|
-
"test:watch": "vitest",
|
|
22
|
-
"test:coverage": "vitest run --coverage",
|
|
23
|
-
"typecheck": "tsc --noEmit",
|
|
24
|
-
"examples": "tsx examples/examples.ts",
|
|
25
|
-
"cli": "tsx examples/cli.ts",
|
|
26
|
-
"integration": "tsx integration/run.ts",
|
|
27
|
-
"integration:check": "tsx integration/run.ts --check",
|
|
28
|
-
"clean": "rimraf dist"
|
|
29
|
-
},
|
|
30
|
-
"dependencies": {
|
|
31
|
-
"@aeye/core": "^0.3.9",
|
|
32
|
-
"zod": "^4.1.12"
|
|
33
|
-
},
|
|
34
|
-
"devDependencies": {
|
|
35
|
-
"@aeye/ai": "^0.3.9",
|
|
36
|
-
"@aeye/aws": "^0.3.9",
|
|
37
|
-
"@aeye/models": "^0.3.9",
|
|
38
|
-
"@aeye/openai": "^0.3.9",
|
|
39
|
-
"@aeye/openrouter": "^0.3.9",
|
|
40
|
-
"@vitest/coverage-v8": "^3.2.4",
|
|
41
|
-
"tsup": "^8.0.0",
|
|
42
|
-
"tsx": "^4.19.0",
|
|
43
|
-
"typescript": "^5.9.3",
|
|
44
|
-
"vitest": "^3.0.0"
|
|
45
|
-
},
|
|
46
|
-
"files": [
|
|
47
|
-
"dist",
|
|
48
|
-
"aeye-*.md"
|
|
49
|
-
],
|
|
50
|
-
"license": "GPL-3.0"
|
|
51
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@aeye/query",
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Query - An LLM-friendly relational query language, runtime & SQL converter",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"source": "./src/index.ts",
|
|
11
|
+
"import": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"default": "./dist/index.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "tsup src/index.ts --format esm --dts",
|
|
20
|
+
"test": "vitest run",
|
|
21
|
+
"test:watch": "vitest",
|
|
22
|
+
"test:coverage": "vitest run --coverage",
|
|
23
|
+
"typecheck": "tsc --noEmit",
|
|
24
|
+
"examples": "tsx examples/examples.ts",
|
|
25
|
+
"cli": "tsx examples/cli.ts",
|
|
26
|
+
"integration": "tsx integration/run.ts",
|
|
27
|
+
"integration:check": "tsx integration/run.ts --check",
|
|
28
|
+
"clean": "rimraf dist"
|
|
29
|
+
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"@aeye/core": "^0.3.9",
|
|
32
|
+
"zod": "^4.1.12"
|
|
33
|
+
},
|
|
34
|
+
"devDependencies": {
|
|
35
|
+
"@aeye/ai": "^0.3.9",
|
|
36
|
+
"@aeye/aws": "^0.3.9",
|
|
37
|
+
"@aeye/models": "^0.3.9",
|
|
38
|
+
"@aeye/openai": "^0.3.9",
|
|
39
|
+
"@aeye/openrouter": "^0.3.9",
|
|
40
|
+
"@vitest/coverage-v8": "^3.2.4",
|
|
41
|
+
"tsup": "^8.0.0",
|
|
42
|
+
"tsx": "^4.19.0",
|
|
43
|
+
"typescript": "^5.9.3",
|
|
44
|
+
"vitest": "^3.0.0"
|
|
45
|
+
},
|
|
46
|
+
"files": [
|
|
47
|
+
"dist",
|
|
48
|
+
"aeye-*.md"
|
|
49
|
+
],
|
|
50
|
+
"license": "GPL-3.0"
|
|
51
|
+
}
|