Repository navigation
feat add kysely integration - #224
Conversation
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>
|
Warning Rate limit exceeded
â How to resolve this issue?After the wait time has elapsed, a review can be triggered using the 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 configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: ð Files selected for processing (1)
ð WalkthroughWalkthroughAdds 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 Changes
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
Estimated code review effortðŊ 3 (Moderate) | âąïļ ~25 minutes Poem
ðĨ Pre-merge checks | â 3â Passed checks (3 passed)
âïļ Tip: You can configure your own custom pre-merge checks in the settings. âĻ Finishing Touchesð§Š Generate unit tests (beta)
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. Comment |
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 1
ð§đ Nitpick comments (5)
test/integrations/kysely/sqlite.test.ts (2)
107-109: Consider disposing the database connection inafterAll.The
afterAllhook drops the table but doesn't dispose of thedbinstance. For consistency with db0's resource management patterns and to prevent potential resource leaks in test suites, consider callingdb.dispose()or usingawait 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
selecttest assertsres.length).toBe(1), but this depends on theinserttest 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
beforeEachto ensure consistent state per testThis 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 notingRETURNINGclause 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 calldb.exec()without any error handling. IfBEGINfails (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: Usingstmt.all()for mutations is correct but relies on implicit behavior.For mutations with
RETURNING,stmt.all()correctly returns the affected rows. For mutations withoutRETURNING, 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
â Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
ð Files selected for processing (7)
AGENTS.mddocs/3.integrations/1.index.mddocs/3.integrations/kysely.mdpackage.jsonsrc/integrations/kysely/_dialect.tssrc/integrations/kysely/index.tstest/integrations/kysely/sqlite.test.ts
There was a problem hiding this comment.
ð§đ Nitpick comments (1)
test/integrations/kysely/pg.test.ts (1)
36-41: Consider using Vitest'sdescribe.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
ð 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>
Summary
db0/integrations/kysely) that wraps a db0Databaseinto a fully typed Kysely instanceUsage
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
ðĪ Generated with Claude Code
Summary by CodeRabbit
New Features
Documentation
Tests
Chores