Docs

Guide 05

Database

05. Database

Scrivener is the model layer. It never learns which database it's talking to.


The Query IR

The requirement: nobody thinks about PostgREST, SQL dialects, or which driver is configured. So the model layer can't be built on a driver's query builder, because every leaked quirk becomes application-visible.

The model and query builder produce a serializable QueryIR. The driver compiles it.

Revised after M0. The spike proved result parity on every expressible operation and failed the assumption on underdefinition. Everything a compiler would otherwise have to guess is now explicit (D25).

export type CompareOp = '=' | '!=' | '<' | '<=' | '>' | '>=' | 'like' | 'ilike'

export interface OrderTerm {
  column: string
  direction: 'asc' | 'desc'
  nulls?: 'first' | 'last'
}

export interface RelationLoad {
  /** Relation name as declared on the model. Keys the loaded rows in the result. */
  relation: string
  kind: 'belongsTo' | 'hasOne' | 'hasMany'
  /** Resolved by the model layer so drivers never introspect models. */
  table: string
  /** Column on the parent row. */
  localKey: string
  /** Column on the related table. */
  foreignKey: string
  select: string[] | '*'
  where: Predicate | null
  order: OrderTerm[]
  limit?: number
  /** Nested loads. Total depth is checked against the driver's maxRelationDepth. */
  relations: RelationLoad[]
}

export interface QueryIR {
  table: string
  mode: 'select' | 'count' | 'insert' | 'update' | 'delete' | 'upsert'
  select: string[] | '*'
  /** Entries compose with AND. */
  where: Predicate[]
  relations: RelationLoad[]
  order: OrderTerm[]
  limit?: number
  offset?: number
  values?: Record<string, unknown> | Record<string, unknown>[]
  returning?: string[] | '*'
  /**
   * Required when mode is 'upsert'. `update` names the columns overwritten on conflict;
   * `'*'` means every supplied value column not named in `conflict.columns`.
   */
  conflict?: { columns: [string, ...string[]]; update: [string, ...string[]] | '*' }
  /** Injected by the ward compiler, ANDed with `where`. Never author-supplied. */
  ward?: Predicate
}

export type Predicate =
  | { kind: 'const'; value: boolean }
  | { kind: 'compare'; column: string; op: CompareOp; value: unknown }
  | { kind: 'null'; column: string; negated: boolean }
  | { kind: 'in'; column: string; values: unknown[]; negated: boolean }
  | { kind: 'and'; predicates: Predicate[] }
  | { kind: 'or'; predicates: Predicate[] }
  | { kind: 'not'; predicate: Predicate }

Defined Semantics

These rules belong to the contract, so they don't vary by driver. Every compiler normalizes before emitting, and 2 drivers can never disagree about what an IR means:

  • where entries and the injected ward compose with AND
  • and: [] is const true and or: [] is const false. They're the identity elements, so machine-generated IR needs no special cases
  • in: [] matches nothing. Negated, it matches everything
  • not over const folds to the opposite const
  • A const false ward or where-set short-circuits. The driver returns an empty result (or affects zero rows) without a round trip
  • A const true compiles to nothing
  • Comparisons follow SQL three-valued logic. Client-side ward scoping evaluates the same way, which M0 verified against live RLS on adversarial null fixtures
  • upsert without conflict is invalid IR and gets rejected before it reaches a driver
  • Relation limit applies per parent row instead of to the combined related set

Count

count returns the number of rows matching where AND ward. It ignores these fields, which must be absent or empty:

  • select
  • relations
  • order
  • limit
  • offset

It exists so paginate() has a portable total. Drivers surface it as QueryResult.count.

Compiling the IR

Each driver compiles the IR its own way:

  • @avelonjs/supabase compiles it to PostgREST parameters
  • @avelonjs/postgres compiles it to parameterized SQL
  • a MySQL driver would compile it to MySQL

The model layer never learns which.

The IR is serializable on purpose. You can log it, snapshot-test it, and diff it. That's how you prove 2 drivers agree on the same query without a live database.


Capabilities That Matter

