kysely-d1

repository·main·Indexed 43 days ago

https://github.com/aidenwallis/kysely-d1

A Kysely dialect for Cloudflare D1 version 0.4.0, enabling the use of Kysely's type-safe query builder with Cloudflare's SQLite-based database service via the D1Dialect class.

Tokens
1.2K
Snippets
8
Records
8
Agent score
56%

What's inside kysely-d1

  1. Setup a Kysely D1 project

    main

    To set up a project using kysely-d1 and Cloudflare D1, follow these steps:

    1. Create a D1 database: Run the creation command and note the resulting database name and UUID.
    2. Configure Wrangler: Update your wrangler.toml file to bind your D1 database to a specific environment variable (e.g., DB).
    3. Run Migrations: Execute the setup script to apply initial migrations to your D1 instance.
    # 1. Create the database
    npm run create-db
    
    # 2. Run migrations
    npm run setup
  2. Configure the Kysely client with D1Dialect

    main

    To use Kysely with Cloudflare D1, import D1Dialect from kysely-d1 and pass your D1 database binding into the dialect option when instantiating the Kysely client.

    Note: You must first bind your Cloudflare Worker to your D1 database following the official Cloudflare documentation.

    import { Kysely } from 'kysely';
    import { D1Dialect } from 'kysely-d1';
    
    export interface Env {
      DB: D1Database;
    }
    
    interface Database {
      kv: {
        key: string;
        value: string;
      };
    }
    
    export default {
      async fetch(request: Request, env: Env): Promise<Response> {
        // Initialize Kysely with the D1 binding from the environment
        const db = new Kysely<Database>({
          dialect: new D1Dialect({
            database: env.DB
          })
        });
    
        // Example query
        const result = await db.selectFrom('kv').selectAll().executeTakeFirst();
        return new Response(JSON.stringify(result));
      },
    };
  3. Configure the D1 database binding in wrangler.toml

    main

    To make your D1 database available in your Cloudflare Worker (e.g., via env.DB), add a [[ d1_databases ]] section to your wrangler.toml file. Replace database_name and database_id with the values obtained from the npm run create-db command.

    [[ d1_databases ]]
    binding = "DB" # i.e. available in your Worker on env.DB
    database_name = "kysely-test"
    database_id = "<YOUR ID>"
  4. Configure the D1Dialect for Kysely

    main

    To use Cloudflare D1 with Kysely, instantiate the D1Dialect class. You must provide a configuration object containing the database property, which is the D1Database instance bound to your environment (e.g., via wrangler.toml).

    Note: Transactions are currently not supported by this dialect and will throw an error if attempted.

    import { Kysely, D1Dialect } from 'kysely-d1';
    
    // Assuming 'env.DB' is your D1 binding from Cloudflare Workers
    const dialect = new D1Dialect({
      database: env.DB,
    });
    
    const db = new Kysely<DatabaseSchema>({ dialect });
  5. D1Dialect interface

    main

    The D1Dialect class implements the Kysely Dialect interface, providing the necessary plumbing to connect Kysely to a Cloudflare D1 database. It uses a SqliteAdapter, SqliteQueryCompiler, and SqliteIntrospector internally because D1 is based on SQLite.

    export class D1Dialect implements Dialect {
      constructor(config: D1DialectConfig) {}
      // ...
    }