# Repositories & Queries

## Introduction

You read and write data with Kysely's query builder, typed by your app's tables. A **repository** is an optional class for one
table that keeps its queries in one place: rows go in, rows come out, and nothing happens that you did not call. There is no
lazy loading and no saving behind your back.

```ts title="modules/notes/NoteRepository.ts"
import { Repository } from '@marmeon/database';

export class NoteRepository extends Repository<'notes'> {
  static table = 'notes' as const;

  latestOf(userId: number) {
    return this.query().selectAll().where('user_id', '=', userId).orderBy('updated_at', 'desc').limit(10).execute();
  }
}
```

A controller asks for `NoteRepository` in its constructor and calls `latestOf()`, `find()` or `insert()`. Every name in a query
is checked against the table's type, and the result is typed by what the query selects.

## Table types

The types of your tables come from your **migrations**, never from the state of a database. `marmeon db:types` reads the plan of
every migration (what `up()` declared with `schema.create()`, `alter()`, `rename()` and `drop()`) and writes
`bootstrap/database.d.ts`. It runs nothing and connects to nothing: no database, no permission to create one, the same file on
SQLite and Postgres. The file is committed, so a type check needs no database either.

The file is also the one place that shows the **current** definition of every table, where the migrations show only the history.
Each table carries a comment with what a query needs to know: the module that owns it and whether it is exposed to the others, soft
deletes and timestamps, the primary key, unique column sets, and foreign keys with their `onDelete` and the name of the inverse
relation. Secret columns are typed `Secret<…>`. Tables and relations are sorted and columns keep the order of the migrations, so a change to one table changes only its
lines.

