Queries & Expressions
A query is a QueryDef and an expression is an ExprDef: JSON unions discriminated by kind that survive JSON.stringify.
Statement kinds
kind | Statement |
|---|---|
select | fields, from, joins, where, groupBy, having, order, limit, offset, distinct |
insert | into, rows or select, onConflict (fields, doNothing, update), returning |
update | type, set, joins, where, returning |
delete | from, joins, where, returning |
union, intersect, except | left, right, all, and set-level order, limit, offset |
cte | ctes and a final query |
expr | A single expression |
where and having are lists of conditions, ANDed together.
Sources and joins
Every source is referenced by its type name. from: { kind: 'type', type: 'user' } binds user, and field references use source: 'user'. Other sources are aliased (type, as), subquery (query, as) and function (function, args, as).
A join crosses one relation field. The relation key supplies the ON, so you never write it:
import { type SelectDef } from '@aeye/query';
const ordersByUser: SelectDef = {
kind: 'select',
fields: [
{ expr: { kind: 'field-ref', source: 'user', field: 'id' } },
{ expr: { kind: 'field-ref', source: 'order', field: 'total' } },
],
from: { kind: 'type', type: 'user' },
joins: [{ on: { kind: 'relation', source: 'user', field: 'orders', as: 'order' }, joinType: 'inner' }],
};asis required: it names the joined rows.joinTypedefaults toleft.andadds a condition to the synthesized key.- Longer paths are chains of single-hop joins.
oncan also be atype,aliased,subqueryorfunctionsource, withandas the wholeON.- Use
aliased(or a differentas) for self-joins. Two sources under one name are asource.duplicateerror. A self-referentialupdateordeletethat needs two instances of its target isn't supported yet.
Expression kinds
| Group | Kinds |
|---|---|
| Leaves | literal, field-ref, param |
| Operators | binary, unary, comparison, logical |
| Predicates | in, between, is-null, exists, array-op |
| Branching | case |
| Calls | function-call, aggregate, window, tabular-function-call, operator |
| Search | semantic, text-search, text-score |
| Embedding | subquery, filters |
| Position-only | output (groupBy / having / order), excluded (onConflict.update), sorter (order), arg |
Calls take named arguments: { kind: 'function-call', function: 'initials', args: { value: expr } }. count(*) is an aggregate with empty args.
Output references
groupBy, order and having can name a selected output instead of repeating its expression:
const revenuePerUser: SelectDef = {
kind: 'select',
fields: [
{ expr: { kind: 'field-ref', source: 'order', field: 'userId' }, as: 'userId' },
{ expr: { kind: 'aggregate', function: 'sum', args: { value: { kind: 'field-ref', source: 'order', field: 'total' } } }, as: 'revenue' },
],
from: { kind: 'type', type: 'order' },
groupBy: [{ kind: 'output', name: 'userId' }],
having: [{ kind: 'comparison', op: '>', left: { kind: 'output', name: 'revenue' }, right: { kind: 'literal', value: 100 } }],
order: [{ expr: { kind: 'output', name: 'revenue' }, dir: 'desc' }],
};The e.* builder
e has a function for each expression, returning a real Expr instance. .toJSON() gives the wire ExprDef. Each is also a named export.
import { e } from '@aeye/query';
const condition = e.and(
e.eq(e.ref('order', 'status'), e.value('paid')),
e.gt(e.ref('order', 'total'), e.value(100)),
);
const paid: SelectDef = {
kind: 'select',
fields: [{ expr: e.ref('order', 'id').toJSON() }],
from: { kind: 'type', type: 'order' },
where: [condition.toJSON()],
};
// A built expression also runs and converts on its own.
const value = await engine.evaluateExpr(condition, { order: { status: 'paid', total: 250 } });
const { sql, params } = engine.exprToSQL(condition, 'postgres');Writes
import { type InsertDef } from '@aeye/query';
const upsert: InsertDef = {
kind: 'insert',
into: 'user',
rows: [{ id: 1, name: 'Ada' }],
onConflict: { fields: ['id'], update: { name: { kind: 'excluded', field: 'name' } } },
returning: [{ expr: { kind: 'field-ref', source: 'user', field: 'id' } }],
};A row or set value is either a plain value or an expression (an object with a string kind). Which types and fields may be written is declared on the model.
CTEs
A CTE entry is { name, query }, or recursive: { name, base, recursive }, where recursive reads the entry's own rows until nothing new appears. maxCteIterations caps the runtime.
Validation
const problems = engine.validateQuery(revenuePerUser);
if (problems.hasErrors) {
for (const p of problems.list) console.log(p.code, p.path.join('.'), p.message);
}engine.parseQuery(def) gives a runnable Query; every engine method also accepts the JSON. See diagnostics.