Skip to content

Running & SQL ​

Run ​

typescript
const result = await engine.run(query, { includeTotal: true });
result.rows;    // output rows (objects)
result.fields;  // output fields: name, resolved type, aggregate information
result.total;   // rows before limit/offset, with includeTotal

const positional = await engine.run(query, undefined, { rows: 'array' });

Rows come from the executors you give the engine. arrayExecutor(rows) serves an array; a TypeExecutor is { load(ctx), validate?(query, problems) }.

OptionDescription
paramsValues for the query's named parameters.
filtersOne boolean expression per source, for filters placeholders.
sort{ sort, dir? } entries for a sorter placeholder.
rlsAn RlsProvider adding row predicates per type.
includeTotalReport the pre-limit count.
embedder, embeddingsQuery embeddings for semantic terms.
maxCteIterationsCap on recursive CTEs.

includeTotal applies to the entry query only. A set operation reports no total; wrap it in a select over a subquery source to page and count it.

SQL ​

typescript
const { sql, params: bound } = engine.toSQL(query, 'postgres');

Parameters are bound, never interpolated. toSQL takes the same params, filters, sort, rls and includeTotal options as run, and is synchronous.

DialectPlaceholdersNotes
base?Portable ANSI. Array containment is refused; lateral joins and similarity degrade.
postgres$1, $2Full coverage, including arrays, LATERAL, tsvector and pgvector.
sqlite?Booleans bound as 1 / 0. Lateral joins are refused.
sqlserver@p1, @p2[x] quoting, OFFSET … FETCH. Doesn't cover a predicate projected as a column, or RETURNING.

Parameters ​

A param expression takes its type from how it is used.

typescript
import { type QueryDef } from '@aeye/query';

const byStatus: QueryDef = {
  kind: 'select',
  fields: [{ expr: { kind: 'field-ref', source: 'order', field: 'id' } }],
  from: { kind: 'type', type: 'order' },
  where: [{
    kind: 'comparison', op: '=',
    left: { kind: 'field-ref', source: 'order', field: 'status' },
    right: { kind: 'param', name: 'status' },
  }],
};

engine.parameters(byStatus);                        // each param: uses, merged type, conflict
const check = engine.checkParams(byStatus, { status: 'paid' });
if (!check.hasErrors) await engine.run(byStatus, { params: { status: 'paid' } });

A param used in several places gets the most specific type compatible with all of them; uses with none are a param.conflict. run and toSQL don't validate values: call checkParams, or pass { params } as the fourth argument of validateQuery.

Filters ​

A filters expression is a placeholder in the query ({ kind: 'filters', source, fields? }). The predicate comes from you at run time and is TRUE when absent.

typescript
import { e } from '@aeye/query';

const listed: QueryDef = {
  kind: 'select',
  fields: [{ expr: { kind: 'field-ref', source: 'order', field: 'id' } }],
  from: { kind: 'type', type: 'order' },
  where: [{ kind: 'filters', source: 'order', fields: ['status', 'total'] }],
};

engine.parseQuery(listed).filters(engine); // the sources and fields a UI can offer
await engine.run(listed, { filters: { order: e.gt(e.ref('order', 'total'), e.value(100)) } });

Pagination ​

autoPaginate adds limit and offset parameters, so paging is a matter of supplying values.

typescript
import { autoPaginate, canAutoPaginate } from '@aeye/query';

if (canAutoPaginate(byStatus)) {
  const paged = autoPaginate(byStatus);
  await engine.run(paged, { params: { status: 'paid', limit: 10, offset: 0 }, includeTotal: true });
}

It applies to select, set operations and cte (through final). Other statements throw paginate.unsupported-kind.

Drill-down ​

drillDownInto builds the query for the rows behind one row of an aggregate.

typescript
import { drillDownInto } from '@aeye/query';

const totals = {
  kind: 'select' as const,
  fields: [
    { expr: { kind: 'field-ref' as const, source: 'order', field: 'status' } },
    { expr: { kind: 'aggregate' as const, function: 'count', args: {} }, as: 'orders' },
  ],
  from: { kind: 'type' as const, type: 'order' },
  groupBy: [{ kind: 'field-ref' as const, source: 'order', field: 'status' }],
};

const { rows: groups } = await engine.run(totals);
const into = drillDownInto(totals, groups[0]!, engine);
if ('query' in into) await engine.run(into.query, { params: into.params });

drillDown(query, engine) returns the parameterized query without a row. Both return an error (Problems) when the query can't be drilled.

Cost ​

Estimates come from each type's count, bytes, indexes and change rates.

typescript
engine.cost(query);            // { rows, bytes }: work to produce the result
engine.outputCost(query);      // { rows, bytes }: size of the result
engine.affected(query);        // rows a write changes
engine.references(query);      // types, fields and functions read
engine.changeInterval(query);  // ms until the data could change (0 always, -1 never)

// Reject over-budget queries during validation
const budget = engine.validateQuery(query, undefined, { maxRows: 1000, maxBytes: 1_000_000 });

Diagnostics ​

Validation returns Problems: each has a structural path into the JSON, a stable code, a message and a severity. For a query as JSON, parseQueryRequest runs the structural and semantic checks and renders a compiler-style report:

typescript
import { parseQueryRequest } from '@aeye/query';

const { query: parsed, problems, report } = parseQueryRequest(engine, { query: byStatus });
if (!parsed) console.log(report);

Unknown names carry a "did you mean" suggestion.

Released under the GPL-3.0 License.