Skip to content
VaelJS Blog

Databases with vael:db

vael:db and vael:db/migrate provide bounded asynchronous SQL execution, a zero-ORM fluent query builder, safe sql tagged templates, nested savepoints, lossless rich types, and deterministic schema migrations in vjs (V8).

Zero ORM by design: There are no ORM classes, entity models, decorators, active-record proxies, or hidden identity stores. Queries return plain JavaScript objects, and TypeScript users can optionally pass an <AppDb> table-to-row interface to open<AppDb>() / openSqlite<AppDb>() for compile-time table/column autocomplete and row inference.

1. Opening SQLite & Network Databases (Plain JS or Typed <AppDb>)

Section titled “1. Opening SQLite & Network Databases (Plain JS or Typed <AppDb>)”

Database implements [Symbol.asyncDispose](), so await using closes the pool cleanly on exit or error. openSqlite(":memory:") defaults to max_connections: 1 so all operations share the same in-memory database:

// Plain JavaScript (zero TypeScript types required)
import { openSqlite } from "vael:db";
await using db = await openSqlite("./app.db");
await db.execute(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
nick TEXT,
role TEXT NOT NULL DEFAULT 'member',
active INTEGER NOT NULL DEFAULT 1
)
`);

In TypeScript, pass a schema interface ({ tableName: { columnName: type } }) to openSqlite<AppDb>() or open<AppDb>() to get checked table names, column names, operators, and projected result types with zero runtime overhead:

import { open, openSqlite } from "vael:db";
interface AppDb {
users: {
id: number;
email: string;
name: string;
nick: string | null;
role: string;
active: number;
};
orders: {
id: number;
user_id: number;
total_cents: number;
status: "pending" | "paid" | "void";
};
}
await using mem = await openSqlite<AppDb>(":memory:");
// Or configure SQLite pool/timeout explicitly:
await using fileDb = await open<AppDb>({
driver: "sqlite",
database: "./app.db",
busy_timeout_ms: 5_000,
max_connections: 4,
});

Opt-In Network SQL Drivers & Secure-by-Default TLS

Section titled “Opt-In Network SQL Drivers & Secure-by-Default TLS”

SQLite (vael-db) is enabled out of the box. Network providers are opt-in Cargo features on vaeljs / vaeljs-core:

Driver NetworkDbConfig.driver Cargo Feature (vaeljs / vaeljs-core) Default Port
PostgreSQL "postgres" vael-db-postgres (or vael-db-all) 5432
MySQL "mysql" vael-db-mysql (or vael-db-all) 3306
MariaDB "mariadb" vael-db-mariadb (or vael-db-all) 3306
Microsoft SQL Server "mssql" vael-db-mssql (or vael-db-all) 1433

If a binary is compiled without the driver feature, open() validates the configuration strictly first and rejects with DbError (code === "DRIVER_UNAVAILABLE").

Network connections default to fail-closed verified TLS (tlsMode: "verifyFull" / tls: true), verifying both the certificate chain and server hostname:

import { open } from "vael:db";
import { env } from "node:process";
// Production: verified TLS is the default (optional custom CA via caFile)
await using pg = await open<AppDb>({
driver: "postgres",
host: "db.internal.example",
port: 5432,
database: "billing",
user: "app_reader",
password: env.PG_PASSWORD,
tlsMode: "verifyFull",
caFile: "./certs/internal-ca.pem",
max_connections: 8,
connect_timeout_ms: 10_000,
});
// Local development only: explicitly opt into cleartext TCP
await using localPg = await open<AppDb>({
driver: "postgres",
host: "127.0.0.1",
database: "billing_dev",
user: "postgres",
password: env.PG_DEV_PASSWORD,
tls: false, // or tlsMode: "plaintext"
});

See the Database API (vaeljs-dbapi) spec for pool limits (1..=1024), timeout bounds (1..=300_000 ms), and per-query DbQueryOptions (maxRows <= 100_000, maxBytes <= 33_554_432, timeoutMs <= 300_000).

All query builders are immutable — branching a base query never mutates the original builder.

import { col, func, select, table } from "vael:db";
const activeBase = db.from("users").where("active", 1);
// Filters, OR branches, ranges, portable ILIKE, conditional .when()
const onlyAdmins = false;
const filtered = await activeBase
.select("id", "name", "email")
.when(onlyAdmins, (q) => q.where("role", "admin"))
.whereIn("role", ["member", "admin"])
.whereNotNull("email")
.whereBetween("id", 1, 1_000)
.whereILike("name", "%ada%")
.orWhere((eb) => eb.and(eb.eq("role", "admin"), eb.isNull("nick")))
.orderDesc("id")
.limit(20)
.offset(0)
.all();

Projections, Joins, Aggregates, CTEs, and Set Operations

Section titled “Projections, Joins, Aggregates, CTEs, and Set Operations”

select() accepts column names or an alias projection map ({ alias: colRefOrExpr }). join() and leftJoin() support both an ExprBuilder callback (eb) => ... and a 3-argument column form:

// Alias map + inner join (callback) + groupBy + having + orderAsc
const vipTotals = await db
.from(table("orders", { as: "o" }))
.join(table("users", { as: "u" }), (eb) => eb.eq(col("o", "user_id"), col("u", "id")))
.select({
userName: col("u", "name"),
orderCount: func("COUNT", "*"),
paidTotal: func("SUM", col("o", "total_cents")),
})
.where(col("o", "status"), "paid")
.groupBy(col("u", "id"), col("u", "name"))
.having((eb) => eb.gt(func("SUM", col("o", "total_cents")), 1_000))
.orderAsc(col("u", "name"))
.all();
// 3-arg column form with leftJoin
const withOptionalOrders = await db
.from(table("users", { as: "u" }))
.leftJoin(table("orders", { as: "o" }), col("u", "id"), col("o", "user_id"))
.select({ userId: col("u", "id"), orderId: col("o", "id") })
.all();
// CTE (.with) and UNION (.union / .unionAll)
const paidCte = db
.from("paid_orders")
.with("paid_orders", select("orders").select("user_id", "total_cents").where("status", "paid"))
.select("user_id", "total_cents")
.orderDesc("total_cents");
const cteRows = await paidCte.all();
const combinedNames = await db
.from("users")
.select("name")
.where("role", "admin")
.union(select("users").select("name").where("active", 1))
.all();

Scalar Helpers, Cardinality & Dialect SQL Inspection (toSql)

Section titled “Scalar Helpers, Cardinality & Dialect SQL Inspection (toSql)”
// Scalar value from first row (null if no row matched OR column is SQL NULL)
const email = await db.from("users").where("id", 1).value("email");
// Array of scalar values for one column
const names = await db.from("users").where("active", 1).orderAsc("id").pluck("name");
// Fast existence & count checks
const hasAdmin = await db.from("users").where("role", "admin").exists();
const activeUsers = await db.from("users").where("active", 1).count();
// Inspect rendered dialect SQL and bound parameters without executing
const rendered = db
.from("users")
.select("id", "name")
.whereILike("name", "%ada%")
.limit(10)
.toSql("postgres");
// rendered.sql -> 'SELECT "id", "name" FROM "users" WHERE ("name" ILIKE $1) LIMIT 10'
// rendered.params -> ["%ada%"]
  • .first() returns Row | null.
  • .one() expects exactly 1 row and throws DbError (code === "CARDINALITY", databaseKind === "NoRows" or "TooManyRows") otherwise.

3. Fluent Mutations (INSERT, UPDATE, DELETE)

Section titled “3. Fluent Mutations (INSERT, UPDATE, DELETE)”

insertInto().values(), undefined vs null, upsert / onConflict, and returning()

Section titled “insertInto().values(), undefined vs null, upsert / onConflict, and returning()”
  • Keys set to undefined are omitted so database DEFAULT values apply.
  • Keys set to null explicitly bind SQL NULL.
  • values([...]) accepts multi-row arrays (even with differing/reordered keys across objects).
// Single row: omit `role` (undefined -> DB default 'member'), set `nick` to SQL NULL
const ada = await db
.insertInto("users")
.values({
email: "ada@example.com",
name: "Ada",
nick: null,
role: undefined,
})
.returning("id", "email", "role", "nick")
.one();
// Multi-row upsert (SQLite & PostgreSQL; use .onDuplicateKeyUpdate() on MySQL/MariaDB)
const upserted = await db
.insertInto("users")
.values([
{ email: "ada@example.com", name: "Ada Lovelace", nick: "ada_l", active: 1 },
{ email: "grace@example.com", name: "Grace Hopper", nick: null, active: 1 },
])
.upsert(["email"], ["name", "nick"])
.returningAll()
.all();
// Ignore conflicts (ON CONFLICT DO NOTHING)
await db
.insertInto("users")
.values({ email: "ada@example.com", name: "Duplicate", nick: null, active: 1 })
.onConflict(["email"], { action: "ignore" })
.execute();

update().set() (PATCH Semantics) & deleteFrom() Mandatory WHERE Guard

Section titled “update().set() (PATCH Semantics) & deleteFrom() Mandatory WHERE Guard”
  • update().set({ ... }) skips undefined keys (PATCH semantics) and explicitly writes SQL NULL for null keys.
  • Both update() and deleteFrom() require a non-tautological .where(...) clause by default; omitting WHERE (or passing 1 = 1) rejects with DbError (code === "INVALID_PARAM", reason === "MissingWhereClause"). Call .unfiltered() explicitly when a full-table update or delete is intentional.
// PATCH update: `name` untouched, `nick` cleared to NULL, `role` updated
const updated = await db
.update("users")
.set({ name: undefined, nick: null, role: "admin" })
.where("id", ada.id)
.returning("id", "nick", "role")
.one();
// Explicit full-table mutation opt-in
await db.update("users").set("active", 1).unfiltered().execute();
// Delete with RETURNING (use .execute() on MySQL/MariaDB)
const deleted = await db
.deleteFrom("orders")
.where("status", "void")
.returning("id")
.all();

4. Safe sql Tagged Templates & Lossless Rich Types

Section titled “4. Safe sql Tagged Templates & Lossless Rich Types”

db.sql\…` & Composition Helpers (sql.ident, sql.col, sql.raw, sql.join`)

Section titled “db.sql\…` & Composition Helpers (sql.ident, sql.col, sql.raw, sql.join`)”

Interpolated values in db.sql\…`andsql`…`` are always bound as parameters — never string-concatenated:

import { sql } from "vael:db";
const ids = [1, 2, 3];
const minAge = 21;
const rows = await db.sql<{ id: number; name: string }>`
SELECT ${sql.col("u", "id")}, ${sql.ident("name")}
FROM users AS u
WHERE ${sql.col("u", "id")} IN (${sql.join(ids, ", ")})
AND age >= ${minAge}
ORDER BY ${sql.col("u", "id")} ASC
`.all();
// Validated expression fragment inside a fluent builder
// (sql.raw rejects semicolons and unbalanced parentheses; `?` count must match params.length)
const filtered = await db
.from("users")
.select("id", "name")
.where(sql.raw("age > ? AND age < ?", [20, 50]))
.all();

Raw positional (?) and named (@name) queries remain available via db.execute(sql, params), db.query(sql, params), and db.queryOne(sql, params). Mixing ? and @name in the same SQL statement is rejected with DbError (code === "PARAMETER").

Rich Type Parameters & Lossless Decode Rules

Section titled “Rich Type Parameters & Lossless Decode Rules”

Use the sql.* typed parameter constructors to bind UUIDs, dates, microsecond timestamps, exact base-10 decimals, and JSON payloads safely across dialects (including null for typed SQL NULL):

import { openSqlite, sql } from "vael:db";
await using db = await openSqlite(":memory:");
await db.execute(`
CREATE TABLE invoices (
id INTEGER PRIMARY KEY,
uid UUID NOT NULL,
issued_on DATE NOT NULL,
created_at TIMESTAMP NOT NULL,
settled_at TIMESTAMPTZ,
total DECIMAL NOT NULL,
meta JSON NOT NULL
)
`);
await db
.insertInto("invoices")
.values({
id: 1,
uid: sql.uuid("01234567-89ab-cdef-0123-456789abcdef"), // or 16-byte Uint8Array
issued_on: sql.date("2024-02-29"), // YYYY-MM-DD or Date
created_at: sql.timestamp("2024-02-29T12:34:56.125000"), // ISO-8601, Date, or bigint micros
settled_at: sql.timestampTz(new Date("2025-01-15T08:00:00.250Z")),
total: sql.decimal("999999999999999999.123456789"), // exact string, finite number, or bigint
meta: sql.json({ currency: "USD", tags: ["priority"] }), // any JSON value except undefined
})
.execute();
const row = await db.from("invoices").where("id", 1).one();

Lossless decode rules when rows return to JavaScript:

SQL Type Returned JS Value Notes
UUID Canonical lowercase hyphenated string e.g. "01234567-89ab-cdef-0123-456789abcdef"
DATE ISO-8601 string (YYYY-MM-DD) Validated calendar date
TIMESTAMP ISO-8601 string (microsecond precision) e.g. "2024-02-29T12:34:56.125000"
TIMESTAMPTZ UTC ISO-8601 string ending in Z e.g. "2025-01-15T08:00:00.250000Z"
DECIMAL Exact base-10 string Preserves arbitrary decimal precision without IEEE-754 rounding
JSON Parsed JS value (JSON.parse) Returns null when the SQL column is NULL
i64 integer number or bigint number within [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], bigint outside
BLOB Uint8Array Raw binary bytes

5. Transactions & Nested Savepoints (tx.savepoint)

Section titled “5. Transactions & Nested Savepoints (tx.savepoint)”

db.transaction(fn) acquires one connection, runs BEGIN, commits on resolve, and rolls back on throw/reject. Inside a transaction, use tx.savepoint(name, fn) for nested partial rollbacks (SAVEPOINT -> RELEASE on resolve, ROLLBACK TO + RELEASE on reject):

await db.transaction(async (tx) => {
await tx.insertInto("users").values({ email: "outer@example.com", name: "Outer" }).execute();
try {
await tx.savepoint("optional_step", async (sp) => {
await sp.insertInto("users").values({ email: "inner@example.com", name: "Inner" }).execute();
throw new Error("abort inner savepoint only");
});
} catch {
// Only `optional_step` was rolled back; outer transaction remains active
}
// Sequential or nested `sp.savepoint(...)` calls are supported.
await tx.savepoint("audit_step", async (sp) => {
await sp.sql`UPDATE users SET role = ${"audited"} WHERE email = ${"outer@example.com"}`.execute();
});
});

Transaction & savepoint guards:

  • Calling tx.transaction() or tx.close() directly on a Transaction handle rejects with DbError (code === "SQL").
  • Overlapping concurrent tx.savepoint() calls on the same handle reject with DbError (code === "SQL"). Always await sequential savepoints or nest via sp.savepoint(...) on the child handle.
  • Reusing a tx or sp handle after its callback settles rejects with DbError (code === "CLOSED").

6. Programmatic Migrations (vael:db/migrate)

Section titled “6. Programmatic Migrations (vael:db/migrate)”

vael:db/migrate loads, validates, dry-run plans, applies, reverts, verifies, flattens, and reconciles SQL migrations. Both authoring layouts are supported (versions must be sequential positive integers >= 1):

  1. Paired files: 0001_init.up.sql and optional 0001_init.down.sql
  2. Single file: 0002_items.sql containing -- migrate:up followed by optional -- migrate:down
import { openSqlite } from "vael:db";
import { down, flatten, loadMigrations, plan, reconcile, status, up, verify } from "vael:db/migrate";
await using db = await openSqlite("./app.db");
// Optional: inspect and bind {{identifier}} placeholders eagerly
const loaded = await loadMigrations("./migrations", {
bindings: { app_schema: "public" },
dialect: db.dialect,
});
// Read-only status & dry-run plan (never creates ledger tables)
const st = await status(db, loaded);
console.log("Current version:", st.currentVersion, "Pending:", st.pending.length);
if (st.pending.length > 0) {
const dryRun = await plan(db, loaded, { direction: "up", step: 1 });
console.log("Planned SQL:", dryRun.steps[0]?.sql);
// Apply migrations and verify ledger consistency
const applied = await up(db, loaded);
console.log("Head version:", applied.currentVersion);
}
await verify(loaded, db);
// Roll back 1 migration explicitly (defaults to step: 1; never rolls back all implicitly)
await down(db, loaded, { step: 1 });
  • flatten(target, { migrations, baseline, legacyMaxVersion }) compacts an exact applied legacy history into an irreversible baseline on SQLite or PostgreSQL.
  • reconcile(target, { migrations, outcome: "applied" | "reverted" }) clears a dirty ledger marker on MySQL/MariaDB after manual operator inspection.

7. CLI Migrations (vjs db migrate) & vael.jsonc "db" Config

Section titled “7. CLI Migrations (vjs db migrate) & vael.jsonc "db" Config”

Configure non-secret database and migration defaults in vael.jsonc under "db" — never store plaintext passwords or URLs with credentials (the manifest parser rejects "password", "url", and ://user:pass@ with SecretInManifest):

vael.jsonc
{
"name": "@acme/billing-service",
"exports": { ".": "./src/main.ts" },
"db": {
"driver": "postgres",
"host": "db.internal.example",
"port": 5432,
"database": "billing",
"user": "migrator",
"passwordEnv": "PG_PASSWORD",
"tlsMode": "verifyFull",
"caFile": "./certs/internal-ca.pem",
"migrationsDir": "./migrations",
"table": "_vael_migrations",
"schema": "public",
"module": "billing",
"lockTimeoutMs": 30000,
"bindings": { "app_schema": "billing" }
}
}

Common vjs db migrate workflow:

Terminal window
# 1. Scaffold sequential migration files (0001_create_users.up.sql + .down.sql)
vjs db migrate new create_users
# 2. Verify local migration files offline in CI
vjs db migrate verify --offline
# 3. Inspect ledger state and preview SQL before applying
vjs db migrate status
vjs db migrate plan --show-sql
# 4. Apply pending migrations (or limit with --step / --to)
vjs db migrate up
vjs db migrate down --step 1
# 5. Explicit destructive / maintenance operations (require --yes)
vjs db migrate reset --yes
vjs db migrate flatten --baseline ./migrations/0001_baseline.up.sql --baseline-version 1 --yes
vjs db migrate reconcile --outcome applied --yes

See Commands & Flags for all flags, environment variables (VAELJS_DB_URL, DATABASE_URL, VAELJS_DB_PASSWORD, etc.), secret-hygiene rules, and exit codes.

DbError never leaks passwords, connection strings, or raw filesystem paths in error messages or properties. Inspect err.code, optional err.databaseKind, err.reason, and err.constraintKind:

import { DbError, openSqlite } from "vael:db";
await using db = await openSqlite(":memory:");
await db.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE)");
await db.execute("INSERT INTO users (email) VALUES (?)", ["a@example.com"]);
try {
await db.queryOne("SELECT id FROM users");
await db.execute("INSERT INTO users (email) VALUES (?)", ["a@example.com"]);
} catch (err) {
if (err instanceof DbError) {
console.error("DB error:", err.code, err.databaseKind, err.reason, err.constraintKind);
} else {
throw err;
}
}