Skip to content

feat add kysely integration - #224

Merged
pi0 merged 5 commits into
mainfrom
feat/kysely
Mar 29, 2026
Merged

pi0 merged 5 commits into
mainfrom
feat/kysely

Conversation

@pi0

@pi0 pi0 commented Mar 24, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Adds a Kysely integration (db0/integrations/kysely) that wraps a db0 Database into a fully typed Kysely instance
  • Auto-detects SQL dialect (SQLite, PostgreSQL, MySQL) from the db0 connector — no manual dialect config needed
  • Adds tests covering insert, select, update, delete, transactions, and rollback

Usage

import { createDatabase } from "db0";
import sqlite from "db0/connectors/better-sqlite3";
import { kysely } from "db0/integrations/kysely";

interface Database {
  users: { id: number; name: string; email: string };
}

const db = createDatabase(sqlite({ name: "mydb.sqlite" }));
const ky = kysely<Database>(db);

// Type-safe queries
const users = await ky.selectFrom("users").selectAll().execute();

await ky
  .insertInto("users")
  .values({ name: "John", email: "john@example.com" })
  .execute();

// Transactions work out of the box
await ky.transaction().execute(async (trx) => {
  await trx.insertInto("users").values({ name: "Alice", email: "alice@example.com" }).execute();
});

The dialect is auto-detected from the db0 connector, so switching from SQLite to PostgreSQL only requires changing the connector — no Kysely config changes needed.

Test plan

  • SQLite integration tests pass with libsql-node connector
  • Verify PostgreSQL dialect path with a pg connector
  • Verify MySQL dialect path with a mysql2 connector

ðŸĪ– Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added Kysely integration support for querying databases through db0.
  • Documentation

    • New Kysely integration guide with installation, CRUD examples, transactions, and dialect mappings.
    • Integration index updated to list Kysely alongside existing adapters.
  • Tests

    • Added end-to-end integration tests validating Kysely CRUD and transaction behavior across connectors.
  • Chores

    • Declared Kysely as a supported dependency in package configuration.

Implements a db0 dialect for Kysely that auto-detects the SQL dialect
(sqlite, postgresql, mysql) from the db0 connector and delegates to
Kysely's built-in query compilers, adapters, and introspectors.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Mar 24, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@pi0 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 17 minutes and 59 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

ðŸšĶ How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

â„đïļ Review info
⚙ïļ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6ceab3b0-5a11-431b-bba8-1265848b2bbe

ðŸ“Ĩ Commits

Reviewing files that changed from the base of the PR and between 0e81a6c and 43c9589.

📒 Files selected for processing (1)
  • docs/3.integrations/kysely.md
📝 Walkthrough

Walkthrough

Adds a Kysely integration to db0: new docs, package.json entries, a Kysely driver/dialect and connection implementation, plus integration tests for SQLite and PostgreSQL connectors and a factory kysely(db, config?) export.

Changes

Cohort / File(s) Summary
Documentation
AGENTS.md, docs/3.integrations/1.index.md, docs/3.integrations/kysely.md
Add Kysely to modular exports and integrations index; expanded Kysely docs with install, usage, queries, transactions, and dialect mapping.
Package Configuration
package.json
Add kysely to devDependencies (^0.28.14), to peerDependencies (*) and mark it optional in peerDependenciesMeta.
Kysely Integration Implementation
src/integrations/kysely/_dialect.ts, src/integrations/kysely/index.ts
Add DB0Connection implementing Kysely DatabaseConnection (executeQuery, streamQuery), DB0Driver handling connection/transaction lifecycle, DB0Dialect selecting compiler/adapter/introspector, export KyselyDatabase type and kysely(db, config?) factory.
Integration Tests
test/integrations/kysely/sqlite.test.ts, test/integrations/kysely/pg.test.ts
Add Vitest integration suites validating Kysely CRUD and transaction (including rollback) behavior against SQLite and PostgreSQL/pglite connectors.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant KyselyFactory as kysely()
    participant Kysely as Kysely Instance
    participant Driver as DB0Driver
    participant Conn as DB0Connection
    participant DB as Database

    Client->>KyselyFactory: kysely(db, config?)
    KyselyFactory->>Driver: new DB0Driver(db)
    Driver->>Conn: open connection / executeQuery
    KyselyFactory->>Kysely: return Kysely instance

    Client->>Kysely: build & execute query
    Kysely->>Driver: execute compiled query
    Driver->>Conn: executeQuery(compiledQuery)
    Conn->>DB: prepare(sql).all(parameters)
    DB-->>Conn: rows
    Conn-->>Driver: QueryResult {rows, numAffectedRows?}
    Driver-->>Kysely: QueryResult
    Kysely-->>Client: result