Only what the blueprint made is in the file. A table or column that raw SQL (`schema.raw()`) makes is not: Marmeon does not read SQL,
so it has no type, no secret column and no marks. Create it with `schema.create()`, or type it in your code with Kysely's
`withTables<…>()` on the app's `Database` or, read-only, on a module's (see [Module boundaries](#module-boundaries)). A migration that changes such a table with the blueprint (`schema.alter()` on a table `schema.raw()` made) stops
`db:types` with an error naming the migration.

`marmeon migrate` and `migrate:fresh` write the file for you when migrations ran, in development only. In production, staging and
tests the committed file is final, and the app's directory may not even be writable. `--no-types` skips it in development too.
In CI, `marmeon db:types --check` fails when a migration or a module's `exposes` changed and the file was not written again:

```text
bootstrap/database.d.ts is out of date — a migration or a module's `exposes` may have changed. Run: marmeon db:types
```

The file's third line, `// @marmeon-format 3`, names its format. A file without it, or with an older number, was generated by another version of Marmeon: `--check` says so instead of "out of date", and you run `marmeon db:types` and commit the file. A file with a newer number comes from a newer Marmeon: `--check` fails with "update @marmeon/*", and no command writes over the file.

The file fills the `Tables` interface, `Relations` with the relations of the foreign keys, and `PrimaryKeys` with the primary key of
each table: the column's name, or for a composite key the list of its columns. A table without a primary key has no entry.
`PrimaryKeyOf<'notes'>` is the type of that column, and `never` for a table without a single-column key, so a repository method
that takes a key refuses such a table already in the types.

Tables you type by hand (`withTables<…>()`, or a database another tool manages) have no entry until you add one. Declare their
keys the same way, in any file the type check includes:

```ts title="bootstrap/keys.d.ts"
declare module '@marmeon/database' {
  interface PrimaryKeys {
    orders: 'id';
  }
}
```

```ts
interface PrimaryKeys {
  notes: 'id';
  tags: 'slug';
  role_user: readonly ['role_id', 'user_id'];
}
```

Views are not in it: `db:types`
reads tables only, on SQLite and Postgres. Three helpers turn a table into the row types you write code with:

```ts title="modules/notes/types.ts"
import type { NewRow, Row, RowUpdate } from '@marmeon/database';

export type Note = Row<'notes'>; // a row as read
export type NewNote = NewRow<'notes'>; // what an insert takes
export type NoteChanges = RowUpdate<'notes'>; // what an update takes
```

Some columns have types of their own:

| Type | Column | Read as | Written as |
| --- | --- | --- | --- |
| `Generated<T>` | An id, or a column with a default | always there | optional |
| `Timestamp` | `timestamp()` | an ISO-8601 string in UTC | a string or a `Date` |
| `Decimal` | `decimal()` | a string such as `'12.50'`, so no precision is lost | a string or a number |
| `JsonColumn<K>` | `json()` | the parsed value, as [you declare it](#a-json-columns-type) | `JSON.stringify(value)` |
| `Secret<T>` | `.secret()` | left out of `Row<…>` | like any column |

A JSON column takes a string on purpose: Postgres would store an array that is not stringified as one of its own arrays.
`db:types` warns about a column type it cannot map, which is then typed as `unknown`, and about a table that no module's migration
created.

### A JSON column's type

`db:types` writes `JsonColumn<'events.title'>` for a `json()` column: its key is the table and the column. Without more, a read
gives `Json`, and you narrow it at every place that reads it. Say once what the value is, and every read has that type, in
`Row<'events'>`, in a select and in a repository's finders. Declare it in the module that owns the table, under that key:

```ts title="modules/events/database.ts"
import type { LocalizedText } from './types.ts';

declare module '@marmeon/database' {
  interface JsonTypes {
    'events.title': LocalizedText;
    'events.tags': readonly string[];
  }
}
```

The declaration is merged, so the keys are flat and one line each. Write the column as before, as text:
`insert({ title: JSON.stringify(title) })`. The type is for reading: the column still takes a string, and `JSON.stringify(value)` is
the one place where a value becomes text. A declared type that is no JSON (a `Date`, a function, a `bigint`, `unknown`, a required field that
may be `undefined`) reads as a message that names the key, such as `'events.starts' in JsonTypes is not JSON`. `unknown` is no JSON: type an open part as `Json`, such as `Record<string, Json>`. A misspelled key
declares nothing: the column stays `Json`. Interfaces, optional fields and `readonly` arrays are JSON.

The type is a promise of your app, and the database does not keep it. Nothing checks the shape of a value, neither when it is read
(the driver parses the text, and a row written by raw SQL or an older version reads as it is) nor when it is written (Postgres
refuses text that is not JSON, SQLite does not even do that). A value that comes from a request is therefore checked with a schema
before it is written, as the [validation](validation.md) of the route does it; the declared type does not replace that check.

## Writing queries

`Database` is the default connection, typed by `Tables`. Inject it and use Kysely's builder:

```ts title="modules/notes/NoteSearch.ts"
import { Database, sql } from '@marmeon/database';

export class NoteSearch {
  readonly #db: Database;

  constructor(db: Database) {
    this.#db = db;
  }

  search(userId: number, term: string) {
    const pattern = `%${term.toLowerCase().replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
    return this.#db
      .selectFrom('notes')
      .select(['id', 'title'])
      .where('user_id', '=', userId)
      .where(sql<boolean>`lower(title) like ${pattern} escape '\\'`)
      .orderBy('title')
      .orderBy('id')
      .execute();
  }
}
```

`sql` is Kysely's template, so your app needs no import of Kysely itself. A value in the template, such as `${pattern}`, is sent
as a parameter and never becomes part of the SQL text. `sql.raw()` is the exception: it puts a string into the SQL as it is, so
never give it input. `marmeon check` warns about `sql.raw()` and `sql.lit()` with an argument that is not a literal ([raw SQL](check.md#raw-sql)).

The builder's types are exported under Marmeon's names: `Connection<DB>` is a connection's builder, `Transaction<DB>` the builder inside a
transaction and `SelectQuery<DB, TB, O>` a select that you go on with. `ColumnReference<DB, TB>` is a column as a query names it
(`'name'` or `'users.name'`), and `ReferencedType<DB, TB, R>` the type a query reads from it. A table's row is `Row<'notes'>`, `NewRow<'notes'>` and
`RowUpdate<'notes'>`, named by the table in `Tables`. A table that is not in `Tables`, such as a package's own, takes its type
instead: `RowOf<NoteTable>`, `NewRowOf<NoteTable>` and `RowUpdateOf<NoteTable>`.

Kysely's own documentation covers the builder: joins, subqueries, `onConflict`, `returning` and the rest. What Marmeon adds is
on this page.

> [!WARNING]
> Secret columns, such as the password hash, are left out of every `selectAll()` and `returningAll()` of the query builder, and
> a query reads one only with `secret()`. For a table the migrations created, those two name the columns the migrations know, so a
> column that raw SQL or a newer migration added is not in the result until the query names it. Raw SQL is not checked: `` sql`select * from users` `` returns the hash. The
> [migrations](migrations.md#secret-columns) page explains secret columns.

## Repositories

### Defining a repository

A repository extends `Repository<'table'>` and names its table again as a value, `static table = 'notes' as const`, because types
do not exist when the app runs. Without it, building the repository throws: `NoteRepository needs its table as a runtime value:
static table = '…' as const;`. Other statics change its behaviour:

| Static | Default | Effect |
| --- | --- | --- |
| `table` | required | The table, as a runtime value. |
| `connection` | `default` | Another connection. See [another connection](#another-connection). |
| `routeKey` | the primary key | The column a route parameter is looked up in. |
| `routeKeyPattern` | by the column: digits for an integer, a UUID for a `uuid`, at most 255 characters for the rest | What a route parameter must look like before it is looked up. |

A repository takes its key from the table's primary key, not from a column named `id`: `find('welcome')` on a table whose key is
`slug` works. A table without a primary key, or with a composite one, has no key a single value could name: `find()`, `update()`,
`delete()`, the route binding and the other methods that take a key throw a `TypeError` (`role_user has no single-column primary
key — use query()`), and the types refuse them. Such a table is read and written with `query()`. A table that raw SQL made is not known to a connection Marmeon migrates, so it counts as one without a key.

Timestamps and soft deletes follow the table's migration. When it calls `timestamps()`, `insert()`,
`insertMany()` and a [relation's](#writing-through-relations) `create()` and `createMany()` set `created_at` and `updated_at` (and `attach()` and `sync()` those of a pivot with `timestamps()`), and `update()` sets `updated_at`, all from the app's clock. When it calls `softDeletes()`, `delete()` sets `deleted_at`, and every read leaves deleted rows out. The
[migrations](migrations.md#timestamps-and-soft-deletes) page explains the marks.

`marmeon make:repository Note --module=notes` writes that class for `notes` (`--table` names another table) and registers nothing.
The table has to be in your app's generated types, so write its migration and run `marmeon migrate` and `marmeon db:types` first.

A repository is an ordinary class, built by the [container](container.md#binding-services). It holds nothing but its connection,
so register it once in your module's provider: `container.singleton(NoteRepository)`. Its constructor takes `Connections` and
nothing else, which is what lets [`using(trx)`](transactions.md#transactions-you-control-yourself) rebuild it for another
transaction. Give other dependencies to the service that uses the repository.

### Reading

| Method | Returns |
| --- | --- |
| `query()` | A Kysely select on the table, to go on with `select()`, `where()` and the rest. Soft-deleted rows are left out. |
| `find(id)` | The row with this primary key, or `undefined`. |
| `findByRouteKey(value)` | The row whose `routeKey` column holds the value, as a route binding finds it, for lookups outside of routes. `undefined` when there is none, or when the value cannot be a key. |
| `findOrFail(id, { with })` | The row and the relations `with` lists, or a 404 (`RecordNotFoundError`) that does not say what was looked up. |
| `findBy(column, value)` | The first row whose column holds the value, or `undefined`. |
| `firstWhere(values)` | The first row that holds every value, `{ author_id: 1, featured: true }`, or `undefined`. |
| `pluck(column)` | One column of every row, as a list. |
| `chunk(size, query?)` | Every row, in batches of `size`, for a `for await` loop. |
| `exists(id)` | Whether the row is there. |
| `count()` | How many rows there are. |
| `paginate(query, ctx.query)` | One page and the total. See [pagination](pagination.md#pages-by-number). |

Every one of them leaves soft-deleted rows out and never returns a secret column. A finder cannot name a secret column at all:
`pluck('password')` is a compile error, and refused when the query runs. A key of `findBy()` or `firstWhere()` that is not a
column of the table, or is a secret one, is refused before the query, also when it got past the types. `findBy()` and
`firstWhere()` find a NULL with `null`. A value that is `undefined`, such as a field a request did not send, is refused, because a
condition without a value would match any row. Which row is "first" is up to the database unless the column is unique; order a
`query()` yourself when it matters.

On a table with a [UUID key](migrations.md#uuid-keys), `find()`, `findOrFail()`, `exists()`, `update()`, `tryUpdate()`, `delete()`,
`forceDelete()`, `restore()`, `relation()` and the route binding check the format of the key first. A value that is no UUID
finds nothing, without a query to the database: Postgres would answer a malformed UUID with an error, and a typo in a URL
would become a 500. A UUID in capitals finds the row all the same, because it is compared in lower case, as it is stored: on SQLite, which compares
text as it is, store UUIDs in lower case (an import of upper-case ones would not be found). The
same holds for a `routeKey` that names a `uuid` column, `static routeKey = 'public_id'`.

`findBy()` and `firstWhere()` do not check the format: on a `uuid` column they throw on Postgres (`22P02`) when given a value that is
no UUID. For input that was not checked, a request's parameter say, use `findByRouteKey()`.

`findOrFail(id, { with: ['author', 'tags'] })` loads the [relations](#relations) into the same query, as `with()` does, and the
row's type has them: `RowWith<'notes', 'author' | 'tags'>` names it, for example as the prop type of a page. `chunk()` reads the rows by their primary key, each batch after the last one it read, one query per batch. Rows removed
during the loop do not make it skip others. Rows added meanwhile come at the end or, when another transaction commits them later
with a lower key, not at all. Its callback narrows what it reads:

```ts
for await (const users of this.#users.chunk(500, (query) => query.where('email_verified_at', 'is', null).with('profile_links'))) {
  for (const user of users) await this.#reminders.send(user, user.profile_links);
}
```

The callback may add conditions and relations. It must keep `id` among the columns, and an `orderBy()` in it is refused: the
batches go by `id`.

`query().withTrashed()` keeps the soft-deleted rows, and so does a relation that calls it in its callback. The
[relations](#soft-deleted-rows) section shows both.

`this.query()` and `this.db` are there for your own methods. `this.db` is the whole connection, for statements on another table or
an `insertInto(…).onConflict(…)`.

### Writing

| Method | Returns |
| --- | --- |
| `insert(values)` | The row as stored, with its id and defaults. Secret columns are not in it. |
| `update(id, values)` | The row as stored, without its secret columns, or `undefined` when there is none. With timestamps, it sets `updated_at` to the app's time. |
| `tryInsert(values)` | `ok(row)`, or an `err` of kind `duplicate` when a unique index already holds the values. Its `columns` name that index's columns. |
| `tryUpdate(id, values)` | `ok(row)`, or an `err` of kind `duplicate` when a unique index holds the new values, or `missing` when there is no row. A `duplicate` has `columns` too. |
| `insertMany(rows)` | The number of rows inserted. Throws on a unique violation, like `insert()`, with none of the rows written. With `{ returning: ['id', 'email'] }`, the rows instead, holding those columns. |
| `tryInsertMany(rows)` | `ok(count)`, or an `err` of kind `duplicate` when a unique index already holds a value of any row, with `columns` like `tryInsert()`. Takes `returning` too. |
| `insertMissing(rows, { on })` | The number of rows inserted: those whose `on` columns the table does not hold yet. The others are left alone. With `returning`, the inserted rows. |
| `delete(id)` | Whether there was a row. With soft deletes, it sets `deleted_at`. |
| `forceDelete(id)` | Whether there was a row. It deletes for real, soft deletes or not. |
| `restore(id)` | Whether there was a soft-deleted row to bring back (`false` for a row that is not deleted). It clears `deleted_at`. |

The values are exact: a field the table does not have is a compile error, also when the values come from a variable. With soft
deletes, `update()` leaves a deleted row alone.

On a table with timestamps, the repository stamps `created_at` and `updated_at` with the app's `Clock`, so `app.travel()` moves them
in a test (the [time](time.md#what-follows-the-clock) page). A value you pass for either column is kept, and the one you leave out is
stamped. The rows of one `insertMany()` share their time, whatever chunk they are written in. A raw statement (`insertInto()`, an
`sql` template) is not stamped by the repository: the column's default is the database server's time, so name the time in the values
when a test moves the clock.

`tryInsert()` and `tryUpdate()` decide "already taken" by the unique index, so two requests at the same moment cannot both pass.
They run in a transaction of their own, or in a savepoint inside an open one: on Postgres a failed statement breaks the
transaction around it, and the savepoint keeps that transaction usable. They return a [`Result`](errors.md#results): narrow it over
`ok`, then look at `error.kind`. Returned from a transaction's callback, the `err` rolls that transaction back like any other, as
the [transactions](transactions.md#returning-an-err) page explains.

The `duplicate` error of `tryInsert()` carries `columns`, the columns of the unique index that was hit. A table with several
unique indexes tells them apart without a savepoint of your own:

```ts
const created = await this.tryInsert(values);
if (!created.ok) {
  // The address is taken, or only the invite code collided and a new one can be drawn.
  return err({ kind: created.error.columns.includes('email') ? 'email-taken' : 'code-taken' });
}
```

`columns` holds columns of the table only, and is empty when they are not known. An index a migration describes is found by its
name, so its columns are exact. An index from raw SQL that no migration describes is read from what the driver reports: the
index's name on SQLite, and on Postgres when the error has no `detail`. Its columns are the column names that occur in that name,
so a word of the name that is also a column can be counted. Name such an index `{table}_{columns}_unique`, or describe it in a
migration. `tryUpdate()` reports `columns` the same way. The starter kit registers a user this way:

```ts title="modules/auth/UserRepository.ts"
import type { PasswordHash } from '@marmeon/auth';
import type { Result } from '@marmeon/core';
import { Repository } from '@marmeon/database';
import type { User } from './users.ts';

export class UserRepository extends Repository<'users'> {
  static table = 'users' as const;

  register(values: { name: string; email: string; password: PasswordHash; locale: string }): Promise<Result<User, { kind: 'duplicate' }>> {
    return this.tryInsert(values);
  }
}
```

To answer a form with "taken" at its field instead, wrap the write in `failOnDuplicate()`. The
[validation](validation.md#the-unique-index-is-the-truth) page shows it.

`insertMany()` and `tryInsertMany()` are for an import of thousands of rows. Both cut them into statements the driver accepts, since one statement takes at most
65 535 parameters on Postgres and 32 766 on SQLite (a row of two columns: about 32 000 and 16 000 rows), and writes all of them in one
transaction, or in a savepoint inside an open one. When the third of five chunks fails, the first two are rolled back with it: all rows
or none. `insertMany()` throws on a duplicate in any chunk, as `insert()` does. `tryInsertMany()` returns the same `err` as `tryInsert()`, with
`columns`; the transaction around it stays usable, and returning the `err` from its callback rolls it back. Any other failure throws. Every row needs the same columns, and at least one, else a
`TypeError` names the row that differs; an empty list is `0` (`ok(0)`) without a statement.

By default no rows come back: they would be one result of the size of the whole import, held in memory. Name the columns you need
with `returning` and each inserted row comes back with just those, from every chunk. They come in no promised order, so match them
by a column you wrote, such as a unique one. A secret column in `returning` is a compile error and a `TypeError` when it runs,
before a statement; so is an empty list.

```ts
const rows = await members.insertMany(names.map((name) => ({ name, email: emailOf(name) })), { returning: ['id', 'email'] });
```

```ts
const imported = await members.tryInsertMany(rows.map((row) => ({ name: row.name, email: row.email })));
if (!imported.ok) return err({ kind: 'email-taken' }); // none of the rows was written
return ok(imported.value);
```

`insertMissing()` writes a catalogue that may already be there. `on` names the columns of one unique index (a `TypeError`
without it), and a row whose values the table holds is skipped instead of failing, so running it again writes nothing, and two
calls at the same moment write each row once. The rows are written in the order of their `on` values, so two calls with the same
keys in another order take the locks in the same order and cannot deadlock (the second still waits for the first's uncommitted rows). A secret column is no `on` column, as it is no column of
`findBy()`: it would tell whether a value exists. Every row needs a value in each `on` column, never `null`: a NULL never conflicts, so such a
row would be written again on every run, and a `TypeError` says so before a statement. It is stamped, chunked and atomic like `insertMany()`. A unique violation on any
*other* index still throws, with every chunk rolled back: an address that belongs to another account does not pass as "already
there". When no unique index covers exactly the `on` columns, a `TypeError` names them and suggests `unique()` in the migration. A
soft-deleted row counts as there.

```ts
const added = await questions.insertMissing(rows, { on: ['survey', 'name'], returning: ['survey', 'name'] }); // only the new ones
```

The web-app's `lab` module seeds a survey's questions this way (`SurveyRepository.addMissing()`).

### Route binding

Every repository can bind a route parameter: `notes.bind('note', NoteRepository)` gives the controller the row, or answers 404.
`notes.bind('note', NoteRepository, { with: ['tags'] })` loads relations with it, in the same query. `routeKey`, `routeKeyPattern`,
bindings scoped to a parent and [relations](routing.md#loading-relations-with-the-record) are on the
[routing](routing.md#binding-a-repository) page.

## Relations

The foreign keys of your migrations relate your tables: `profile_links.user_id` gives `profile_links` a `user`, and `users` its
`profile_links`. The [migrations](migrations.md#relations-from-foreign-keys) page shows how the relations are named. `with()`
loads one into the same query, as JSON the database builds:

```ts title="modules/user-profile/ProfileDirectory.ts"
import { Database } from '@marmeon/database';

export class ProfileDirectory {
  readonly #db: Database<'user-profile'>;

  constructor(db: Database<'user-profile'>) {
    this.#db = db;
  }

  profile(id: number) {
    return this.#db
      .selectFrom('users')
      .selectAll('users')
      .with('login_activity', { as: 'activity' }, (activity) => activity.select('last_login_at'))
      .with('profile_links', { as: 'links' }, (links) => links.select(['id', 'user_id', 'label', 'url']).orderBy('id'))
      .where('users.id', '=', id)
      .executeTakeFirst();
  }
}
```

The result is the user's row with `activity: { last_login_at } | null` and `links: { id, user_id, label, url }[]`. It is **one
query**: there is no lazy loading, so there are no N+1 queries to fall into, and the [query log](observability.md) shows one
statement.

### Loading a relation

`with(name)` loads every column of the related table except its secret columns. A belongsTo or a hasOne gives one row or `null`,
a hasMany or a belongsToMany a list, empty when there is none. The names come from `bootstrap/database.d.ts`, so a wrong one is
a compile error that lists the right ones:

```text
Argument of type '"profile_link"' is not assignable to parameter of type '"login_activity" | "profile_links"'.
```

`with()` is a method of every select of the app's connection: a repository's `query()`, `Database`, a transaction, a subquery.
In a query that joins tables, it offers the relations of each table, except a name two of them share. Relations are offered on a
table's own name, `selectFrom('users')`, not on an alias such as `selectFrom('users as u')`. A module's
`Database<'user-profile'>` offers only relations whose tables the module sees, its own and the tables other modules expose: the
related table, and for a belongsToMany its pivot too. The same holds for `withCount()` and `whereHas()`.

> [!NOTE]
> Kysely has a `with()` of its own on the connection: `db.with('recent', (q) => …)` defines a common table expression. The
> relation method belongs to a select, `db.selectFrom('users').with('profile_links')`, so the two never meet.

### Narrowing and nesting

The callback gets the related table's query. Select, filter, order and limit it like any query, and load its relations with
`with()` again, to any depth. Its scope is the related table only: refer to the outer row through `sql` or `eb.ref()`, as in
`` links.where(sql<boolean>`profile_links.label <> users.name`) ``. When it selects columns of that table, the relation holds those
columns. A column under another name (`'label as title'`) does not count: it comes on top of every column but the secret ones,
until the callback names one column of the table as it is. When it selects none, because it only orders, filters or nests, the
relation keeps every column but the secret ones. `selectAll()` means the same:

```ts
this.#db
  .selectFrom('users')
  .select(['users.id', 'users.name'])
  .with('profile_links', (links) => links.where('label', '!=', '').orderBy('id').limit(3).with('user', (user) => user.select('name')));
```

`{ as }` gives a relation another key, `with('profile_links', { as: 'links' })`, with or without a callback after it.

A belongsTo is typed without `null` only when its foreign key is `NOT NULL` and the related table has no soft deletes. Otherwise
the related row may be missing, and the type says so. A hasOne may always be missing.

### Relations without a foreign key

`withRelation(name, definition, callback?)` loads rows no foreign key describes, or a relation in a shape of its own: the rows of
`table` whose `foreignKey` holds the outer row's `localKey`, which is `id` unless you name another column of the query's tables (the
first table that has it). With `one: true` it
loads the first row the callback's order gives, or `null`:

```ts
this.#db
  .selectFrom('users')
  .select(['users.id', 'users.name'])
  .withRelation('newest_link', { table: 'profile_links', foreignKey: 'user_id', one: true }, (links) => links.orderBy('id', 'desc'));
```

Its columns, secret columns and soft-deleted rows follow the rules of `with()`.

### Counting related rows

`withCount(name)` counts the rows of a hasMany or a belongsToMany in the same query and adds the number under `<name>_count`.
`{ as }` names it otherwise, and a callback narrows what is counted, with the related table in scope as in `with()`:

```ts
this.#db
  .selectFrom('users')
  .select(['users.id', 'users.name'])
  .withCount('profile_links')
  .withCount('profile_links', { as: 'secure_links' }, (links) => links.where('url', 'like', 'https://%'));
```

Each row gets `profile_links_count: number` and `secure_links: number`, a number on SQLite and on Postgres alike, `0` when
there is none. The callback filters what is counted: `groupBy()`, `having()`, `limit()`, `offset()` and a `union()` or another
set operation in it are refused, because they would change the count. A name the query selects already is refused too, since one
row cannot hold two values under it. A belongsTo or a hasOne has one row or none, so there is nothing to count: `withCount()` on
one is a compile error that lists the relations it can count, and `whereHas()` asks the question instead:

```text
Argument of type '"login_activity"' is not assignable to parameter of type '"profile_links"'.
```

A [data table](tables.md#columns) shows and sorts by such a count like a column.

### Filtering by relations

`whereHas(name, callback?)` keeps the rows that have a related row, and `whereDoesntHave(name, callback?)` the rows that have
none. Both become `exists (…)` in the same query. With a callback, only related rows its conditions match count:

```ts
this.#db
  .selectFrom('users')
  .select(['users.id', 'users.name'])
  .whereHas('profile_links', (links) => links.where('url', 'like', 'https://%'))
  .whereDoesntHave('login_activity');
```

Any relation works, a belongsToMany through its pivot too. The callbacks nest: `whereHas()` inside a `whereHas()`, a `with()`
or a `withCount()` callback filters that level. What the callback selects does not matter: only whether a row is there.
`limit()`, `offset()` and a set operation in it are refused, because they would change the answer. So is `having()` without
`groupBy()`, which makes every related row one group and which databases answer differently.

In the callback of `whereHas()`, `whereDoesntHave()`, `with()`, `withCount()` and `withRelation()`, an unqualified column is the
related table's: one it does not have is refused with an error before the query runs, never read from the outer table. Name the
table to reach the outer row (`users.email`). A selection's alias counts only in `orderBy()`. Subqueries in the callback are
checked too: a column is a table of the subquery's own, or one of the callback's. A subquery in FROM or a join sees neither the
callback's tables nor its other subqueries; a lateral join sees the tables before it. Raw SQL is not read, and a select with a
common table expression or a subquery without named columns (`selectAll()`) is left to the database.

### Writing through relations

A repository's `relation(id, name)` writes through a relation of one row. For a belongsToMany, it manages the rows of the pivot
that link the two tables:

```ts
await this.relation(noteId, 'tags').sync([1, 4, 7]); // { attached: [7], detached: [2] }
await this.relation(noteId, 'tags').attach(9); // [9]
await this.relation(noteId, 'tags').detach(4); // 1
```

`sync(ids)` leaves the note linked to exactly these tags: it attaches the missing ones, detaches the others and leaves the rest
alone, and says which it attached and detached. `attach()` takes one id or a list, skips the ones linked already, also by a
request at the same moment, and returns those it linked. `detach()` returns how many links went: without an argument, every
one; with an empty list, none. Every write through a relation, also with an empty list, answers 404 when the parent row is
missing or soft-deleted. Ids that may be `undefined`, such as a field a request did not send, are a compile error and
refused when the call runs.

A link to a row that is missing or soft-deleted is refused before anything is written, and the error names the ids:

```text
relation('tags').attach() would link the notes row 3 to the tags row 9, which is missing or soft-deleted — nothing was written. Check the ids first: the rule exists() leaves soft-deleted rows out. See docs/queries.md#writing-through-relations.
```

Check ids that come from a request with [`exists()`](validation.md#database-rules-and-why-they-never-run-live) in its rules. A
link to a row that was soft-deleted later stays until you detach it.

For a hasMany or a hasOne, `create(values)` and `createMany(values)` insert related rows with the foreign key set:

```ts
const link = await users.relation(user.id, 'profile_links').create({ label: 'Blog', url: 'https://example.com' });
```

The values are those of an insert without the foreign key, which the relation sets: naming it is a compile error, and a value that
got past the types is refused when it names the key in any case (`POST_ID`, which SQLite reads as `post_id`). The rows come
back as stored, without their secret columns, and `timestamps()` in the related table's migration fills in `created_at` and
`updated_at`. A hasOne's unique key refuses a second row.

Each call runs in a transaction of its own, or in a savepoint inside an open one, so a refused `sync()` changes nothing. The row
whose relation you write must be there: a missing or soft-deleted one answers 404 (`RecordNotFoundError`). A belongsTo has no
`relation()`: update its foreign key instead. A pivot with soft deletes is refused, and nested writes, such as creating a row
with its relations, do not exist: write each relation with a call of its own.

`RelationWriter<Tables, 'notes', 'tags'>` names what `relation()` returns: a `LinkWriter` for a belongsToMany, a `RelatedWriter`
for a hasMany or a hasOne. `WritableRelationName<Tables, 'notes'>` names the relations it takes.

### Soft-deleted rows

A relation never loads the rows a table's [soft deletes](migrations.md#timestamps-and-soft-deletes) mark as deleted, and
`withCount()`, `whereHas()` and `whereDoesntHave()` never count them, through a pivot neither. Call `withTrashed()` in the
callback to keep them for that relation. On a repository's `query()`, `withTrashed()` keeps them in the
query's own rows:

```ts
// In a NoteRepository, when notes and their attachments both have soft deletes:
this.query().withTrashed().selectAll().with('attachments', (attachments) => attachments.withTrashed());
```

`withTrashed()` works on the level it is called on: the relations below it still leave deleted rows out unless their callbacks
call it too. On a plain `db.selectFrom()`, which filters nothing, it has nothing to keep. A table you join yourself, inside a
callback or anywhere else, is your query: soft-deleted rows are not filtered there.

### Relations and secret columns

A secret column never comes back through a relation. It is not among the columns `with()` loads, and naming one inside a relation
is refused when the query runs: by name, with `secret(eb, …)`, `sql.ref()` or `sql.id()`, under an alias, from a table the
callback joins, from the outer query or a subquery or common table expression of it, or deeper down. So is a whole row of a source
that holds one, such as `eb.table('users')` in a function.

That goes for a subquery in a relation's `where()` too, as in any query, although its value stays in the database. Filter on a key
instead: `where('user_id', 'in', (eb) => eb.selectFrom('personal_access_tokens').select('user_id').where(…))`, or with a join.

```text
[marmeon:D9] with('personal_access_tokens') selects personal_access_tokens.token_hash, a secret column — a relation never loads one. Read it where it is needed, in a query of its own with secret(eb, …). See docs/queries.md#relations-and-secret-columns.
```

A condition may compare a secret column, in the callback of `with()`, `withCount()` or `whereHas()` as in any `where()`: its
value stays in the database. The answer does not: every row, count or yes the condition gives says something about the secret, so
never let a request choose the column or send a `like` pattern for it. A comparison in SQL does not take constant time either,
so a secret that can be guessed (a PIN, a password, a short code) is never looked up by its value: look the row up by its key and
compare the secret in code. A keyed MAC of it may be looked up, see [a short code a person types](encryption.md#a-short-code-a-person-types). A token with at least 128 random bits is different, see below.

### Finding a row by a hashed secret

A token with at least 128 random bits cannot be guessed, however fast the comparison: a request may look it up by its hash, which
the table keeps in a secret column with a unique index. The types close `where('token_hash', '=', hash)` (a secret column has no
value to compare), and `secretEquals()` opens it for this one comparison. It works in any `where()`, also in `whereHas()`, `updateTable()`
and `deleteFrom()`:

```ts
import { hashLinkToken } from '@marmeon/encryption';
import { secretEquals } from '@marmeon/database';

findByToken(presented: string) {
  return this.query().selectAll().where((eb) => secretEquals(eb, 'token_hash', hashLinkToken(presented))).executeTakeFirst();
}
```

The row comes back without the hash, as from any query. `secretEquals()` takes the hash, never the token, and throws a `TypeError`
for a value under 32 characters (a hex SHA-256 has 64) without naming it. It refuses a short secret, but not the hash of
a guessable one: hash only what is random, as [`linkToken()`](urls.md#a-link-that-is-used-once) and an
[API token](api-tokens.md#the-token-format) do.

A keyed MAC of a short code goes through `secretEquals()` the same way, as a [short code a person types](encryption.md#a-short-code-a-person-types) shows: the column holds
the MAC, which a request cannot work towards bit by bit, never the code.

The text of a raw `` sql`…` `` template is not checked: a column written into it is the query's own choice. Neither is a view: it
is raw SQL of a migration, so a view over a table with secret columns returns what its own SQL selects.

### Rows the database makes up

A list of days, a run of numbers or a calendar has no table. Raw SQL in `FROM` is refused with error D10, because the connection cannot see which columns it
passes on; a set-returning function belongs in the select list of a query of its own, and the query becomes a derived table. That works on
`Database<'notes'>` as well, which has `selectNoFrom()` and no `with()`:

```ts
import { sql, type Database } from '@marmeon/database';

// Postgres: seven rows, 1 to 7, that no table holds.
export function dayNumbers(db: Database<'notes'>) {
  const days = db.selectNoFrom(sql<number>`generate_series(1, 7)`.as('day')).as('days');
  return db.selectFrom(days).select('day');
}
```

For a [table](tables.md#the-base-query), `db.selectFrom(days)` without the `select('day')` is the base query: it selects nothing itself, and the
table names the column and its key as `days.day` (`key: 'days.day'`, `column('days.day')`). SQLite has no `generate_series()` without an
extension, so a test of such a query runs on Postgres.

On the app's `Database`, a common table expression does the same:

```ts
const days = sql<number>`generate_series(1, 7)`.as('day');
const rows = await db.with('days', (q) => q.selectNoFrom(days)).selectFrom('days').select('day').execute();
```

### The app's connection

The app's connection resolves the relations from its database, where the migrations left the foreign keys and their marks. A
query built on a connection without Marmeon's plugins, `connections.infrastructure()` or Kysely's `withoutPlugins()`, is refused
before it is sent, and so is a repository's `update()` or `delete()` bound to one with `using()`:

```text
This query loads, counts or filters by relations, leaves out soft-deleted rows or touches a row's timestamps (with(), withCount(), whereHas(), withRelation(), withTrashed(), a repository's query(), update() or delete()), which only the app's connection resolves — it was not sent: it runs on the database connection "default" without Marmeon's plugins (infrastructure(), withoutPlugins()). Build it on connections.get() or Database. See docs/queries.md#relations.
```

Nested values come back with the same types as the outer row's: booleans, parsed JSON, decimals as strings and timestamps in UTC,
on SQLite and Postgres alike.

## Module boundaries

`Database` sees every table. `Database<'notes'>` is the connection as the `notes` module sees it (`make:module` runs `db:types` for a new module; one you create or register by hand needs `marmeon db:types` before its name compiles):

- its **own tables**, created by its migrations, for everything;
- the tables other modules **expose**, for reading and joins only.

A module exposes a table in its definition. The starter kit's auth module exposes `users`:

```ts title="modules/auth/index.ts"
import { defineModule } from '@marmeon/core';
import routes from './routes.ts';

export default defineModule({
  name: 'auth',
  migrations: new URL('./migrations/', import.meta.url),
  exposes: ['users'],
  routes,
});
```

Changing `exposes` changes the types, so it needs `marmeon db:types` like a migration does (`marmeon check` and `marmeon db:types --check` say so).

In the `notes` module, `insertInto('users')`, `updateTable('users')` and `deleteFrom('users')` are compile errors, and a table of
another module that is not exposed does not exist at all. Writing to `users` goes through the auth module's `UserRepository`. The
boundary is a type: at runtime both are the same connection, and the connection checks none of the following: raw SQL, `sql`
fragments inside a builder (`modifyEnd`, for one), and a query built with the builder's own `.withoutPlugins()` — these are
deliberate escape hatches. A plugin added to a single query with `.withPlugin()` (or to the connection) runs after the connection's
own plugins, so the connection checks what it returns again before sending it — for secret columns like any query — and refuses
one that changes which tables the statement writes (its own and those of any statement inside it, such as a common table
expression), schema included. A query without such a plugin pays a lookup; one with a plugin is compiled a second time.
`Database<'notes'>` offers only the builder's reading methods (`selectFrom`, `selectNoFrom`, `fn`,
`case`, `dynamic`, `isTransaction`) and `insertInto`, `updateTable`, `deleteFrom` and `transaction()` for the module's own tables: no
`schema`, `introspection` or `with()`, and no `sql` template executed against it (``sql`…`.execute(db)``) — use `Database` where a
module needs those. A method the query builder gains later is not offered to modules until the framework has classified it. A module that exposes a table another
module's migration created, or that no migration created, stops `db:types` with an error that says so.

A module can type a table Marmeon does not know — made with `schema.raw()` or by another tool — with `withTables<…>()`. The table is
readable and joinable with the module's own and exposed tables, and never writable: `insertInto`, `updateTable` and `deleteFrom` on it are compile errors.

```ts
const orders = this.db.withTables<{ legacy_orders: { id: number; user_id: number; total: string } }>();
const rows = await orders.selectFrom('legacy_orders').innerJoin('users', 'users.id', 'legacy_orders.user_id').select(['users.name', 'legacy_orders.total']).execute();
```

A name the schema knows cannot be declared this way, neither another module's table that is not exposed nor your own: that would reach
past the boundary, and `withTables<{ audit_log: … }>()` is a compile error. Like the rest of the boundary it is a type only; at runtime `withTables` returns the
same connection. Names with a schema (`reporting.orders`) or an alias cannot be declared this way either.
Marmeon knows no secret column of these tables, so their columns pass the guard unchecked; they have no soft deletes or
timestamps, and `selectAll()` stays `*`.

A [table's base query](tables.md#the-base-query) takes `Database<'module'>` the same way.

A repository sees every table: `Repository<'profile_links'>` is typed with all of `Tables`. To give it the module's view, pass
`ModuleTables` as its second type argument. Its queries then see only the module's own tables and the exposed ones, `with()`
offers only relations to those, and `relation()` writes only into the module's own:

```ts title="modules/user-profile/ProfileLinkRepository.ts"
import { Repository, type ExposedTables, type ModuleTables, type TableOwners, type Tables } from '@marmeon/database';

export class ProfileLinkRepository extends Repository<'profile_links', ModuleTables<Tables, TableOwners, ExposedTables, 'user-profile'>> {
  static table = 'profile_links' as const;

  async removeAllOf(userIds: readonly number[]): Promise<number> {
    if (userIds.length === 0) return 0;
    const result = await this.db.deleteFrom('profile_links').where('user_id', 'in', userIds).executeTakeFirst();
    return Number(result.numDeletedRows);
  }
}
```

The migrator records which module's migration created each table. That record is what the boundaries and the comments in
`bootstrap/database.d.ts` are built on.

## Errors

| Function | Says |
| --- | --- |
| `isUniqueViolation(error)` | Whether the error is a unique violation, on SQLite and Postgres. |
| `uniqueViolationColumns(error)` | The violated index's columns, as far as the driver names them. |
| `missingTable(error)` | The table a statement could not find, or `undefined`. |

Catch a unique violation inside a transaction only around a savepoint, as `tryInsert()` does. On Postgres the failed statement
otherwise aborts the whole transaction, and every later query in it fails. Where "taken" is an outcome your code handles, prefer
`tryInsert()` and `tryUpdate()`: their `err` of kind `duplicate` is a [`Result`](errors.md#results), not an exception.

## Another connection

A repository with `static connection = 'reporting'` works on that connection. Its tables still come from `Tables`, the types of
your migrations. Code that queries a connection with tables of its own asks `Connections` for it:
`connections.get<ReportingTables>('reporting')`. The [database](database.md#more-connections) page shows how to define one.

## Queries take turns

A physical connection runs one query at a time, in the order the queries were sent. Outside a transaction, a Postgres pool spreads
queries over its connections. A transaction holds one connection, and SQLite has only one, so there a `Promise.all` of queries,
such as the props of a page, runs one query after the other. A query stream (`.stream()`) holds its connection until it ends:
while it runs, send other queries to another connection.
