@8x/kysely-d1
v1.0.1
Published
Readme
@8x/kysely-d1
Install
bun add @8x/kysely-d1Usage
Create a Kysely instance (recommended)
initD1Kysely takes a D1Database and returns a Kysely instance configured with the D1 dialect.
import { initD1Kysely } from "@8x/kysely-d1";
// Example database type
type Database = {
Comment: {
id: number;
content: string;
isHidden: 0 | 1;
};
};
export default {
async fetch(_req: Request, env: { DB: D1Database }) {
const db = initD1Kysely<Database>(env.DB);
const comments = await db.selectFrom("Comment").selectAll().execute();
const rows = await db
.selectFrom("Comment")
.select(["Comment.content", "id", "isHidden as is"])
.execute();
return Response.json({ comments, rows });
},
};Create manually with D1SQLiteDialect
If you prefer to construct Kysely yourself, you can use D1SQLiteDialect directly.
import { Kysely } from "kysely";
import { D1SQLiteDialect } from "@8x/kysely-d1";
const db = new Kysely<Database>({
dialect: new D1SQLiteDialect(env.DB),
});Run batch (atomic on D1)
runBatch(db, queries) executes an array of Kysely queries (Compilable) using D1's db.batch().
Per D1 behavior, a batch is executed atomically; if any statement fails, the batch is rolled back.
import { runBatch } from "@8x/kysely-d1";
const result = await runBatch(env.DB, [
db.insertInto("Person").values({ first_name: "John" }),
db.insertInto("Pet").values({ name: "Fido", owner_id: 1 }),
db.selectFrom("Person").selectAll(),
]);
console.log(result[0].meta.last_row_id); // insert id of the first query
console.log(result[1].meta.last_row_id); // insert id of the second query
console.log(result[2].results); // rows returned by the third (select) queryFor insert / update / delete queries without returning(), D1 returns an empty
results array (typed as never[]); the affected-row info lives in meta
(last_row_id, changes). Add returning() / returningAll() to get typed rows back.
Notes / Limitations
- Kysely
transaction()is not supported because D1 does not support SQL transaction statements likeBEGIN,COMMIT, andROLLBACK. streamQueryis not supported.
Development
To install dependencies:
bun installTo run:
bun run src/index.tsThis project was created using bun init in bun v1.3.6. Bun is a fast all-in-one JavaScript runtime.
Test
bun run cf-typegen
bun run vitest