Loading

Estimated code review effort

ðŸŽŊ 3 (Moderate) | ⏱ïļ ~25 minutes

Poem

I hopped from patch to patch today, 🐰
A Kysely bridge to db0, hooray!
Queries run and transactions play,
Docs and tests now lead the way,
The rabbit nods—new paths to stray.

ðŸšĨ Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and accurately summarizes the main change: adding a Kysely integration to the db0 library, which is the primary purpose of this PR.

✏ïļ Tip: You can configure your own custom pre-merge checks in the settings.

âœĻ Finishing Touches
🧊 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/kysely

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

âĪïļ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@pi0
pi0 marked this pull request as ready for review March 24, 2026 21:56
pi0 and others added 2 commits March 24, 2026 22:59
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@pi0 pi0 changed the title feat(kysely): add kysely query builder integration feat add kysely integration Mar 24, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

ðŸ§đ Nitpick comments (5)
test/integrations/kysely/sqlite.test.ts (2)

107-109: Consider disposing the database connection in afterAll.

The afterAll hook drops the table but doesn't dispose of the db instance. For consistency with db0's resource management patterns and to prevent potential resource leaks in test suites, consider calling db.dispose() or using await using.

â™ŧïļ Suggested improvement
     afterAll(async () => {
       await db.sql`DROP TABLE IF EXISTS users`;
+      await db[Symbol.asyncDispose]?.();
     });
ðŸĪ– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/integrations/kysely/sqlite.test.ts` around lines 107 - 109, The afterAll
hook currently drops the users table but doesn't close the database connection;
update the afterAll in the test to also dispose the db instance by calling await
db.dispose() (or using the test framework's resource cleanup like await using if
supported) so the Kysely/SQLite connection is properly closed; locate the db
variable and the afterAll block in sqlite.test.ts and add the disposal call
after the DROP TABLE operation.

52-57: Tests have sequential dependencies; consider adding comments or improving isolation.

The select test asserts res.length).toBe(1), but this depends on the insert test having run first. While test frameworks typically run tests in order, this coupling can make tests fragile. Consider either:

  • Adding a comment noting the intentional sequential dependency
  • Using beforeEach to ensure consistent state per test

This is acceptable for integration tests but worth noting for maintainability.

ðŸĪ– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/integrations/kysely/sqlite.test.ts` around lines 52 - 57, The "select"
test depends on prior state seeded by the "insert" test (it expects res.length
toBe(1)); make the dependency explicit or isolate it: either add a concise
comment above the it("select", ...) test noting the intentional sequential
dependency on the "insert" test, or modify the suite to initialize state
consistently (e.g., add a beforeEach that resets the users table or inserts the
expected user) so the select test no longer relies on execution order; reference
the test case name "select" and the related "insert" test when making the
change.
docs/3.integrations/kysely.md (1)

49-54: Consider noting RETURNING clause compatibility.

The example uses .returning(["id", "name", "email"]), which works for SQLite and PostgreSQL but is not supported by MySQL. Since the documentation mentions MySQL as a supported dialect, a brief note about this limitation would help users avoid runtime errors.

