@superfunctions/db
v0.3.4
Published
Shared database adapter system for building useful backend libraries
Maintainers
Readme
@superfunctions/db
Shared database adapter system for Superfunctions libraries. Provides a unified interface for interacting with databases across multiple ORMs (Drizzle, Prisma, Kysely).
Installation
npm install @superfunctions/db
# Install the integration you use. drizzle-orm is a required peer;
# @prisma/client and kysely are optional peers.
npm install drizzle-orm
npm install @prisma/client
npm install kysely
# The PostgreSQL Drizzle examples also import the pg driver directly.
npm install pgQuick Start
Memory adapter (tests and local):
import { memoryAdapter } from '@superfunctions/db/adapters';
const adapter = memoryAdapter();
const user = await adapter.create({
model: 'users',
data: { email: '[email protected]', name: 'John Doe' },
});Drizzle adapter (Postgres, MySQL, SQLite):
import { drizzle } from 'drizzle-orm/node-postgres';
import { drizzleAdapter } from '@superfunctions/db/adapters';
import { Pool } from 'pg';
import { users } from './schema';
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const db = drizzle(pool, { schema: { users } });
const adapter = drizzleAdapter({
db,
dialect: 'postgres', // 'postgres' | 'mysql' | 'sqlite'
upsertKeys: { users: 'email' },
});Runnable demos: examples/.
Core Concepts
Adapter Interface
All adapters implement a unified interface:
interface Adapter {
// CRUD operations
create(params: CreateParams): Promise<T>;
findOne(params: FindOneParams): Promise<T | null>;
findMany(params: FindManyParams): Promise<T[]>;
update(params: UpdateParams): Promise<T>;
delete(params: DeleteParams): Promise<void>;
// Batch operations
createMany(params: CreateManyParams): Promise<T[]>;
updateMany(params: UpdateManyParams): Promise<number>;
deleteMany(params: DeleteManyParams): Promise<number>;
// Advanced
upsert(params: UpsertParams): Promise<T>;
count(params: CountParams): Promise<number>;
transaction<R>(callback: (trx: TransactionAdapter) => Promise<R>, options?: { isolationLevel: TransactionIsolation }): Promise<R>;
// Lifecycle
initialize(): Promise<void>;
isHealthy(): Promise<HealthStatus>;
close(): Promise<void>;
// Schema management
getSchemaVersion(namespace: string): Promise<number>;
setSchemaVersion(namespace: string, version: number): Promise<void>;
}Per-call isolation is opt-in: consult capabilities.transactions.configurableIsolation
and the advertised isolation levels before requiring it. PostgreSQL Drizzle honors
explicit isolation; unsupported adapters reject requested isolation rather than
silently downgrade it. Omitting options retains ordinary transaction behavior.
Release gates are package-local: npm run typecheck, npm run build,
npm run lint, and npm test. Tests require the declared native SQLite development
dependency. Consumers of @superfunctions/db/testing must also install Vitest.
Capabilities System
Adapters declare their capabilities, and libraries adapt accordingly:
const adapter = memoryAdapter();
if (adapter.capabilities.operations.batch) {
// Use batch operations
await adapter.createMany({ model: 'users', data: users });
} else {
// Fallback to sequential
for (const user of users) {
await adapter.create({ model: 'users', data: user });
}
}Namespace Isolation
Scope records by the namespace supplied on each operation:
import { wrapWithRowLevelNamespace } from '@superfunctions/db';
import { memoryAdapter } from '@superfunctions/db/adapters';
const adapter = wrapWithRowLevelNamespace(memoryAdapter(), {
enabled: true,
columnName: '__ns',
mandatory: true,
});
await adapter.create({
model: 'users',
data: { email: '[email protected]' },
namespace: 'auth',
});
// Stored with __ns = 'auth'; other namespaces cannot read this row.
await adapter.create({
model: 'files',
data: { path: '/readme.md' },
namespace: 'files',
});
// Stored with __ns = 'files'.Built-in Adapters
Memory Adapter
In-memory adapter for testing and development:
import { memoryAdapter } from '@superfunctions/db/adapters';
const adapter = memoryAdapter({
namespace: { enabled: true },
debug: true
});Drizzle Adapter
For Drizzle ORM (PostgreSQL, MySQL, SQLite):
import { drizzle } from 'drizzle-orm/node-postgres';
import { users, posts } from './schema';
import { drizzleAdapter } from '@superfunctions/db/adapters';
import { Pool } from 'pg';
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const db = drizzle(pool, { schema: { users, posts } });
const adapter = drizzleAdapter({
db,
dialect: 'postgres', // 'postgres' | 'mysql' | 'sqlite'
upsertKeys: { users: 'email' }, // conflict targets
debug: false
});Features:
- Full CRUD with where/orderBy/select
- Batch operations
- Transactions (async for Postgres/MySQL)
- Upsert with conflict resolution
- All where operators: eq, ne, gt, gte, lt, lte, in, not_in, contains, starts_with, ends_with
Prisma Adapter
For Prisma ORM:
import { PrismaClient } from '@prisma/client';
import { prismaAdapter } from '@superfunctions/db/adapters';
const prisma = new PrismaClient();
const adapter = prismaAdapter({
prisma,
modelMap: { users: 'user', posts: 'post' }, // model → Prisma model name
schemaVersionsTable: 'schemaVersions', // optional
debug: false
});Features:
- Full where clause translation with AND/OR
- Select projection and orderBy
- Batch operations
- Transaction support via
$transaction - Upsert with unique constraints
Kysely Adapter
For Kysely query builder:
import { Kysely, PostgresDialect } from 'kysely';
import { kyselyAdapter } from '@superfunctions/db/adapters';
const db = new Kysely<Database>({
dialect: new PostgresDialect({ pool })
});
const adapter = kyselyAdapter({
db,
dialect: 'postgres', // 'postgres' | 'mysql' | 'sqlite'
schema: { users: 'users', posts: 'posts' }, // model → table name
schemaVersionsTable: '__schema_versions', // optional
debug: false
});Features:
- Type-safe query building
- Full CRUD with all operators
- Transactions
- Upsert (INSERT...ON CONFLICT)
- Multi-dialect support
Raw SQL
drizzleAdapter and kyselyAdapter also expose adapter.rawSql for statements the CRUD API cannot express, such as an atomic UPDATE … RETURNING. Each ? is a positional parameter, rendered for the dialect ($1… on Postgres); the text must contain no other ?. rawSql uses the adapter's connection but bypasses schema mapping and row-level namespaces. Other adapters leave it undefined.
const rows = await adapter.rawSql!.query(
'UPDATE jobs SET state = ? WHERE id = (SELECT id FROM jobs WHERE state = ? LIMIT 1) RETURNING id',
['leased', 'pending']
);
await adapter.rawSql!.execute('CREATE INDEX IF NOT EXISTS jobs_state_idx ON jobs (state)');@superfunctions/queue uses it for its durable DatabaseQueueAdapter.
JSON stored in text columns
Function authors can declare { type: "json", jsonStorageType: "json-text" }
on a field in their internal wrapWithSchema schema when the physical column
stores JSON as text (for example SQLite TEXT). Native JSON storage remains the
default. The wrapper serializes values on writes and parses them on reads,
including transactions; repeated wrappers with the same codec do not encode twice.
Selected-field projections remain selected-field projections.
Codec ownership also survives intermediate wrappers declaring native storage: those declarations cannot disable an already-active delegated JSON-text or integer-boolean codec. The outer wrapper avoids converting the field twice.
Runtime null is stored as SQL NULL. Both SQL NULL and JSON text null read as
runtime null; use a tagged application value if that distinction matters.
Strings are JSON strings, even if they contain valid JSON text. Malformed stored
JSON raises a TypeError identifying the field without including its contents.
The optional Vitest peer is required only by the @superfunctions/db/testing
contract suites; Vitest 3.2.4+ and 4.x are supported. Production adapters do not
require Vitest.
JSON-text predicates use the same JSON serialization as writes (including each value in in/not_in). Equality compares the serialized representation, so object key order remains significant; this is not a database-native JSON structural comparison.
JSON-text fields support eq, ne, in, and not_in. Range and substring
operators reject with a field-specific error instead of silently comparing
serialized JSON using undefined application semantics.
Import wrapWithSchema from @superfunctions/db/schema when only schema wrapping is needed. This narrow ESM entry does not initialize database drivers or observability; it also supports synchronous require() on Node versions that support requiring synchronous ESM (validated on Node 20.19).
Testing
Use the built-in memory adapter for testing:
import { memoryAdapter } from '@superfunctions/db/testing';
import { describe, it, expect } from 'vitest';
describe('My Library', () => {
it('should create records', async () => {
const adapter = memoryAdapter();
const result = await adapter.create({
model: 'users',
data: { name: 'John' }
});
expect(result).toHaveProperty('id');
expect(result.name).toBe('John');
});
});TypeScript
Full TypeScript support with strict types:
import type {
Adapter,
CreateParams,
WhereClause,
TableSchema
} from '@superfunctions/db';
const adapter: Adapter = memoryAdapter();
const params: CreateParams = {
model: 'users',
data: { name: 'John' }
};
const user = await adapter.create(params);Error Handling
Standardized error classes across all adapters:
import {
AdapterError,
NotFoundError,
ConnectionError
} from '@superfunctions/db';
try {
await adapter.findOne({ model: 'users', where: [{ field: 'id', operator: 'eq', value: '123' }] });
} catch (error) {
if (error instanceof NotFoundError) {
console.log('User not found');
} else if (error instanceof ConnectionError) {
console.log('Database connection failed');
} else if (error instanceof AdapterError) {
console.log('Adapter error:', error.code);
}
}License
Apache-2.0
Contributing
Contributions welcome! See Contributing Guide for details.
Related Packages
@superfunctions/cli- Schema management and migrations
