npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@cibule/db

v0.7.3

Published

Readme

@cibule/db

Driver-agnostic database abstraction for TypeScript, built on Kysely.

Installation

npm install @cibule/db
# or
bun add @cibule/db
# or
pnpm add @cibule/db
# or
yarn add @cibule/db

Dependencies @cibule/di and kysely are installed automatically.

Quick Start

import { createMockDb, MockUnitOfWork, paginate } from '@cibule/db';

interface MySchema {
  users: { id: number; name: string; email: string };
  posts: { id: number; title: string; user_id: number };
}

// Create a mock database for testing
const db = createMockDb<MySchema>();

// Build and compile a type-safe query
const compiled = db.selectFrom('users').selectAll().compile();
// { sql: 'select * from "users"', parameters: [] }

// Use MockUnitOfWork to capture queries for assertions
const uow = new MockUnitOfWork();
uow.add(db.insertInto('users').values({ id: 1, name: 'Alice', email: '[email protected]' }).compile());
await uow.execute();
console.log(uow.queries.length); // 1

API Reference

Db<Schema>

Type alias for Kysely<Schema>. All database operations go through this type, keeping your code independent of the underlying driver.

import type { Db } from '@cibule/db';

interface MySchema {
  users: { id: number; name: string };
}

function findUser(db: Db<MySchema>, id: number) {
  return db.selectFrom('users').selectAll().where('id', '=', id).executeTakeFirst();
}

DbAccessor / DB_ACCESSOR

Accessor pattern for per-request database instances. DbAccessor<Schema> is a function () => Db<Schema>, resolved via the DB_ACCESSOR injection token.

import { inject } from '@cibule/di';
import type { DbAccessor } from '@cibule/db';
import { DB_ACCESSOR } from '@cibule/db';

class UserRepository {
  private readonly db = inject(DB_ACCESSOR);

  findAll() {
    return this.db().selectFrom('users').selectAll().execute();
  }
}

provideDbAccessor(factory)

DI provider factory that registers a DbAccessor with the injector.

import { Injector } from '@cibule/di';
import { createMockDb, provideDbAccessor } from '@cibule/db';

const injector = Injector.create({
  providers: [provideDbAccessor(() => () => createMockDb<MySchema>())],
});

provideDb(db, unitOfWorkFactory)

Registers an existing Db and a UnitOfWorkFactory in one call, for jobs and crons that already hold a database instance.

import { provideDb } from '@cibule/db';
import { createD1Db, D1UnitOfWork } from '@cibule/db-d1';

const injector = Injector.create({
  providers: [provideDb(createD1Db<MySchema>(env.DB), () => new D1UnitOfWork(env.DB))],
});

UnitOfWork / UNIT_OF_WORK_FACTORY

Interface for atomic multi-statement writes. Add compiled queries, then execute them as a batch. UNIT_OF_WORK_FACTORY is an injection token for the double-factory pattern — each call produces a fresh UnitOfWork.

Registering with DI:

import { inject, Injector } from '@cibule/di';
import { DB_ACCESSOR, UNIT_OF_WORK_FACTORY } from '@cibule/db';

const injector = Injector.create({
  providers: [
    // ... db accessor provider ...
    {
      provide: UNIT_OF_WORK_FACTORY,
      useFactory: () => () => new MockUnitOfWork(), // or SqliteUnitOfWork, D1UnitOfWork
    },
  ],
});

// Resolving:
const createUow = inject(UNIT_OF_WORK_FACTORY);
const uow = createUow(); // fresh instance each call

Usage:

import type { Db, UnitOfWorkFactory } from '@cibule/db';

async function transferFunds(uowFactory: UnitOfWorkFactory, db: Db<Schema>) {
  const uow = uowFactory();

  uow.add(db.updateTable('accounts').set({ balance: 900 }).where('id', '=', 1).compile());
  uow.add(db.updateTable('accounts').set({ balance: 1100 }).where('id', '=', 2).compile());

  await uow.execute(); // atomic — all or nothing
}

Design constraints (lowest common denominator for D1 compatibility):

  • No intermediate reads between statements
  • All statements prepared upfront (pre-generate UUIDs)
  • Maximum 100 statements per batch (D1 limit)

createMockDb<Schema>()

Creates a Kysely instance with a DummyDriver for testing. Queries can be built and compiled but not executed.

import { createMockDb } from '@cibule/db';

const db = createMockDb<MySchema>();

// Compile queries for assertion
const query = db.selectFrom('users').where('name', '=', 'Alice').selectAll().compile();
expect(query.sql).toContain('select');
expect(query.parameters).toEqual(['Alice']);

MockUnitOfWork

Test implementation of UnitOfWork that captures queries for assertion. execute() is a no-op.

import { createMockDb, MockUnitOfWork } from '@cibule/db';

const db = createMockDb<MySchema>();
const uow = new MockUnitOfWork();

uow.add(db.insertInto('users').values({ id: 1, name: 'Alice' }).compile());
uow.add(db.insertInto('users').values({ id: 2, name: 'Bob' }).compile());

expect(uow.queries).toHaveLength(2);
expect(uow.queries[0]?.sql).toContain('insert');

await uow.execute(); // no-op, queries remain for inspection
expect(uow.queries).toHaveLength(2);

paginate(query, params?, transform?)

Single-query pagination using count(*) over() window function. Returns data and total count without a separate COUNT query.

import { paginate } from '@cibule/db';
import type { PaginatedResult } from '@cibule/db';

const result: PaginatedResult<User> = await paginate(db.selectFrom('users').selectAll(), {
  page: 2,
  limit: 10,
});

// result.data   — User[] (page of results)
// result.total  — number (total matching rows)
// result.page   — number (current page, minimum 1)
// result.limit  — number (page size, clamped 1-200)

With a transform function to map rows:

const result = await paginate(db.selectFrom('users').selectAll(), { page: 1, limit: 20 }, row => ({
  id: row.id,
  displayName: row.name,
}));
// result.data — { id: number; displayName: string }[]

Parameter clamping:

| Parameter | Default | Minimum | Maximum | | --------- | ------- | ------- | ------- | | page | 1 | 1 | -- | | limit | 20 | 1 | 200 |

Driver Architecture

@cibule/db provides the core interfaces and a mock driver for testing. Real database drivers are separate packages, each at a heavy dependency boundary:

| Package | Driver | Heavy dependency | | ------------------- | -------------- | ---------------- | | @cibule/db | Mock (testing) | None (built-in) | | @cibule/db-sqlite | SQLite | better-sqlite3 | | @cibule/db-d1 | Cloudflare D1 | kysely-d1 |

All drivers produce Db<Schema> and implement UnitOfWork, so application code stays driver-agnostic.

Type Exports

import type {
  Db,
  DbAccessor,
  PaginatedResult,
  PaginateParams,
  UnitOfWork,
  UnitOfWorkFactory,
} from '@cibule/db';

License

MIT