ðŸĪ– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/3.integrations/kysely.md` around lines 49 - 54, Add a short
compatibility note next to the example stating that .returning([...]) (used
after ky.insertInto("users").values(...).returning(...).executeTakeFirst()) is
supported by SQLite and PostgreSQL but not by MySQL; for MySQL instruct readers
to instead retrieve the inserted id from the insert result (or run a follow-up
select via ky.selectFrom("users").select(...).where(...)) as an alternative to
.returning.
src/integrations/kysely/index.ts (1)

41-51: Transaction methods should handle errors gracefully.

The transaction methods (beginTransaction, commitTransaction, rollbackTransaction) directly call db.exec() without any error handling. If BEGIN fails (e.g., nested transaction attempt on SQLite), the error propagates but leaves the connection in an undefined state.

Consider whether additional safeguards are needed, though Kysely's transaction executor likely handles this at a higher level.

ðŸĪ– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/integrations/kysely/index.ts` around lines 41 - 51, The transaction
helpers beginTransaction, commitTransaction, and rollbackTransaction call
this.db.exec(...) without error handling; wrap each call in a try/catch that
captures any error from this.db.exec, log or annotate the error with context
(e.g., which operation failed and the SQL verb like "BEGIN"/"COMMIT"/"ROLLBACK")
and then rethrow (or throw a new Error that preserves the original error) so
callers still get failures but with clear context; reference the methods
beginTransaction, commitTransaction, rollbackTransaction and the call site
this.db.exec to locate and update the implementations.
src/integrations/kysely/_dialect.ts (1)

20-21: Using stmt.all() for mutations is correct but relies on implicit behavior.

For mutations with RETURNING, stmt.all() correctly returns the affected rows. For mutations without RETURNING, it returns an empty array. This works but the intent could be clearer with a comment explaining this dual behavior.

