Skip to content

Backing & Security ​

The model sees a flat list of fields. A TypeBacking is developer code registered beside a type that says what is behind it. It applies the same way in engine.run and engine.toSQL, and never appears in the schema the model is given.

typescript
import { createRegistry, QueryEngine, e, type TypeDef, type TypeBacking } from '@aeye/query';

const projectDef: TypeDef = {
  name: 'project',
  fields: [
    { name: 'id', type: { kind: 'number', whole: true } },
    { name: 'status', type: { kind: 'text' } },
    { name: 'secret', type: { kind: 'text' }, nullable: true },
  ],
  count: 500,
};

const currentOrg = 7;

const backing: TypeBacking = {
  name: 'projects', // the real table: FROM "projects" AS "project"

  // Row security: `orgId` exists only in the database.
  access: { expr: (alias) => e.eq(e.ref(alias, 'orgId'), e.value(currentOrg)) },

  fields: {
    // Field security: NULL unless the project is active.
    secret: { access: { expr: (alias) => e.eq(e.ref(alias, 'status'), e.value('active')) } },
  },
};

const registry = createRegistry();
registry.registerType(registry.parseType(projectDef), backing);
const engine = new QueryEngine(registry); // or new QueryEngine(registry, { backings: { project: backing } })

Every factory is handed the alias the type is bound under. Use it for each reference, never the type name, so self-joins and aliases resolve.

Each backing hook has an expr path used by both modes, and sql / run overrides for one of them.

Security ​

BackingEffect
TypeBacking.accessRow filter on every occurrence of the type. false means no rows.
FieldBacking.accessPer field: NULL when the predicate is false.
run / toSQL option rlsAn RlsProvider (predicateFor(typeName, alias)) for predicates that vary per call. Combined with access.

Computed and remapped fields ​

  • FieldBacking.name reads a differently named column.
  • FieldBacking.compute supplies the value: { expr }, or { sql, run }. A computed field is not insertable or updatable unless you say so.
  • FieldBacking.default (a Value or a factory) makes a field optional on insert. The runtime fills it; in SQL the column is left to the database's default.

Joins ​

TypeBacking.joins declares named, hidden joins. A field opts in with joins: [name], and the join is planned once per query however many fields use it. A join is a relation ({ kind: 'relation', source, relation }) or a lateral correlated sub-select. Read its columns through joinAlias(alias, name).

typescript
import { joinAlias, type TypeBacking } from '@aeye/query';

const withOwner: TypeBacking = {
  joins: {
    owner: { expr: (alias) => ({ kind: 'relation', source: alias, relation: 'owner' }) },
  },
  fields: {
    ownerName: { joins: ['owner'], compute: { expr: (alias) => e.ref(joinAlias(alias, 'owner'), 'name') } },
  },
};

A relation field's own ON clause can use physical columns the model never sees: FieldBacking.relation: { keys: [{ local: 'user_id', foreign: 'id' }] }, or a custom on.

Default conditions and ordering ​

defaultConditions is a soft scope a query can lift, such as hiding archived rows until the query filters on archivedAt. Row security is never lifted.

typescript
const archived: TypeBacking = {
  defaultConditions: [{ where: { expr: (alias) => e.isNull(e.ref(alias, 'archivedAt')) } }],
  // The ORDER BY a select gets when it names none.
  defaultOrder: { by: [{ by: { expr: (alias) => e.ref(alias, 'createdAt') }, dir: 'desc' }] },
};

Each condition takes where, and optionally without (the fields whose use in where, having or a join condition lifts it; derived from where.expr when omitted), ops (default select, update, delete) and description. defaultOrder.applyTo is 'result' (default), 'paginated' or 'all', and ordering is skipped for aggregated and distinct selects.

Write permissions ​

Declared on the definitions, and honoured by both validation and the model's schema, so the model is never offered a write the engine would refuse.

  • TypeDef.insertable / updatable / deletable
  • FieldDef.insertable / updatable
  • FieldDef.exprs (only / not) restricts which expressions may use a field.

A field is required on insert when it is insertable, non-nullable, without a default and not computed.

Search and similarity ​

Three expressions search a bound source, optionally narrowed to a field:

kindResultNeeds
text-searchbooleana type flagged search, or a searchable text field
text-scorenumber (relevance)the same
semanticnumber (similarity)a type or text field flagged semantic, and an embedding

TypeBacking.search / semantic (or the field's) point them at precomputed columns:

typescript
const searchable: TypeBacking = {
  search: { vectorField: 'search_tsv', language: 'english' }, // a tsvector column
  semantic: { vectorField: 'embedding' },                     // a pgvector column
};

toSQL never calls an embedder. For plain-text semantic terms, extract, embed, then convert:

typescript
const terms = engine.semanticTexts(query);
const embeddings = new Map<string, number[]>();
for (const text of terms) embeddings.set(text, await embed(text));
const { sql, params } = engine.toSQL(query, 'postgres', { embeddings });

For run, pass the same embeddings, or an embedder ({ embed(text) }) to the engine or the call. On the base dialect, full-text search falls back to LIKE and similarity to 0.

Released under the GPL-3.0 License.