Skip to content

Queries & Expressions ​

A query is a QueryDef and an expression is an ExprDef: JSON unions discriminated by kind that survive JSON.stringify.

Statement kinds ​

kindStatement
selectfields, from, joins, where, groupBy, having, order, limit, offset, distinct
insertinto, rows or select, onConflict (fields, doNothing, update), returning
updatetype, set, joins, where, returning
deletefrom, joins, where, returning
union, intersect, exceptleft, right, all, and set-level order, limit, offset
ctectes and a final query
exprA 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:

typescript
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' }],
};
  • as is required: it names the joined rows.
  • joinType defaults to left. and adds a condition to the synthesized key.
  • Longer paths are chains of single-hop joins.
  • on can also be a type, aliased, subquery or function source, with and as the whole ON.
  • Use aliased (or a different as) for self-joins. Two sources under one name are a source.duplicate error. A self-referential update or delete that needs two instances of its target isn't supported yet.

Expression kinds ​

GroupKinds
Leavesliteral, field-ref, param
Operatorsbinary, unary, comparison, logical
Predicatesin, between, is-null, exists, array-op
Branchingcase
Callsfunction-call, aggregate, window, tabular-function-call, operator
Searchsemantic, text-search, text-score
Embeddingsubquery, filters
Position-onlyoutput (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:

typescript
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.

typescript
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 ​

typescript
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 ​

typescript
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.

Released under the GPL-3.0 License.