📝 Suggested clarifying comment
     if (
       compiledQuery.query.kind === "InsertQueryNode" ||
       compiledQuery.query.kind === "UpdateQueryNode" ||
       compiledQuery.query.kind === "DeleteQueryNode" ||
       compiledQuery.query.kind === "MergeQueryNode"
     ) {
-      // For mutations that may return rows (RETURNING clause)
+      // For mutations: stmt.all() returns rows if RETURNING is used, empty array otherwise.
+      // db0 doesn't expose affected row count from run(), so we derive it from returned rows.
       const rows = (await stmt.all(...(parameters as Primitive[]))) as R[];
ðŸĪ– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/integrations/kysely/_dialect.ts` around lines 20 - 21, Clarify the dual
behavior of using stmt.all(...) for mutations by adding a comment near the
stmt.all call (where rows is assigned: "const rows = (await
stmt.all(...(parameters as Primitive[]))) as R[]") that explains it returns
affected rows when the query uses RETURNING and returns an empty array for
mutations without RETURNING; reference the stmt.all function, the rows variable,
and the Primitive/R[] types so future readers understand this implicit behavior
and why stmt.all is used for both cases.
ðŸĪ– Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/integrations/kysely/_dialect.ts`:
- Around line 14-27: The current logic treats all mutation queries the same and
uses stmt.all(...parameters) which returns an empty rows array for mutations
without a RETURNING clause, making numAffectedRows incorrect; update the
mutation handling in the block that checks compiledQuery.query.kind
(InsertQueryNode/UpdateQueryNode/DeleteQueryNode/MergeQueryNode) to call
stmt.all first, and if that returns an empty array (indicating no RETURNING),
call stmt.run(...) instead and return rows: [] with numAffectedRows: undefined
(or otherwise explicitly document the limitation), referencing compiledQuery,
stmt, rows, and numAffectedRows to locate the change.

---

Nitpick comments:
In `@docs/3.integrations/kysely.md`:
- Around line 49-54: Add a short compatibility note next to the example stating
that .returning([...]) (used after
ky.insertInto("users").values(...).returning(...).executeTakeFirst()) is
supported by SQLite and PostgreSQL but not by MySQL; for MySQL instruct readers
to instead retrieve the inserted id from the insert result (or run a follow-up
select via ky.selectFrom("users").select(...).where(...)) as an alternative to
.returning.

In `@src/integrations/kysely/_dialect.ts`:
- Around line 20-21: Clarify the dual behavior of using stmt.all(...) for
mutations by adding a comment near the stmt.all call (where rows is assigned:
"const rows = (await stmt.all(...(parameters as Primitive[]))) as R[]") that
explains it returns affected rows when the query uses RETURNING and returns an
empty array for mutations without RETURNING; reference the stmt.all function,
the rows variable, and the Primitive/R[] types so future readers understand this
implicit behavior and why stmt.all is used for both cases.

In `@src/integrations/kysely/index.ts`:
- Around line 41-51: The transaction helpers beginTransaction,
commitTransaction, and rollbackTransaction call this.db.exec(...) without error
handling; wrap each call in a try/catch that captures any error from
this.db.exec, log or annotate the error with context (e.g., which operation
failed and the SQL verb like "BEGIN"/"COMMIT"/"ROLLBACK") and then rethrow (or
throw a new Error that preserves the original error) so callers still get
failures but with clear context; reference the methods beginTransaction,
commitTransaction, rollbackTransaction and the call site this.db.exec to locate
and update the implementations.

In `@test/integrations/kysely/sqlite.test.ts`:
- Around line 107-109: The afterAll hook currently drops the users table but
doesn't close the database connection; update the afterAll in the test to also
dispose the db instance by calling await db.dispose() (or using the test
framework's resource cleanup like await using if supported) so the Kysely/SQLite
connection is properly closed; locate the db variable and the afterAll block in
sqlite.test.ts and add the disposal call after the DROP TABLE operation.
- Around line 52-57: The "select" test depends on prior state seeded by the
"insert" test (it expects res.length toBe(1)); make the dependency explicit or
isolate it: either add a concise comment above the it("select", ...) test noting
the intentional sequential dependency on the "insert" test, or modify the suite
to initialize state consistently (e.g., add a beforeEach that resets the users
table or inserts the expected user) so the select test no longer relies on
execution order; reference the test case name "select" and the related "insert"
test when making the change.

â„đïļ Review info
⚙ïļ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9e4e4cc1-8554-41ee-abdd-44fed36466aa

ðŸ“Ĩ Commits

Reviewing files that changed from the base of the PR and between 8356a77 and 9c27dd1.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (7)
  • AGENTS.md
  • docs/3.integrations/1.index.md
  • docs/3.integrations/kysely.md
  • package.json
  • src/integrations/kysely/_dialect.ts
  • src/integrations/kysely/index.ts
  • test/integrations/kysely/sqlite.test.ts

Comment thread src/integrations/kysely/_dialect.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ðŸ§đ Nitpick comments (1)
test/integrations/kysely/pg.test.ts (1)

36-41: Consider using Vitest's describe.skipIf() for cleaner conditional execution.

Vitest provides describe.skipIf(condition) which could simplify the conditional logic:

-  const describeFn = runIf === false ? describe.skip : describe;
-
-  describeFn(`integrations: kysely: ${name}`, () => {
+  describe.skipIf(runIf === false)(`integrations: kysely: ${name}`, () => {

This is a minor suggestion—the current approach works correctly.

ðŸĪ– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/integrations/kysely/pg.test.ts` around lines 36 - 41, The loop currently
creates a conditional describe function via describeFn and uses it to skip
suites when runIf is false; replace that pattern by calling Vitest's
describe.skipIf to simplify the logic: inside the for loop, remove describeFn
and use describe.skipIf(runIf === false)(`integrations: kysely: ${name}`, () =>
{ ... }) so the connector iteration (connectors, name, connector, runIf) and the
test suite body (the let ky: Kysely<DB>; let db: Database; etc.) remain
unchanged while relying on describe.skipIf for conditional skipping.
ðŸĪ– Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@test/integrations/kysely/pg.test.ts`:
- Around line 36-41: The loop currently creates a conditional describe function
via describeFn and uses it to skip suites when runIf is false; replace that
pattern by calling Vitest's describe.skipIf to simplify the logic: inside the
for loop, remove describeFn and use describe.skipIf(runIf ===
false)(`integrations: kysely: ${name}`, () => { ... }) so the connector
iteration (connectors, name, connector, runIf) and the test suite body (the let
ky: Kysely<DB>; let db: Database; etc.) remain unchanged while relying on
describe.skipIf for conditional skipping.

â„đïļ Review info
⚙ïļ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 63b00b61-a20d-4aa4-8b9e-a076b20985dd

ðŸ“Ĩ Commits

Reviewing files that changed from the base of the PR and between 9c27dd1 and 0e81a6c.

📒 Files selected for processing (1)
  • test/integrations/kysely/pg.test.ts

Document that numAffectedRows is unavailable without RETURNING
and that streaming queries are not supported.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

@igalklebanov igalklebanov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! 🚀

@pi0
pi0 merged commit 60202ee into main Mar 29, 2026
5 checks passed
@pi0
pi0 deleted the feat/kysely branch March 29, 2026 20:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants