Move docs/ package mirror into document-navigator plugin
Relocate the ~6k-file docs tree from the repo root into plugins/document-navigator/docs/ so the plugin is self-contained and portable. docs/superpowers/ (specs and plans) stays at the repo root. Moved via cp+rm rather than git mv because directory rename() fails with EPERM on this WSL /mnt DrvFs mount; git rename-detection pairs the identical-content files at commit time. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
# DatabaseAdapter
|
||||
|
||||
<!-- begin:auto-docs -->
|
||||
_(no submodules)_
|
||||
<!-- end:auto-docs -->
|
||||
## Purpose
|
||||
|
||||
`DatabaseAdapter` is the full database connection contract for `@suaveplan/db`. It extends `DatabaseLike` from `@suaveplan/types` (the minimal DI interface used by packages that inject a database without depending on a concrete driver) and adds lifecycle management, migration support, and `AbortSignal` propagation on every async entrypoint. Concrete adapters — `@suaveplan/db-sqlite`, future Postgres and Turso adapters — implement this interface.
|
||||
|
||||
Keeping `DatabaseLike` as the base means any `DatabaseAdapter` can be passed wherever a `DatabaseLike` is expected, enabling clean dependency injection across the project without introducing circular dependencies between domain packages and their database layer.
|
||||
|
||||
## Features
|
||||
|
||||
- Extends `DatabaseLike` — structurally compatible with the minimal DI interface
|
||||
- `connect` / `disconnect` lifecycle with optional `DatabaseConfig`
|
||||
- `query<T>` — typed SELECT, returns `T[]`
|
||||
- `execute` — INSERT / UPDATE / DELETE / DDL, returns `{ rowsAffected: number }`
|
||||
- `transaction<T>` — callback receives active `DatabaseLike` tx handle; auto-commit / auto-rollback
|
||||
- `migrate` — delegates to a `MigrationRunner`; accepts optional `MigrationConfig`
|
||||
- `isConnected` — boolean state predicate; checked by singleton helpers before reconnecting
|
||||
- `AbortSignal` on every async method via `DbOperationOptions`
|
||||
- `close()` alias from `DatabaseLike` — concrete adapters may implement as `this.disconnect()`
|
||||
|
||||
## Usage: Basic Example
|
||||
|
||||
```ts
|
||||
import type { DatabaseAdapter } from "@suaveplan/db";
|
||||
|
||||
class SqliteAdapter implements DatabaseAdapter {
|
||||
#connected = false;
|
||||
get isConnected() { return this.#connected; }
|
||||
|
||||
async connect(config?) { /* open bun:sqlite */ this.#connected = true; }
|
||||
async disconnect() { /* close */ this.#connected = false; }
|
||||
async close() { await this.disconnect(); }
|
||||
|
||||
async query<T>(sql, params?) { /* ... */ return [] as T[]; }
|
||||
async execute(sql, params?) { return { rowsAffected: 0 }; }
|
||||
async transaction(fn) { return fn(this); }
|
||||
async migrate(config?) { return { applied: 0, migrations: [] }; }
|
||||
}
|
||||
```
|
||||
|
||||
## Usage: Advanced Example
|
||||
|
||||
```ts
|
||||
import { getSingleton, DB_CODES, DatabaseError } from "@suaveplan/db";
|
||||
import { SqliteAdapter } from "@suaveplan/db-sqlite";
|
||||
|
||||
// Register a named singleton with an isolated registry (safe in tests)
|
||||
const reg = new Map();
|
||||
const db = await getSingleton(
|
||||
"app",
|
||||
() => new SqliteAdapter({ filename: "./app.db" }),
|
||||
undefined,
|
||||
undefined,
|
||||
reg
|
||||
);
|
||||
|
||||
// Abort a long-running query
|
||||
const ac = new AbortController();
|
||||
setTimeout(() => ac.abort(), 5_000);
|
||||
|
||||
try {
|
||||
const rows = await db.query<{ id: number }>(
|
||||
"SELECT id FROM events WHERE ts > ?",
|
||||
[Date.now() - 86_400_000],
|
||||
{ signal: ac.signal }
|
||||
);
|
||||
} catch (err) {
|
||||
if (err instanceof DatabaseError && err.code === DB_CODES.QUERY_FAILED) {
|
||||
console.error("query failed", err.message);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### `DatabaseAdapter`
|
||||
|
||||
Extends `DatabaseLike`.
|
||||
|
||||
| Method | Signature | Description |
|
||||
|---|---|---|
|
||||
| `connect` | `(config?, opts?) => Promise<void>` | Open the connection |
|
||||
| `disconnect` | `(opts?) => Promise<void>` | Close and release resources |
|
||||
| `close` | `() => Promise<void>` | `DatabaseLike` alias for `disconnect` |
|
||||
| `query<T>` | `(sql, params?, opts?) => Promise<T[]>` | Typed SELECT |
|
||||
| `execute` | `(sql, params?, opts?) => Promise<{ rowsAffected }>` | DML/DDL |
|
||||
| `transaction<T>` | `(fn, opts?) => Promise<T>` | Auto-commit/rollback |
|
||||
| `migrate` | `(config?, opts?) => Promise<MigrationResult>` | Apply pending migrations |
|
||||
| `isConnected` | `boolean` (readonly) | Connection state |
|
||||
|
||||
### `DbOperationOptions`
|
||||
|
||||
```ts
|
||||
interface DbOperationOptions {
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
```
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
The `transaction` callback signature uses `DatabaseLike` (not `DatabaseAdapter`) so implementations can pass a lightweight transaction handle that exposes only `query`/`execute`/`transaction`/`close` without the lifecycle methods. This matches how ORMs typically expose transaction objects and avoids callers calling `connect` or `migrate` on a transaction handle.
|
||||
|
||||
`disconnect` and `close` serve the same purpose — `disconnect` is the richer signature (accepts `DbOperationOptions`); `close` is the `DatabaseLike`-compatible alias with no arguments. Concrete adapters typically implement `disconnect` and delegate `close` to it.
|
||||
@@ -0,0 +1,120 @@
|
||||
# Connection Singletons
|
||||
|
||||
<!-- begin:auto-docs -->
|
||||
_(no submodules)_
|
||||
<!-- end:auto-docs -->
|
||||
## Purpose
|
||||
|
||||
`getSingleton`, `closeSingleton`, `hasSingleton`, and `closeAllSingletons` provide a lightweight singleton registry for `DatabaseAdapter` instances. The primary purpose is to avoid opening multiple connections to the same database within a single process — `getSingleton` is idempotent: the first call creates and connects the adapter, subsequent calls with the same name return the cached reference without reconnecting.
|
||||
|
||||
By accepting an optional `registry` parameter (a plain `Map<string, DatabaseAdapter>`), the helpers are safe for test isolation: each test suite can pass its own private map and have zero cross-test bleed. In production, omitting `registry` uses a module-level default map, replicating the familiar global-singleton pattern without requiring any global state management from callers.
|
||||
|
||||
## Features
|
||||
|
||||
- Idempotent `getSingleton` — second call with same name returns cached adapter
|
||||
- `DatabaseConfigSchema` validation before `connect` is called
|
||||
- Wraps `connect` failures as `DatabaseError` with `DB.CONNECTION_FAILED`
|
||||
- `closeSingleton` — graceful disconnect + registry removal (no-op for unknown names)
|
||||
- `closeAllSingletons` — drains the entire registry; collects disconnect errors into `AggregateError`
|
||||
- Injectable `registry` parameter — full test isolation without global state
|
||||
- `AbortSignal` threading via `DbOperationOptions`
|
||||
|
||||
## Usage: Basic Example
|
||||
|
||||
```ts
|
||||
import { getSingleton, closeSingleton } from "@suaveplan/db";
|
||||
import { SqliteAdapter } from "@suaveplan/db-sqlite";
|
||||
|
||||
// Get or create the default "app" connection
|
||||
const db = await getSingleton("app", () => new SqliteAdapter({ filename: "./app.db" }));
|
||||
|
||||
const rows = await db.query<{ id: number }>("SELECT id FROM users");
|
||||
|
||||
// Clean up at process exit
|
||||
await closeSingleton("app");
|
||||
```
|
||||
|
||||
## Usage: Advanced Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
getSingleton,
|
||||
closeAllSingletons,
|
||||
hasSingleton,
|
||||
} from "@suaveplan/db";
|
||||
import type { DatabaseAdapter } from "@suaveplan/db";
|
||||
|
||||
// Test-isolated registry — no cross-test bleed
|
||||
const testRegistry = new Map<string, DatabaseAdapter>();
|
||||
|
||||
beforeEach(async () => {
|
||||
await getSingleton(
|
||||
"test-db",
|
||||
() => new SqliteAdapter({ filename: ":memory:" }),
|
||||
undefined,
|
||||
undefined,
|
||||
testRegistry
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await closeAllSingletons(undefined, testRegistry);
|
||||
});
|
||||
|
||||
it("has singleton after setup", () => {
|
||||
expect(hasSingleton("test-db", testRegistry)).toBe(true);
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### `getSingleton`
|
||||
|
||||
```ts
|
||||
getSingleton(
|
||||
name: string,
|
||||
factory: () => DatabaseAdapter,
|
||||
config?: Partial<DatabaseConfig>,
|
||||
opts?: DbOperationOptions,
|
||||
registry?: Map<string, DatabaseAdapter>
|
||||
): Promise<DatabaseAdapter>
|
||||
```
|
||||
|
||||
Returns the cached adapter for `name`, or creates one via `factory`, validates `config`, connects it, and caches it. Throws `DatabaseError(DB.CONNECTION_FAILED)` if `connect` fails.
|
||||
|
||||
### `closeSingleton`
|
||||
|
||||
```ts
|
||||
closeSingleton(
|
||||
name: string,
|
||||
opts?: DbOperationOptions,
|
||||
registry?: Map<string, DatabaseAdapter>
|
||||
): Promise<void>
|
||||
```
|
||||
|
||||
Calls `disconnect` on the named adapter and removes it from the registry. No-op if `name` is not registered.
|
||||
|
||||
### `hasSingleton`
|
||||
|
||||
```ts
|
||||
hasSingleton(name: string, registry?: Map<string, DatabaseAdapter>): boolean
|
||||
```
|
||||
|
||||
Returns `true` if an adapter is registered under `name`.
|
||||
|
||||
### `closeAllSingletons`
|
||||
|
||||
```ts
|
||||
closeAllSingletons(
|
||||
opts?: DbOperationOptions,
|
||||
registry?: Map<string, DatabaseAdapter>
|
||||
): Promise<void>
|
||||
```
|
||||
|
||||
Clears the registry immediately, then disconnects all adapters concurrently. If one or more disconnects fail, an `AggregateError` is thrown after all attempts complete.
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
The registry is cleared before `disconnect` is called in `closeAllSingletons`. This ensures that even if a `disconnect` rejects, the registry is empty and a subsequent `getSingleton` call will create a fresh adapter rather than returning a half-closed one. The AggregateError is thrown after all disconnect attempts so callers get complete failure information rather than a short-circuit on the first error.
|
||||
|
||||
Config validation uses `DatabaseConfigSchema.parse` (not `.safeParse`) so invalid config throws a `ZodError` immediately — fail-fast at the boundary is preferable to a cryptic driver-level error.
|
||||
@@ -0,0 +1,107 @@
|
||||
# DatabaseError / MigrationError
|
||||
|
||||
<!-- begin:auto-docs -->
|
||||
_(no submodules)_
|
||||
<!-- end:auto-docs -->
|
||||
## Purpose
|
||||
|
||||
`DatabaseError` is the structured error class for all database failures in `@suaveplan/db`. It extends `SuaveplanError` from `@suaveplan/error`, ensuring every database error carries a stable, machine-readable `DB.*` code alongside a human-readable message and optional cause chain. `MigrationError` is a specialisation that records which named migration failed.
|
||||
|
||||
Using `SuaveplanError` as the base means consumers can perform type-safe `instanceof` checks, extract OTel-compatible codes from `error.code`, and inspect cause chains consistently across the entire Suaveplan project.
|
||||
|
||||
## Features
|
||||
|
||||
- Extends `SuaveplanError<DbCode>` — participates in the project-wide error hierarchy
|
||||
- Stable `DB.*` codes registered via `defineCodes` — never change between versions
|
||||
- `cause` threading — wraps lower-level driver errors without losing the original stack
|
||||
- `MigrationError.migration` field — names the exact migration file that failed
|
||||
- `name` property set to the concrete class name for easy identification in logs
|
||||
|
||||
## Usage: Basic Example
|
||||
|
||||
```ts
|
||||
import { DatabaseError, MigrationError, DB_CODES } from "@suaveplan/db";
|
||||
|
||||
// Throw a connection failure
|
||||
throw new DatabaseError(
|
||||
DB_CODES.CONNECTION_FAILED,
|
||||
"Could not reach postgres://localhost:5432/app"
|
||||
);
|
||||
|
||||
// Throw a migration failure
|
||||
throw new MigrationError("003_add_index", "duplicate column name: email");
|
||||
```
|
||||
|
||||
## Usage: Advanced Example
|
||||
|
||||
```ts
|
||||
import { DatabaseError, DB_CODES } from "@suaveplan/db";
|
||||
import { SuaveplanError } from "@suaveplan/error";
|
||||
|
||||
async function runQuery(sql: string): Promise<unknown[]> {
|
||||
try {
|
||||
return await driver.query(sql);
|
||||
} catch (cause) {
|
||||
throw new DatabaseError(
|
||||
DB_CODES.QUERY_FAILED,
|
||||
`Query failed: ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
{ cause: cause instanceof Error ? cause : undefined }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Narrowing in catch blocks
|
||||
try {
|
||||
await runQuery("SELECT * FROM users");
|
||||
} catch (err) {
|
||||
if (err instanceof DatabaseError) {
|
||||
console.error(err.code, err.message); // "DB.QUERY_FAILED Query failed: ..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### `DatabaseError`
|
||||
|
||||
```ts
|
||||
class DatabaseError extends SuaveplanError<DbCode> {
|
||||
constructor(code: DbCode, message: string, options?: SuaveplanErrorOptions): void
|
||||
}
|
||||
```
|
||||
|
||||
- **`code`** (`DbCode`) — one of `DB.CONNECTION_FAILED`, `DB.NOT_CONNECTED`, `DB.QUERY_FAILED`, `DB.TRANSACTION_FAILED`, `DB.MIGRATION_FAILED`
|
||||
- **`message`** (`string`) — human-readable description
|
||||
- **`options.cause`** (`Error | undefined`) — lower-level error that triggered this one
|
||||
|
||||
### `MigrationError`
|
||||
|
||||
```ts
|
||||
class MigrationError extends DatabaseError {
|
||||
readonly migration: string;
|
||||
constructor(migration: string, detail: string, options?: SuaveplanErrorOptions): void
|
||||
}
|
||||
```
|
||||
|
||||
- **`migration`** (`string`) — the migration name (e.g. `"001_init"`)
|
||||
- **`detail`** (`string`) — description of what went wrong
|
||||
- Message format: `"Migration '<migration>' failed: <detail>"`
|
||||
- Code is always `DB.MIGRATION_FAILED`
|
||||
|
||||
### `DB_CODES`
|
||||
|
||||
```ts
|
||||
const DB_CODES: {
|
||||
readonly CONNECTION_FAILED: "DB.CONNECTION_FAILED";
|
||||
readonly NOT_CONNECTED: "DB.NOT_CONNECTED";
|
||||
readonly QUERY_FAILED: "DB.QUERY_FAILED";
|
||||
readonly TRANSACTION_FAILED:"DB.TRANSACTION_FAILED";
|
||||
readonly MIGRATION_FAILED: "DB.MIGRATION_FAILED";
|
||||
}
|
||||
```
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
Both classes pass the `message` string directly to `SuaveplanError` as a literal message key rather than an i18n key, so no message-resolver configuration is required. This keeps `@suaveplan/db` dependency-free of any i18n infrastructure. If localisation is needed in a future version, the message key can be replaced with an i18n key and the `context` option used for interpolation.
|
||||
|
||||
`MigrationError` explicitly sets `this.name = "MigrationError"` in the constructor because `SuaveplanError` sets `this.name = new.target.name` — the explicit assignment in the subclass constructor ensures the name is accurate when the class is transpiled or minified.
|
||||
@@ -0,0 +1,101 @@
|
||||
# MigrationRunner
|
||||
|
||||
<!-- begin:auto-docs -->
|
||||
_(no submodules)_
|
||||
<!-- end:auto-docs -->
|
||||
## Purpose
|
||||
|
||||
`MigrationRunner` is the interface that `DatabaseAdapter.migrate` delegates to in concrete adapter implementations. Separating the migration contract from the adapter contract lets adapters swap migration strategies without changing their top-level API — for example, a SQLite adapter might use Drizzle's migration runner while a SurrealDB adapter uses a custom `.surql` file runner, yet both expose the same `DatabaseAdapter.migrate` signature to callers.
|
||||
|
||||
The three-method design mirrors the principle of least surprise: `pendingMigrations` is a read-only query (safe to call for status checks without making changes), `applyMigration` is the atomic unit of work, and `run` is the high-level orchestrator that wires them together.
|
||||
|
||||
## Features
|
||||
|
||||
- `pendingMigrations` — read-only: lists unapplied migrations without side effects
|
||||
- `applyMigration` — atomic unit: applies a single named migration by SQL string
|
||||
- `run` — orchestrator: discovers, orders, and applies all pending migrations
|
||||
- `MigrationError` — thrown with the exact migration name on failure
|
||||
- `AbortSignal` on both `applyMigration` and `run` via `DbOperationOptions`
|
||||
- Accepts optional `MigrationConfig` to override folder/table defaults
|
||||
|
||||
## Usage: Basic Example
|
||||
|
||||
```ts
|
||||
import type { MigrationRunner } from "@suaveplan/db";
|
||||
import { MigrationError } from "@suaveplan/db";
|
||||
|
||||
class FileMigrationRunner implements MigrationRunner {
|
||||
async pendingMigrations(config?) {
|
||||
const applied = await this.loadApplied(config);
|
||||
const all = await this.discoverFiles(config);
|
||||
return all
|
||||
.filter(m => !applied.has(m.name))
|
||||
.map(m => ({ name: m.name, applied: false }));
|
||||
}
|
||||
|
||||
async applyMigration(name, sql, opts?) {
|
||||
try {
|
||||
await this.db.execute(sql, [], opts);
|
||||
await this.recordApplied(name);
|
||||
} catch (err) {
|
||||
throw new MigrationError(name, err instanceof Error ? err.message : String(err), { cause: err });
|
||||
}
|
||||
}
|
||||
|
||||
async run(config?, opts?) {
|
||||
const pending = await this.pendingMigrations(config);
|
||||
const names: string[] = [];
|
||||
for (const { name } of pending) {
|
||||
const sql = await this.loadSql(name, config);
|
||||
await this.applyMigration(name, sql, opts);
|
||||
names.push(name);
|
||||
}
|
||||
return { applied: names.length, migrations: names };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Usage: Advanced Example
|
||||
|
||||
```ts
|
||||
import type { MigrationRunner } from "@suaveplan/db";
|
||||
import { MigrationError, withDbSpan } from "@suaveplan/db";
|
||||
|
||||
// Wrapping run with OTel tracing
|
||||
async function runMigrations(runner: MigrationRunner): Promise<void> {
|
||||
const result = await withDbSpan("db.migrate", () =>
|
||||
runner.run({ migrationsFolder: "./db/migrations" })
|
||||
);
|
||||
console.log(`Applied ${result.applied} migration(s):`, result.migrations);
|
||||
}
|
||||
|
||||
// Status check without applying
|
||||
async function checkMigrationStatus(runner: MigrationRunner): Promise<void> {
|
||||
const pending = await runner.pendingMigrations();
|
||||
if (pending.length > 0) {
|
||||
console.warn(`${pending.length} unapplied migrations:`, pending.map(m => m.name));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### `MigrationRunner`
|
||||
|
||||
```ts
|
||||
interface MigrationRunner {
|
||||
pendingMigrations(config?: MigrationConfig): Promise<MigrationStatus[]>;
|
||||
applyMigration(name: string, sql: string, opts?: DbOperationOptions): Promise<void>;
|
||||
run(config?: MigrationConfig, opts?: DbOperationOptions): Promise<MigrationResult>;
|
||||
}
|
||||
```
|
||||
|
||||
- **`pendingMigrations`** — returns only unapplied migrations; never mutates state
|
||||
- **`applyMigration`** — applies one migration; throws `MigrationError` on failure with the migration's name in `error.migration`
|
||||
- **`run`** — discovers pending migrations via `pendingMigrations` and applies them in order via `applyMigration`; returns aggregate `MigrationResult`
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
`MigrationRunner` is intentionally an interface rather than an abstract class. This keeps the dependency graph clean — the runner itself has no implementation, so it imposes no runtime cost. Concrete adapters in `@suaveplan/db-sqlite` and future packages supply the implementation.
|
||||
|
||||
The `AbortSignal` is only threaded through `applyMigration` and `run` — `pendingMigrations` is a read-only operation and is not expected to take long enough to warrant cancellation in typical use cases. Implementors may add signal support to `pendingMigrations` as a non-breaking extension.
|
||||
@@ -0,0 +1,97 @@
|
||||
# OTel Instruments
|
||||
|
||||
## Purpose
|
||||
|
||||
`instruments.ts` provides lazily-initialised OpenTelemetry metric instruments for `@suaveplan/db`. Rather than creating meters at module load time (which would execute OTel SDK code before any SDK is registered and could silently fail), instruments are created on first use via a module-level singleton guard. This ensures the package works correctly both when an OTel SDK exporter is configured and when it is not — in the latter case, the OTel no-op provider handles all calls without errors.
|
||||
|
||||
Four instruments cover the core observability surface: query/execute latency, connection lifecycle, transaction outcomes, and migration counts.
|
||||
|
||||
## Features
|
||||
|
||||
- Lazy initialisation — OTel meter created on first call, not at module load
|
||||
- `resetInstruments()` — clears the singleton for test isolation
|
||||
- `recordQueryDuration(ms, operation)` — histogram labelled by `db.operation`
|
||||
- `recordConnectionDelta(±1, dbName)` — UpDownCounter labelled by `db.name`
|
||||
- `recordTransaction(outcome)` — counter labelled by `db.outcome`
|
||||
- `recordMigration(name)` — counter labelled by `db.migration.name`
|
||||
- Works with no-op OTel provider — safe when no SDK is configured
|
||||
|
||||
## Usage: Basic Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
recordQueryDuration,
|
||||
recordConnectionDelta,
|
||||
} from "@suaveplan/db/telemetry/instruments";
|
||||
|
||||
// In a concrete adapter's connect():
|
||||
recordConnectionDelta(1, "main");
|
||||
|
||||
// In a concrete adapter's query():
|
||||
const start = performance.now();
|
||||
const rows = await driver.query(sql);
|
||||
recordQueryDuration(performance.now() - start, "query");
|
||||
```
|
||||
|
||||
## Usage: Advanced Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
recordTransaction,
|
||||
recordMigration,
|
||||
resetInstruments,
|
||||
} from "@suaveplan/db/telemetry/instruments";
|
||||
|
||||
// In a concrete adapter's transaction():
|
||||
let outcome: "committed" | "rolled_back" = "rolled_back";
|
||||
try {
|
||||
await fn(tx);
|
||||
outcome = "committed";
|
||||
} finally {
|
||||
recordTransaction(outcome);
|
||||
}
|
||||
|
||||
// In a migration runner after each applied migration:
|
||||
recordMigration("003_add_index");
|
||||
|
||||
// In tests — reset between test runs to avoid state leak:
|
||||
beforeEach(() => resetInstruments());
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### `recordQueryDuration(durationMs, operation)`
|
||||
|
||||
Records a query or execute duration.
|
||||
|
||||
- `durationMs` — elapsed time in milliseconds
|
||||
- `operation` — `"query"` or `"execute"`
|
||||
|
||||
### `recordConnectionDelta(delta, dbName)`
|
||||
|
||||
Adjusts the active connection count.
|
||||
|
||||
- `delta` — `1` on connect, `-1` on disconnect
|
||||
- `dbName` — logical name of the database (used as the `db.name` attribute)
|
||||
|
||||
### `recordTransaction(outcome)`
|
||||
|
||||
Increments the transaction counter.
|
||||
|
||||
- `outcome` — `"committed"` or `"rolled_back"`
|
||||
|
||||
### `recordMigration(migrationName)`
|
||||
|
||||
Increments the migration counter.
|
||||
|
||||
- `migrationName` — the name of the applied migration file
|
||||
|
||||
### `resetInstruments()`
|
||||
|
||||
Clears the cached instruments singleton. Useful in unit tests to avoid state from a prior test bleeding into subsequent ones.
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
The instruments singleton guard uses an `undefined` check rather than a lazy initialiser class so there is no closure overhead — the check is a single `!== undefined` comparison per call. The `metrics.getMeter("@suaveplan/db")` call is safe under the OTel no-op provider because it returns a no-op meter whose `createHistogram`, `createUpDownCounter`, and `createCounter` methods all return no-op instruments that silently discard all data.
|
||||
|
||||
`recordQueryDuration` uses a histogram (not a counter) so downstream dashboards can compute percentiles — P50/P95/P99 query latency is far more useful than a total call count for diagnosing slow queries.
|
||||
@@ -0,0 +1,76 @@
|
||||
# withDbSpan
|
||||
|
||||
## Purpose
|
||||
|
||||
`withDbSpan` is a thin OTel tracing helper that wraps any async database operation in a named span. It handles the boilerplate of starting a span, setting its status on success or error, recording exceptions, and always ending the span — so concrete adapters and migration runners can add tracing with a single wrapper call rather than repeating the span lifecycle pattern in every method.
|
||||
|
||||
Like the instruments module, `withDbSpan` relies on the OTel no-op tracer when no SDK is configured, so it is safe to call in any environment including tests with no OTel setup.
|
||||
|
||||
## Features
|
||||
|
||||
- Creates a named span via `trace.getTracer("@suaveplan/db")`
|
||||
- Sets `SpanStatusCode.OK` on successful completion
|
||||
- Sets `SpanStatusCode.ERROR` and records the exception on throw
|
||||
- Always ends the span (via `finally`) — no span leaks
|
||||
- Accepts optional `Attributes` for span metadata (e.g. `db.name`, `db.operation`)
|
||||
- Works with the OTel no-op provider — zero overhead when no exporter is registered
|
||||
|
||||
## Usage: Basic Example
|
||||
|
||||
```ts
|
||||
import { withDbSpan } from "@suaveplan/db/telemetry/trace";
|
||||
|
||||
const rows = await withDbSpan("db.query", async () => {
|
||||
return driver.query("SELECT * FROM users");
|
||||
});
|
||||
```
|
||||
|
||||
## Usage: Advanced Example
|
||||
|
||||
```ts
|
||||
import { withDbSpan } from "@suaveplan/db/telemetry/trace";
|
||||
|
||||
// With span attributes for richer trace data
|
||||
const result = await withDbSpan(
|
||||
"db.execute",
|
||||
async () => driver.execute("DELETE FROM sessions WHERE expires_at < ?", [Date.now()]),
|
||||
{
|
||||
"db.name": "app",
|
||||
"db.operation": "execute",
|
||||
"db.statement": "DELETE FROM sessions",
|
||||
}
|
||||
);
|
||||
|
||||
// Wrapping a full transaction
|
||||
const transferResult = await withDbSpan("db.transaction.transfer", async () => {
|
||||
return adapter.transaction(async (tx) => {
|
||||
await tx.execute("UPDATE accounts SET balance = balance - ? WHERE id = ?", [100, "sender"]);
|
||||
await tx.execute("UPDATE accounts SET balance = balance + ? WHERE id = ?", [100, "receiver"]);
|
||||
return { ok: true };
|
||||
});
|
||||
}, { "transfer.amount": 100 });
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### `withDbSpan<T>`
|
||||
|
||||
```ts
|
||||
withDbSpan<T>(
|
||||
name: string,
|
||||
fn: () => Promise<T>,
|
||||
attrs?: Attributes
|
||||
): Promise<T>
|
||||
```
|
||||
|
||||
- **`name`** — OTel span name (e.g. `"db.query"`, `"db.migrate"`)
|
||||
- **`fn`** — async function to execute inside the span
|
||||
- **`attrs`** — optional `Attributes` map attached to the span at creation time
|
||||
- **Returns** — the resolved value of `fn()`
|
||||
- **Throws** — re-throws whatever `fn()` throws after recording the exception on the span
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
`withDbSpan` uses the module-level `tracer` constant (created once at import time via `trace.getTracer("@suaveplan/db")`) rather than calling `getTracer` on every invocation. The OTel spec guarantees that `getTracer` with the same name returns the same tracer instance, so this is a safe optimisation.
|
||||
|
||||
Non-Error thrown values (e.g. strings, numbers) are wrapped in `new Error(String(err))` before being passed to `span.recordException`. This satisfies the OTel SDK's type requirement for `recordException` while still re-throwing the original value, so callers that catch strings continue to work as before.
|
||||
@@ -0,0 +1,117 @@
|
||||
# DatabaseConfig / MigrationConfig
|
||||
|
||||
<!-- begin:auto-docs -->
|
||||
_(no submodules)_
|
||||
<!-- end:auto-docs -->
|
||||
## Purpose
|
||||
|
||||
`DatabaseConfig` and `MigrationConfig` are the two primary configuration shapes for `@suaveplan/db`. They define the options accepted by `DatabaseAdapter.connect` and `DatabaseAdapter.migrate` respectively, and are validated at runtime via their companion Zod schemas. Centralising config shapes here ensures every concrete adapter (SQLite, Postgres, SurrealDB) receives the same validated input.
|
||||
|
||||
By deriving the TypeScript types from Zod schemas (`z.infer<typeof ...>`), the types and runtime validation are always in sync — adding a new field in one place adds it to both automatically.
|
||||
|
||||
## Features
|
||||
|
||||
- `DatabaseConfig` — connection settings: optional file path, network URL, and read-only mode flag
|
||||
- `MigrationConfig` — migration settings: migrations folder path and tracking table name, both with sensible defaults
|
||||
- `MigrationStatus` — per-migration state returned by `pendingMigrations`
|
||||
- `MigrationResult` — aggregate result returned by `migrate` / `MigrationRunner.run`
|
||||
- Strict Zod schemas (`.strict()`) — unknown fields throw validation errors rather than being silently stripped
|
||||
- Default values baked into the Zod schemas: `readonlyMode` defaults to `false`, `migrationsFolder` to `"./drizzle"`, `migrationsTable` to `"__drizzle_migrations"`
|
||||
|
||||
## Usage: Basic Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
DatabaseConfigSchema,
|
||||
MigrationConfigSchema,
|
||||
} from "@suaveplan/db";
|
||||
|
||||
// Parse and validate adapter config
|
||||
const dbConfig = DatabaseConfigSchema.parse({
|
||||
filename: ":memory:",
|
||||
readonlyMode: false,
|
||||
});
|
||||
|
||||
// Parse and validate migration config
|
||||
const migConfig = MigrationConfigSchema.parse({
|
||||
migrationsFolder: "./db/migrations",
|
||||
});
|
||||
// { migrationsFolder: "./db/migrations", migrationsTable: "__drizzle_migrations" }
|
||||
```
|
||||
|
||||
## Usage: Advanced Example
|
||||
|
||||
```ts
|
||||
import type { DatabaseConfig, MigrationConfig } from "@suaveplan/db";
|
||||
import { DatabaseConfigSchema } from "@suaveplan/db";
|
||||
|
||||
function buildAdapter(raw: Partial<DatabaseConfig>): MyAdapter {
|
||||
// Validate at the boundary — unknown fields throw ZodError
|
||||
const config = DatabaseConfigSchema.parse(raw);
|
||||
return new MyAdapter(config);
|
||||
}
|
||||
|
||||
// TypeScript consumers that don't need runtime validation can use the type directly:
|
||||
function connectPg(config: DatabaseConfig): Promise<void> {
|
||||
if (!config.url) throw new Error("url required for PostgreSQL");
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### `DatabaseConfig`
|
||||
|
||||
```ts
|
||||
interface DatabaseConfig {
|
||||
filename?: string; // File path for embedded databases (e.g. ':memory:')
|
||||
url?: string; // Connection URL for network databases
|
||||
readonlyMode?: boolean; // Default: false
|
||||
}
|
||||
```
|
||||
|
||||
### `DatabaseConfigSchema`
|
||||
|
||||
Zod schema matching `DatabaseConfig`. Strict — rejects unknown fields.
|
||||
|
||||
### `MigrationConfig`
|
||||
|
||||
```ts
|
||||
interface MigrationConfig {
|
||||
migrationsFolder?: string; // Default: './drizzle'
|
||||
migrationsTable?: string; // Default: '__drizzle_migrations'
|
||||
}
|
||||
```
|
||||
|
||||
### `MigrationConfigSchema`
|
||||
|
||||
Zod schema matching `MigrationConfig`. Strict — rejects unknown fields.
|
||||
|
||||
### `MigrationStatus`
|
||||
|
||||
```ts
|
||||
interface MigrationStatus {
|
||||
name: string;
|
||||
applied: boolean;
|
||||
appliedAt?: Date;
|
||||
}
|
||||
```
|
||||
|
||||
Returned by `MigrationRunner.pendingMigrations`.
|
||||
|
||||
### `MigrationResult`
|
||||
|
||||
```ts
|
||||
interface MigrationResult {
|
||||
applied: number; // Count of migrations applied in this run
|
||||
migrations: string[]; // Names of applied migrations in order
|
||||
}
|
||||
```
|
||||
|
||||
Returned by `DatabaseAdapter.migrate` and `MigrationRunner.run`.
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
Both schemas use `.strict()` to catch typos in field names early. If a future version needs to support passthrough (e.g. for driver-specific extensions), that should be handled by extending the base schema rather than loosening it — keeping the core strict preserves the type-safety guarantee at the adapter boundary.
|
||||
|
||||
The `MigrationStatus` and `MigrationResult` types are plain interfaces (not Zod-derived) because they are output shapes returned to callers, not input shapes validated at the boundary.
|
||||
Reference in New Issue
Block a user