page wrnexusdb {
  seo {
    title = "@wrnexus/db"
    description = "Database adapters, typed queries, models, migrations, and sessions."
  }

  view {
    <div class="docs-shell">
      <a class="skip-link" href="#main">Skip to content</a>
      <header class="topbar">
        <a class="brand" href="/"><span>W</span> WRNexusJS</a>
        <nav aria-label="Primary"><a href="/getting-started">Get started</a><a href="/packages">Packages</a><a href="/language">Language</a><a href="/architecture">Architecture</a></nav>
        <div class="topbar-actions"><a class="preview-pill" href="/access">Private preview · v0.2.31</a><button data-wire-theme-toggle class="theme-button" aria-label="Toggle color theme" title="Toggle color theme">◐</button></div>
      </header>
      <div class="mobile-doc-nav"><details><summary>Browse documentation</summary><nav><a href="/getting-started">Get started</a><a href="/packages">Packages</a><a href="/language">Language</a><a href="/architecture">Architecture</a><a href="/tutorial">Tutorial</a><a href="/guides/project-structure">Guides</a><a href="/examples">Examples</a><a href="/search">Search</a></nav></details></div>
      <main class="page package-page">
      <aside class="sidebar"><a href="/packages">← All packages</a><span class="category">Data</span><h2>@wrnexus/db</h2><p>Database adapters, typed queries, models, migrations, and sessions.</p><span class="status status-beta">Private preview · 0.2.31</span><nav><a href="#access">Access</a><a href="#guide">Guide</a><a href="#api">Complete API</a></nav></aside>
      <article id="main" class="documentation"><section class="doc-intro"><span class="eyebrow">Data · Preview</span><h1>@wrnexus/db</h1><p>Database adapters, typed queries, models, migrations, and sessions.</p><section id="access" class="access-callout"><h2>Private registry access required</h2><p>This package is not available from the public npm registry. After WorkRoot approves access and supplies private registry instructions, install the release-aligned package:</p><pre><code>bun add @wrnexus/db@0.2.31</code><button type="button" class="copy-button" aria-label="Copy installation command">Copy</button></pre><p><a href="/access">Request preview access</a>. Never put registry tokens in source control.</p></section></section><section id="guide" class="prose"><blockquote>The database layer for WRNexusJS: TS models as the single source of truth for DDL, validation, and result typing, plus a driver-based <code>Db</code> client, migrations, and a sqlc-style query generator.</blockquote>
<p>Part of the <strong>WRNexusJS</strong> framework — an SSR-first, Bun-native full-stack web framework.</p>
<h3 id="overview">Overview</h3>
<p><code>@wrnexus/db</code> is the server-side data layer. You describe tables as TypeScript models (the <code>v</code> column builder + <code>table()</code>); those models drive migrations, coerce raw DB rows into typed objects, and feed the query generator. A thin <code>Driver</code> interface is implemented by adapters for SQLite (<code>bun:sqlite</code>), Postgres/MySQL (<code>Bun.SQL</code>), and MongoDB. The <code>Db</code> client adds ergonomics — model-mapped <code>all</code>/<code>one</code>, transactions, <code>createTable</code>, pagination, and batched relation loading. A process-wide registry (<code>getDb</code>/<code>setDb</code>) exposes configured connections to pages and API routes. Reach for it whenever a WRNexusJS app needs persistence.</p>
<pre data-language="bash"><code>bun add @wrnexus/db</code></pre>
<blockquote>Private package — the machine must be authenticated to the <code>wrnexus</code> npm org</blockquote>
<blockquote>(a read token in <code>~/.npmrc</code>). Requires <strong>Bun</strong> (Node is not supported).</blockquote>
<h3 id="api">API</h3>
<p>The core entry (<code>@wrnexus/db</code>) is dependency-free; adapters and connectors live in subpaths so importing the core doesn't pull in every driver.</p>
<div class="table-wrap"><table>
<thead><tr><th>Subpath</th><th>Exports</th></tr></thead>
<tbody><tr><td><code>@wrnexus/db</code></td><td><code>v</code>, <code>table</code>, <code>Column</code>, <code>createDb</code>, <code>createTableSql</code>, the client registry (<code>setDb</code>/<code>getDb</code>/…), migrations, the query generator, and query helpers</td></tr><tr><td><code>@wrnexus/db/connect</code></td><td><code>connectFromConfig</code>, <code>resolveDbUrl</code>, <code>DbConfig</code> — resolve a config to a live SQL <code>Db</code></td></tr><tr><td><code>@wrnexus/db/session</code></td><td><code>sqliteSessionStore</code> — a <code>bun:sqlite</code> session backend for <code>@wrnexus/core</code></td></tr><tr><td><code>@wrnexus/db/sqlite</code></td><td><code>sqlite(url?)</code> driver</td></tr><tr><td><code>@wrnexus/db/postgres</code></td><td><code>postgres(url)</code> driver</td></tr><tr><td><code>@wrnexus/db/mysql</code></td><td><code>mysql(url)</code> driver</td></tr><tr><td><code>@wrnexus/db/mongo</code></td><td><code>mongo(url, dbName?)</code> document API</td></tr></tbody></table></div>
<h4 id="schema-v-table-column">Schema — <code>v</code>, <code>table</code>, <code>Column</code></h4>
<p><code>table(name, columns)</code> returns a <code>Model&lt;T&gt;</code>. Columns are built with <code>v</code>:</p>
<pre data-language="ts"><code>import &#123; v, table &#125; from &quot;@wrnexus/db&quot;;

const users = table(&quot;users&quot;, &#123;
  id: v.id(), // auto-increment primary key
  email: v.text().unique(),
  name: v.text().optional(), // NULLable
  age: v.int().default(0),
  active: v.bool().default(true),
  createdAt: v.timestamp().default(&quot;now&quot;), // CURRENT_TIMESTAMP
&#125;);</code></pre>
<p>Column builders: <code>v.id</code>, <code>v.text</code> (alias <code>v.string</code>), <code>v.int</code>, <code>v.real</code> (alias <code>v.number</code>), <code>v.bool</code> (alias <code>v.boolean</code>), <code>v.timestamp</code>, <code>v.json</code>. <code>BaseType</code> values are <code>&quot;id&quot; | &quot;text&quot; | &quot;int&quot; | &quot;real&quot; | &quot;bool&quot; | &quot;timestamp&quot; | &quot;json&quot;</code>.</p>
<p><code>Column</code> modifiers (chainable): <code>.optional()</code>, <code>.unique()</code>, <code>.default(value)</code> (use the sentinel <code>&quot;now&quot;</code> for a current-timestamp default), <code>.primaryKey()</code>, <code>.references(table, column = &quot;id&quot;)</code>. <code>.coerce(raw)</code> converts a raw DB value to its JS type.</p>
<p>A <code>Model&lt;T&gt;</code> exposes: <code>name</code>, <code>columns</code>, <code>parse(row)</code> (coerces a raw row into a typed <code>T</code>; unknown columns pass through), and <code>describe()</code> (returns each column's <code>ColumnDef</code>, for migrations and the generator).</p>
<h4 id="driver-client-createdb-db-driver">Driver &amp; client — <code>createDb</code>, <code>Db</code>, <code>Driver</code></h4>
<pre data-language="ts"><code>createDb(driver: Driver): Db</code></pre>
<p>A <code>Driver</code> (implemented by adapters) exposes <code>dialect</code>, <code>query(sql, params?)</code>, <code>exec(sql, params?)</code>, <code>transaction(fn)</code>, and <code>close()</code>. <code>createDb</code> wraps it in a <code>Db</code>:</p>
<ul>
<li><code>all&lt;T&gt;(sql, params?, model?)</code> — all rows, mapped through <code>model.parse</code> when a model is given.</li>
<li><code>one&lt;T&gt;(sql, params?, model?)</code> — first row or <code>null</code>.</li>
<li><code>exec(sql, params?)</code> — <code>Promise&lt;ExecResult&gt;</code> (<code>&#123; changes, lastInsertId? &#125;</code>).</li>
<li><code>tx(fn)</code> — run <code>fn(db)</code> in a transaction; rolls back on throw. Nested <code>tx</code> reuses the current transaction.</li>
<li><code>createTable(model)</code> — runs the model's <code>CREATE TABLE IF NOT EXISTS</code> DDL.</li>
<li><code>close()</code>.</li>
</ul>
<p>Every query is parameterized (positional params). <code>createTableSql(model, dialect, ifNotExists?)</code> renders <code>CREATE TABLE</code> directly; <code>Dialect</code> is <code>&quot;sqlite&quot; | &quot;postgres&quot; | &quot;mysql&quot;</code>.</p>
<h4 id="client-registry-getdb-setdb">Client registry — <code>getDb</code> / <code>setDb</code></h4>
<p>A process-wide registry the runtime configures at startup from <code>wrnexus.config.ts</code> (the <code>db</code> setting is the default; <code>databases.&lt;name&gt;</code> entries are named).</p>
<ul>
<li><code>setDb(db)</code> / <code>setDb(name, db)</code> — set the default or a named connection.</li>
<li><code>registerDb(name, db)</code> — alias of <code>setDb(name, db)</code>.</li>
<li><code>getDb(name = &quot;default&quot;)</code> — the default or a named <code>Db</code> (throws if unconfigured).</li>
<li><code>hasDb(name?)</code>, <code>databaseNames()</code>, <code>closeDatabases()</code>.</li>
</ul>
<pre data-language="ts"><code>const users = await getDb().all(&quot;SELECT * FROM users&quot;);
const events = await getDb(&quot;analytics&quot;).all(&quot;SELECT * FROM hits&quot;);</code></pre>
<h4 id="adapters">Adapters</h4>
<ul>
<li><code>@wrnexus/db/sqlite</code> — <code>sqlite(url = &quot;:memory:&quot;)</code>. <code>url</code> may be <code>file:./dev.db</code>, a raw path, or <code>:memory:</code>. Built on <code>bun:sqlite</code>; no external service.</li>
<li><code>@wrnexus/db/postgres</code> — <code>postgres(url)</code> (e.g. <code>postgres://user:pass@host:5432/db</code>, placeholders <code>$N</code>).</li>
<li><code>@wrnexus/db/mysql</code> — <code>mysql(url)</code> (e.g. <code>mysql://user:pass@host:3306/db</code>, placeholders <code>?</code>). Postgres/MySQL both use Bun's native <code>Bun.SQL</code> client and its pooled <code>begin()</code> for transactions.</li>
<li><code>@wrnexus/db/mongo</code> — <code>mongo(url, dbName?)</code>. A document API, not SQL: <code>db.collection(model)</code> returns a <code>MongoRepo&lt;T&gt;</code> with <code>find</code>, <code>findOne</code>, <code>insert</code>, <code>insertMany</code>, <code>update</code>, <code>delete</code>, <code>count</code>. Reads are coerced through <code>model.parse</code> (<code>_id</code> is mapped to <code>id</code>). The <code>mongodb</code> driver is imported lazily — install it to use Mongo.</li>
</ul>
<h4 id="migrations">Migrations</h4>
<p>Migrations are <code>.sql</code> files (in e.g. <code>app/db/migrations</code>), each split into <code>-- +up</code> and <code>-- +down</code> sections. A file with no markers is treated entirely as <code>up</code>. Applied names are recorded in a <code>_wire_migrations</code> table so each runs once.</p>
<ul>
<li><code>parseMigration(name, content)</code> → <code>Migration</code> (<code>&#123; name, up, down &#125;</code>).</li>
<li><code>loadMigrations(dir)</code> — parse all <code>.sql</code> files, sorted by filename.</li>
<li><code>appliedMigrations(db)</code> — applied names, oldest first.</li>
<li><code>migrate(db, dir)</code> — apply all pending (each in a transaction); returns applied names.</li>
<li><code>rollback(db, dir)</code> — roll back the most recent; returns its name or <code>null</code>.</li>
<li><code>status(db, dir)</code> — <code>&#123; name, applied &#125;[]</code> for every migration file.</li>
<li><code>scaffoldMigration(dir, name, dialect, models?)</code> — write a new numbered migration; with <code>models</code> it generates <code>CREATE</code>/<code>DROP</code> for every table (referenced tables first via topological sort). Returns the file path.</li>
</ul>
<h4 id="query-generator-sqlc-style">Query generator (sqlc-style)</h4>
<p>Turns annotated SQL into typed TS functions; params and result types are inferred from the models, and rows map back through <code>model.parse</code> when the selected columns are model columns.</p>
<ul>
<li><code>parseQueries(content)</code> → <code>QueryDef[]</code> from <code>-- name: X :one|:many|:exec</code> blocks.</li>
<li><code>generateQueriesFile(queries, models, dialect)</code> → the <code>queries.gen.ts</code> source. <code>models</code> is a <code>ModelRef[]</code> (<code>&#123; varName, model &#125;</code>). Rewrites <code>:name</code> placeholders to positional (<code>$N</code>/<code>?</code>) form.</li>
</ul>
<p><code>QueryKind</code> is <code>&quot;one&quot; | &quot;many&quot; | &quot;exec&quot;</code>.</p>
<h4 id="query-helpers">Query helpers</h4>
<ul>
<li><code>paginate(db, &#123; sql, params?, countSql?, model? &#125;, opts?)</code> — offset pagination. Pass the base SELECT <strong>without</strong> a LIMIT; it appends the page window and derives <code>total</code> via a COUNT subquery. <code>PageOptions</code>: <code>&#123; page?, perPage?, maxPerPage? &#125;</code> (defaults page 1, perPage 20, maxPerPage 100). Returns <code>Paginated&lt;T&gt;</code> (<code>items, page, perPage, total, totalPages, hasNext, hasPrev</code>).</li>
<li><code>loadRelated(db, parents, opts)</code> — load a relation for many parents in ONE query and attach it (no N+1). <code>RelationOptions</code>: <code>&#123; table, foreignKey, as, localKey?, single?, model? &#125;</code> — <code>single: true</code> attaches one child (belongsTo), otherwise an array (hasMany). Table/foreign-key names are validated as identifiers.</li>
</ul>
<h4 id="session-store">Session store</h4>
<p><code>@wrnexus/db/session</code> exports <code>sqliteSessionStore(path = &quot;sessions.db&quot;)</code>, a persistent, process-shared <code>SessionBackend</code> (from <code>@wrnexus/core</code>) backed by <code>bun:sqlite</code> (WAL mode). Sessions survive restarts and are shared by every worker on the same file.</p>
<h3 id="usage">Usage</h3>
<p>Define models, connect, create tables, and query with typed results:</p>
<pre data-language="ts"><code>import &#123; v, table, createDb &#125; from &quot;@wrnexus/db&quot;;
import &#123; sqlite &#125; from &quot;@wrnexus/db/sqlite&quot;;

const users = table&lt;&#123; id: number; email: string; name: string | null &#125;&gt;(&quot;users&quot;, &#123;
  id: v.id(),
  email: v.text().unique(),
  name: v.text().optional(),
  createdAt: v.timestamp().default(&quot;now&quot;),
&#125;);

const db = createDb(sqlite(&quot;file:./dev.db&quot;));
await db.createTable(users);

await db.exec(&quot;INSERT INTO users (email) VALUES (?)&quot;, [&quot;a@b.com&quot;]);
const list = await db.all(&quot;SELECT * FROM users&quot;, [], users); // rows typed + coerced
const one = await db.one(&quot;SELECT * FROM users WHERE id = ?&quot;, [1], users);

await db.tx(async (tx) =&gt; &#123;
  await tx.exec(&quot;UPDATE users SET name = ? WHERE id = ?&quot;, [&quot;Ada&quot;, 1]);
&#125;);</code></pre>
<p>Resolve a config to a live SQL <code>Db</code>, and register it:</p>
<pre data-language="ts"><code>import &#123; connectFromConfig &#125; from &quot;@wrnexus/db/connect&quot;;
import &#123; setDb, getDb &#125; from &quot;@wrnexus/db&quot;;

setDb(connectFromConfig(&#123; driver: &quot;sqlite&quot;, url: &quot;file:./dev.db&quot; &#125;, process.cwd()));
const rows = await getDb().all(&quot;SELECT * FROM users&quot;);</code></pre>
<p>Run migrations and paginate:</p>
<pre data-language="ts"><code>import &#123; migrate, paginate &#125; from &quot;@wrnexus/db&quot;;

await migrate(db, &quot;app/db/migrations&quot;);
const pageTwo = await paginate(
  db,
  &#123; sql: &quot;SELECT * FROM users ORDER BY id&quot;, model: users &#125;,
  &#123; page: 2 &#125;,
);</code></pre>
<p>MongoDB (document API):</p>
<pre data-language="ts"><code>import &#123; mongo &#125; from &quot;@wrnexus/db/mongo&quot;;

const mdb = await mongo(process.env.MONGO_URL!, &quot;app&quot;);
const repo = mdb.collection(users);
await repo.insert(&#123; email: &quot;a@b.com&quot; &#125;);
const active = await repo.find(&#123; active: true &#125;);</code></pre>
<h3 id="configuration">Configuration</h3>
<p><code>connectFromConfig</code> (and the runtime) read a <code>DbConfig</code> (<code>&#123; driver, url &#125;</code>) where <code>driver</code> is <code>sqlite | postgres | mysql</code>. <code>resolveDbUrl(url, appRoot?)</code> resolves a relative <code>file:</code>/<code>sqlite:</code> URL against the app root. MongoDB is not a SQL driver — use <code>@wrnexus/db/mongo</code> directly.</p>
<h3 id="requirements-notes">Requirements / Notes</h3>
<ul>
<li><strong>Bun-only.</strong> Uses <code>bun:sqlite</code> (SQLite adapter + session store) and <code>Bun.SQL</code></li>
<p>(Postgres/MySQL). Migrations/scaffolding use <code>node:fs</code>/<code>node:path</code>.</p>
<li>Works with <code>@wrnexus/core</code> — <code>sqliteSessionStore</code> implements its</li>
<p><code>SessionBackend</code>; <code>getDb</code>/<code>setDb</code> are wired by the WRNexusJS runtime from <code>wrnexus.config.ts</code>.</p>
<li>The <code>mongodb</code> npm package is an optional, lazily-imported peer — install it</li>
<p>only if you use <code>@wrnexus/db/mongo</code>. The core package stays dependency-free.</p>
</ul></section><section id="api" class="prose api"><h2>Complete TypeScript API</h2><p>This declaration comes from the exact installed package and lists its exported functions, classes, interfaces, and types.</p><pre data-language="typescript"><code>import &#123; M as Model &#125; from './schema-tVurYsbL.js';
export &#123; B as BaseType, C as Column, a as ColumnDef, b as Columns, t as table, v &#125; from './schema-tVurYsbL.js';
import &#123; a as Db, b as Dialect, R as Row &#125; from './driver-DA53QHkO.js';
export &#123; D as Driver, E as ExecResult, T as TxHandle, c as createDb, d as createTableSql &#125; from './driver-DA53QHkO.js';

/**
 * A process-wide database registry. The framework configures it at server
 * startup from `wrnexus.config.ts`: the `db` setting becomes the **default**
 * connection, and each entry under `databases` becomes a **named** connection.
 * Pages and API routes then call `getDb()` for the default, or `getDb(&quot;&lt;name&gt;&quot;)`
 * for a named one, to run queries (including the generated typed functions).
 *
 *   const users = await getDb().all(&quot;SELECT * FROM users&quot;);            // default db
 *   const events = await getDb(&quot;analytics&quot;).all(&quot;SELECT * FROM hits&quot;); // named db
 */

/** Set the default database (called by the runtime at startup). */
declare function setDb(db: Db): Db;
/** Set a named database (from `databases.&lt;name&gt;` in config). */
declare function setDb(name: string, db: Db): Db;
/** Register a named database. Alias of `setDb(name, db)` for readability. */
declare function registerDb(name: string, db: Db): Db;
/** The default database, or a named one. Throws if it isn't configured. */
declare function getDb(name?: string): Db;
/** Whether the default (or a named) database has been configured. */
declare function hasDb(name?: string): boolean;
/** Names of all configured databases (the default appears as &quot;default&quot;). */
declare function databaseNames(): string[];
/** Close every configured database and clear the registry. */
declare function closeDatabases(): Promise&lt;void&gt;;

/**
 * Migration runner. Migrations are `.sql` files in `app/db/migrations`, each
 * split into `-- +up` and `-- +down` sections. Applied migrations are recorded
 * in a `_wire_migrations` table so they run exactly once, newest-last.
 *
 * `scaffoldMigration(..., models)` writes an initial migration straight from the
 * TS models — the source of truth — so you don't hand-write the first schema.
 */

interface Migration &#123;
    name: string;
    up: string;
    down: string;
&#125;
/** Split a migration file into its `up` and `down` SQL sections. */
declare function parseMigration(name: string, content: string): Migration;
/** Load and parse all migration files in a directory, sorted by filename. */
declare function loadMigrations(dir: string): Migration[];
/** Names of already-applied migrations, oldest first. */
declare function appliedMigrations(db: Db): Promise&lt;string[]&gt;;
/** Apply all pending migrations (each in a transaction). Returns applied names. */
declare function migrate(db: Db, dir: string): Promise&lt;string[]&gt;;
/** Roll back the most recently applied migration. Returns its name, or null. */
declare function rollback(db: Db, dir: string): Promise&lt;string | null&gt;;
/** Full status: every migration file with whether it has been applied. */
declare function status(db: Db, dir: string): Promise&lt;&#123;
    name: string;
    applied: boolean;
&#125;[]&gt;;
/**
 * Write a new migration file. With `models`, the `up`/`down` are generated from
 * the TS models (create/drop every table); otherwise empty stubs are written.
 * Returns the created file path.
 */
declare function scaffoldMigration(dir: string, name: string, dialect: Dialect, models?: Model[]): string;

/**
 * sqlc-style query generator. Annotated SQL in `app/db/queries/*.sql` becomes
 * typed TS functions whose params + results are inferred from the TS models and
 * whose rows are mapped back through `model.parse`.
 *
 *   -- name: GetUserByEmail :one
 *   SELECT * FROM users WHERE email = :email;
 *
 * →  GetUserByEmail(db, &#123; email: string &#125;): Promise&lt;&#123;…&#125; | null&gt;
 *
 * Type inference is best-effort (comparisons + INSERT column lists + SELECT list
 * vs the model); anything it can't resolve becomes `unknown`.
 */

type QueryKind = &quot;one&quot; | &quot;many&quot; | &quot;exec&quot;;
interface QueryDef &#123;
    name: string;
    kind: QueryKind;
    sql: string;
&#125;
/** A model plus the variable name it is exported under (for imports). */
interface ModelRef &#123;
    varName: string;
    model: Model;
&#125;
/** Parse annotated queries from one `.sql` file's contents. */
declare function parseQueries(content: string): QueryDef[];
/** Generate the full `queries.gen.ts` source. */
declare function generateQueriesFile(queries: QueryDef[], models: ModelRef[], dialect: Dialect): string;

/**
 * Query ergonomics built on the `Db` client: offset pagination and a batched
 * relation loader (avoids N+1). Both are dialect-aware — placeholders follow the
 * driver's style (`$N` for Postgres, `?` for SQLite/MySQL).
 */

interface PageOptions &#123;
    page?: number;
    perPage?: number;
    /** Upper bound on perPage. Default 100. */
    maxPerPage?: number;
&#125;
interface Paginated&lt;T&gt; &#123;
    items: T[];
    page: number;
    perPage: number;
    total: number;
    totalPages: number;
    hasNext: boolean;
    hasPrev: boolean;
&#125;
/**
 * Paginate a SELECT. Pass the base query WITHOUT a LIMIT; the helper appends the
 * page window and derives the total with a COUNT over the same query.
 *
 *   await paginate(db, &#123; sql: &quot;SELECT * FROM users ORDER BY name&quot;, model: users &#125;, &#123; page: 2 &#125;)
 */
declare function paginate&lt;T = Row&gt;(db: Db, query: &#123;
    sql: string;
    params?: unknown[];
    countSql?: string;
    model?: Model&lt;T&gt;;
&#125;, opts?: PageOptions): Promise&lt;Paginated&lt;T&gt;&gt;;
interface RelationOptions&lt;C&gt; &#123;
    /** Parent field whose value matches the child's foreign key. Default &quot;id&quot;. */
    localKey?: string;
    /** Child table to load from. */
    table: string;
    /** Child column that references the parent. */
    foreignKey: string;
    /** Property name to attach on each parent. */
    as: string;
    /** true → attach a single child (belongsTo); false → an array (hasMany). */
    single?: boolean;
    /** Map child rows through a model. */
    model?: Model&lt;C&gt;;
&#125;
/**
 * Load a relation for a set of parent rows in ONE query and attach it to each
 * parent (no N+1). Returns the same parents, each with `opts.as` populated.
 *
 *   await loadRelated(db, users, &#123; table: &quot;posts&quot;, foreignKey: &quot;userId&quot;, as: &quot;posts&quot; &#125;)
 */
declare function loadRelated&lt;P extends Row, C extends Row = Row&gt;(db: Db, parents: P[], opts: RelationOptions&lt;C&gt;): Promise&lt;(P &amp; Record&lt;string, C | C[] | null&gt;)[]&gt;;

export &#123; Db, Dialect, type Migration, Model, type ModelRef, type PageOptions, type Paginated, type QueryDef, type QueryKind, type RelationOptions, Row, appliedMigrations, closeDatabases, databaseNames, generateQueriesFile, getDb, hasDb, loadMigrations, loadRelated, migrate, paginate, parseMigration, parseQueries, registerDb, rollback, scaffoldMigration, setDb, status &#125;;
</code></pre></section><section id="examples" class="prose examples"><h2>Examples</h2><p>Examples are taken from this package's installed documentation and must be evaluated with its requirements and stability notes.</p><div class="example-grid"><article class="example-card"><h3>Define models, connect, create tables, and query with typed results</h3><pre data-language="ts"><code>import &#123; v, table, createDb &#125; from &quot;@wrnexus/db&quot;;
import &#123; sqlite &#125; from &quot;@wrnexus/db/sqlite&quot;;

const users = table&lt;&#123; id: number; email: string; name: string | null &#125;&gt;(&quot;users&quot;, &#123;
  id: v.id(),
  email: v.text().unique(),
  name: v.text().optional(),
  createdAt: v.timestamp().default(&quot;now&quot;),
&#125;);

const db = createDb(sqlite(&quot;file:./dev.db&quot;));
await db.createTable(users);

await db.exec(&quot;INSERT INTO users (email) VALUES (?)&quot;, [&quot;a@b.com&quot;]);
const list = await db.all(&quot;SELECT * FROM users&quot;, [], users); // rows typed + coerced
const one = await db.one(&quot;SELECT * FROM users WHERE id = ?&quot;, [1], users);

await db.tx(async (tx) =&gt; &#123;
  await tx.exec(&quot;UPDATE users SET name = ? WHERE id = ?&quot;, [&quot;Ada&quot;, 1]);
&#125;);</code></pre></article><article class="example-card"><h3>Resolve a config to a live SQL Db, and register it</h3><pre data-language="ts"><code>import &#123; connectFromConfig &#125; from &quot;@wrnexus/db/connect&quot;;
import &#123; setDb, getDb &#125; from &quot;@wrnexus/db&quot;;

setDb(connectFromConfig(&#123; driver: &quot;sqlite&quot;, url: &quot;file:./dev.db&quot; &#125;, process.cwd()));
const rows = await getDb().all(&quot;SELECT * FROM users&quot;);</code></pre></article><article class="example-card"><h3>Run migrations and paginate</h3><pre data-language="ts"><code>import &#123; migrate, paginate &#125; from &quot;@wrnexus/db&quot;;

await migrate(db, &quot;app/db/migrations&quot;);
const pageTwo = await paginate(
  db,
  &#123; sql: &quot;SELECT * FROM users ORDER BY id&quot;, model: users &#125;,
  &#123; page: 2 &#125;,
);</code></pre></article><article class="example-card"><h3>MongoDB (document API)</h3><pre data-language="ts"><code>import &#123; mongo &#125; from &quot;@wrnexus/db/mongo&quot;;

const mdb = await mongo(process.env.MONGO_URL!, &quot;app&quot;);
const repo = mdb.collection(users);
await repo.insert(&#123; email: &quot;a@b.com&quot; &#125;);
const active = await repo.find(&#123; active: true &#125;);</code></pre></article></div></section></article>
      <aside class="on-this-page"><h2>On this page</h2><nav><a class="toc-level-2" href="#guide">Guide</a><a class="toc-level-3" href="#overview">Overview</a><a class="toc-level-3" href="#api">API</a><a class="toc-level-4" href="#schema-v-table-column">Schema — v, table, Column</a><a class="toc-level-4" href="#driver-client-createdb-db-driver">Driver &amp; client — createDb, Db, Driver</a><a class="toc-level-4" href="#client-registry-getdb-setdb">Client registry — getDb / setDb</a><a class="toc-level-4" href="#adapters">Adapters</a><a class="toc-level-4" href="#migrations">Migrations</a><a class="toc-level-4" href="#query-generator-sqlc-style">Query generator (sqlc-style)</a><a class="toc-level-4" href="#query-helpers">Query helpers</a><a class="toc-level-4" href="#session-store">Session store</a><a class="toc-level-3" href="#usage">Usage</a><a class="toc-level-3" href="#configuration">Configuration</a><a class="toc-level-3" href="#requirements-notes">Requirements / Notes</a><a class="toc-level-2" href="#api">Complete API</a><a class="toc-level-2" href="#examples">Examples</a></nav></aside>
    </main>
      <footer>WRNexusJS 0.2.31 · Private Developer Preview · Bun-native · Documentation generated from installed package APIs.</footer>
    </div>
  }
}
