default

Examples

Basic query with Task semantics

import { DB, createInMemory } from "@anabranch/db";

const users = await DB.withConnection(createInMemory(), (db) =>
  db.query("SELECT * FROM users WHERE active = ?", [true])
).run();

Streaming large result sets with error collection

import { DB, createInMemory } from "@anabranch/db";

const { successes, errors } = await DB.withConnection(createInMemory(), (db) =>
  db.stream("SELECT * FROM large_table")
    .withConcurrency(10)
    .map(row => processRow(row))
    .partition()
).run();

Transactions with automatic rollback on error

import { DB, ConstraintViolation, createInMemory } from "@anabranch/db";

const result = await DB.withConnection(createInMemory(), (db) =>
  db.withTransaction(async (tx) => {
    await tx.execute("INSERT INTO orders (user_id) VALUES (?)", [userId]);
    await tx.execute("UPDATE users SET order_count = order_count + 1 WHERE id = ?", [userId]);
    return tx.query("SELECT last_insert_rowid()");
  })
).recoverWhen(
  (e) => e instanceof ConstraintViolation,
  (e) => ({ id: 0, error: e.message })
).run();

Retry with exponential backoff

import { DB } from "@anabranch/db";
import { createPostgres } from "@anabranch/db-postgres";

const users = await DB.withConnection(createPostgres(), (db) =>
  db.query("SELECT * FROM users")
    .retry({ attempts: 3, delay: (attempt) => 100 * Math.pow(2, attempt) })
).run();

Pub/sub with in-memory connector (swap for createPostgres in production)

import { createInMemory } from "@anabranch/db";

const connector = createInMemory();
const ch = await connector.listen("orders").run();

await connector.notify("orders", JSON.stringify({ id: 1 })).run();

for await (const n of ch.successes()) {
  console.log(n.payload);
}

Classes

c
CloseError(message: string)

Failed to close the database connection.

c
ConnectionFailed(message: string)

Failed to establish a database connection.

c
ConstraintViolation(
sql: string,
message: string
)

Constraint violation (e.g., unique, foreign key).

c
DB(adapter: DBAdapter)

Database wrapper with Task/Stream semantics.

c
ListenFailed(message: string)

Failed to establish or maintain a pub/sub subscription.

c
SerializationFailure(message?: string)

Serialization failure (concurrent modification detected).

Functions

Interfaces

I
DBAdapter

Database adapter interface for DB-agnostic operations.

I
DBConnector

Connector that produces connected DBAdapter instances.

I
DBTransactionAdapter

Transaction adapter interface.

Type Aliases

T
Notification = { channel: string; payload: string; }

A notification received from a pub/sub channel.

Variables