capabilities: {
  transactions: false,        // supabase: use rpc()
  rowSecurity: true,          // wards compile to RLS
  maxRelationDepth: 2,        // PostgREST embed limit
  fullTextSearch: false,
  upsert: true,
  returning: true,
  windowFunctions: false,
  jsonOperators: true,
}

Bailiff checks maxRelationDepth against every .with() chain in the codebase. Going past the configured driver's limit is a lint error at authoring time instead of an empty array at runtime.


Models

export class Post extends Model {
  static table = 'posts'
  static fillable = ['title', 'body']
  static casts = { published_at: 'datetime', meta: 'json' } as const
  static timestamps = true
  static softDeletes = true

  declare id: string
  declare title: string
  declare body: string
  declare user_id: string
  declare published_at: Date | null

  author() {
    return this.belongsTo(User, 'user_id')
  }
  comments() {
    return this.hasMany(Comment, 'post_id')
  }

  static published() {
    return this.query().whereNotNull('published_at')
  }
}

declare is required. An emitted class field would overwrite hydrated values during construction.

await Post.published().with('author').latest().paginate(15)
await Post.findOrFail(id)
await Post.query().where('user_id', user.id).where('views', '>', 100).get()
await post.update({ title })
await post.delete() // soft delete when enabled
await Post.withTrashed().where('id', id).first()

Eager loading issues a second query with a whereIn, never an N+1 loop. On drivers that support embeds it can collapse into 1 round trip. That's a driver decision the model layer doesn't see.


Model Lifecycle

Hooks dispatch on the same event bus as application events. That's what makes Observers ordinary listeners:

creating  created  updating  updated  saving  saved  deleting  deleted  restored

A creating listener returning false aborts the write. See 07-events.md.


Types

Bailiff's attribute-schema-match rule checks each model's fillable attributes against the table of the same name in database/types.ts. A column rename fails the build instead of production.

reeve schema:pull writes that file with an empty Database interface. It doesn't read the live schema yet, so declare the tables you want checked in the file by hand until it does.


Transactions

Transactions are a driver capability, surfaced by narrowing.

// avelon.config.ts
import { defineConfig } from '@avelonjs/core'
import { createPostgresDatabase } from '@avelonjs/postgres'
import { migrations } from './database/migrations'

export const database = createPostgresDatabase({ url: process.env.DATABASE_URL, migrations })

export default defineConfig({ name: 'shop', drivers: { database } })
// app/Actions/PlaceOrder.ts
import { database } from '@/avelon.config'

await database.transaction(async (tx) => {
  const order = await Order.create({ id: crypto.randomUUID(), total }, tx)
  await Payment.create({ id: crypto.randomUUID(), order_id: order.id }, tx)
})

// The Supabase driver declares transactions: false, so its type has no transaction().
// Multi-statement atomicity goes through a Postgres function:
await DB.rpc('create_order_with_payment', { total })

These accept the transaction as their last argument:

  • Model.create
  • save
  • update
  • delete
  • restore

Bailiff errors on hand-rolled "transaction" helpers that wrap sequential writes in a try/catch. That pattern reads as atomic and isn't.


Migrations

Migrations are driver-owned. The contract is:

  • plan
  • apply
  • rollback
  • status

reeve migrate is the same command whatever the driver.

Migration Shape

The Postgres, Neon, and Supabase drivers share one migration shape: { id, up: string[], down: string[] }.

  • Applied ids are recorded in an avelon_migrations table
  • Each migration's statements and its history row are applied in one batch

Adding a Migration

reeve make:migration does 2 things:

  • writes a timestamped migration
  • appends it to the migrations list in database/migrations/index.ts

Pass that list to the driver in avelon.config.ts. reeve migrate loads that file.

reeve make:migration create_posts_table
reeve migrate
reeve migrate:rollback
reeve migrate:fresh --seed
reeve migrate:status

Row Security

reeve ward:sync applies row-security policies through drivers that declare rowSecurity: true. Row security travels with the code instead of living in a dashboard nobody has read since setup. See 06-authorization.md.

A schema builder DSL is deferred. It hasn't been rejected. See D13.