Tables & DDL
TableSpec is one shape for a table read from a database and for a table you want: columns with a portable type, nullability, defaults, a closed set of values, the primary key, foreign keys and unique sets.
import { type TableSpec } from '@aeye/query';
const customer: TableSpec = {
name: 'customer',
columns: [
{ name: 'id', type: { kind: 'uuid' }, nullable: false },
{ name: 'name', type: { kind: 'text' }, nullable: false },
],
primaryKey: ['id'],
foreignKeys: [],
unique: [],
};
const invoice: TableSpec = {
name: 'invoice',
columns: [
{ name: 'id', type: { kind: 'integer' }, nullable: false, generated: true },
{ name: 'customerId', type: { kind: 'uuid' }, nullable: false },
{ name: 'status', type: { kind: 'text' }, nullable: false, values: ['open', 'paid'] },
{ name: 'total', type: { kind: 'decimal', precision: 12, scale: 2 }, nullable: false },
{ name: 'createdAt', type: { kind: 'timestamp' }, nullable: false, default: { kind: 'now' } },
],
primaryKey: ['id'],
foreignKeys: [{ columns: ['customerId'], table: 'customer', references: ['id'] }],
unique: [],
};Column types are text, integer, decimal, float, bool, date, timestamp, uuid, json, bytes and other (a native spelling).
DDL
Each registered dialect has a ddl writer (the Postgres, SQLite and SQL Server ones are PostgresDdl, SqliteDdl and SqlServerDdl) that writes statements and reads native types and defaults back.
import { createRegistry } from '@aeye/query';
const ddl = createRegistry().dialect('postgres')!.ddl;
ddl.createTable(invoice).sql;
const wanted: TableSpec = { ...invoice, columns: [...invoice.columns, { name: 'note', type: { kind: 'text' }, nullable: true }] };
for (const step of ddl.alterTable(invoice, wanted)) {
console.log(step.summary, step.irreversible, step.sql);
}alterTable returns ordered steps so no constraint trips. Drops and narrowing changes are marked irreversible. SQLite rebuilds the table for anything beyond plain adds and drops. Renames aren't planned.
Query types and gin types
import { createRegistry, tableToQueryType, tableToGinType, ginTypeToTable } from '@aeye/query';
const tables = [customer, invoice];
const registry = createRegistry();
for (const table of tables) {
registry.registerType(registry.parseType(tableToQueryType(table, { tables })));
}
registry.finalize();
const row = tableToGinType(invoice); // the row as a gin `obj`
const back = ginTypeToTable('invoice', row, { current: invoice, primaryKey: ['id'] });Single-column foreign keys onto a key become relation fields. ginTypeToTable keeps the physical details of current that the type doesn't change.
Generated functions
tableFns lists every useful function a table's columns, keys and relations make possible. No model is involved, and the same tables always give the same list.
import { tableFns, queryArgProblems } from '@aeye/query';
const { fns, more, hash } = tableFns('invoice', tables); // ranked, 60 by default
const one = fns.find((fn) => fn.name === 'selectOne')!;
one.signature; // 'selectOne(id: num)'
one.query; // a checked QueryDef
queryArgProblems(one.args, {}); // ['id is required: give a value for it.']- CRUD:
create,update,remove,updateWhere,removeWhere,selectOne,selectPage. - Column helpers: counts per value, number statistics, counts per day, week or month,
exists,findOrCreate, children of a parent. - Derived fields: relation counts and sums, parent fields, ranks, percentiles and shares.
hash changes when the table or a related one does. Options are depth, cap and paging.
Any query as a function
The same helpers describe a stored query's arguments:
import { queryArgsType, queryArgProblems, withArgDefaults, signatureText, type QueryDef } from '@aeye/query';
const byStatus: QueryDef = {
kind: 'select',
fields: [{ expr: { kind: 'field-ref', source: 'invoice', field: 'id' } }],
from: { kind: 'type', type: 'invoice' },
where: [{ kind: 'comparison', op: '=', left: { kind: 'field-ref', source: 'invoice', field: 'status' }, right: { kind: 'param', name: 'status' } }],
};
const engine = new QueryEngine(registry);
const argsType = queryArgsType(engine.parameters(byStatus), { paging: { max: 100, page: 25 } });
signatureText('byStatus', argsType);
const errors = queryArgProblems(argsType, { status: 'open' });
const args = withArgDefaults(argsType, { status: 'open' });