Skip to content

Functions & Operators ​

The built-in library ​

createRegistry() registers a library of scalar, tabular, aggregate and window functions. Names are camelCase.

GroupExamples
Stringlower, upper, trim, concat, substring, replace, padLeft, splitPart
Mathabs, round, ceil, floor, power, sqrt, log
Conditionalcoalesce, nullif, iif, greatest, least
Date and timenow, currentDate, year, dateTrunc, dateAdd, dateDiff, dateFormat, age
Array (Postgres)arrayLength, arrayContains, arrayAppend, arraySlice, stringToArray
Aggregatecount, sum, avg, min, max, stddev, stringAgg, arrayAgg, countIf, boolAnd
WindowrowNumber, rank, denseRank, lag, lead, firstValue, lastValue, ntile
typescript
import { createRegistry, QueryEngine, describeFunctions } from '@aeye/query';

const registry = createRegistry();
registry.functionList();                    // every definition
describeFunctions(new QueryEngine(registry)); // the listing a model reads

Some builtins degrade on dialects without them. The full SQL table is in the package README.

Your own functions ​

Declare the signature (plain JSON), then register how it runs in memory.

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

registry.registerFunction({
  name: 'initials', shape: 'scalar',
  params: [{ name: 'value', type: { kind: 'text' } }],
  output: { kind: 'text' },
  instructions: 'The first letter of each word.',
});
registry.registerFunctionRun('initials', {
  shape: 'scalar',
  run: (args) => Value.of(args.value!.toText().split(/\s+/).map((word) => word[0]).join('')),
});

// { kind: 'function-call', function: 'initials', args: { value: <expr> } }
shaperun receivesExpression kind
scalar(args, ctx), returns a valuefunction-call
tabular(args, ctx), returns rowstabular-function-call, or a function source
aggregate(rows, ctx) over a groupaggregate
window(partition, index, ctx) per rowwindow

Operators ​

Infix SQL operators (&&, <->, @>) can't be functions. Register an operator with a SQL template per dialect, used through the operator expression.

typescript
registry.registerOperator({
  name: '&&',
  operands: [
    { name: 'left', type: { kind: 'json' } },
    { name: 'right', type: { kind: 'json' } },
  ],
  output: { kind: 'bool' },
  instructions: 'Bounding-box overlap between two geometries.',
  emit: { postgres: '({left} && {right})' }, // must be wrapped in parentheses
});

// { kind: 'operator', op: '&&', args: { left: <expr>, right: <expr> } }

A dialect with no template is refused (operator.unsupported-dialect), and so is an in-memory run without registerOperatorRun (operator.no-run).

Field type refinements ​

A refinement is a registered name over a builtin field type: { kind: 'text', as: 'uuid' }. It carries narrowing options, SQL cast targets and instructions for the model. Register refinements before parsing any types.

typescript
const catalog = createRegistry();

catalog.registerFieldType({
  name: 'uuid',
  base: 'text',
  instructions: 'A UUID, lower-case and hyphenated.',
  options: { minLength: 36, maxLength: 36, casing: 'exact' },
  sql: { postgres: 'uuid' },
});

// then on a field: { name: 'id', type: { kind: 'text', as: 'uuid' } }

A declaration can also set:

PropertyPurpose
ownOptionsNew options a column supplies in with (such as a geometry's srid).
castHow a bound document value is cast, on json and array bases.
compareWhich comparisons mean anything: equality, ordering, textMatch.
comparableWithOther refinements it can be compared with.
avgBytesSize used by cost estimates.

Code that can't be stored as JSON, a stricter value schema (zod) or an in-memory compareValues, is registered with registerFieldTypeImpl(name, impl).

Testing a declaration ​

@aeye/query/conformance runs the property tests the builtins pass against your declaration.

typescript
import { checkFieldType } from '@aeye/query/conformance';

const report = checkFieldType({
  name: 'slug', base: 'text',
  instructions: 'A lower-case, hyphenated URL slug.',
  options: { casing: 'exact' },
});
report.problems; // empty when it holds up

It also exports checkOperator, checkLatticeLaws and differentialCheck, which compares the in-memory runtime against a real database.

Released under the GPL-3.0 License.