-
Notifications
You must be signed in to change notification settings - Fork 94
Add Cloudflare D1 database driver #980
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Copilot
wants to merge
3
commits into
main
Choose a base branch
from
copilot/add-cloudflare-workers-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,3 +6,4 @@ leveldb-store | |
| npm-debug.log | ||
| .idea | ||
| dist | ||
| package-lock.json | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| /** | ||
| * Cloudflare D1 database driver for ueberDB. | ||
| * | ||
| * D1 is Cloudflare's SQL database built on SQLite. This driver expects a | ||
| * D1Database binding to be passed via `settings.d1Database`. In a Cloudflare | ||
| * Worker you obtain the binding from the worker's `env` object: | ||
| * | ||
| * const db = new Database('cloudflare_d1', {d1Database: env.MY_D1_BINDING}); | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS-IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| import AbstractDatabase, {type Settings} from '../lib/AbstractDatabase'; | ||
| import type {BulkObject} from './cassandra_db'; | ||
|
|
||
| /** | ||
| * Minimal subset of the Cloudflare D1 API used by this driver. | ||
| * This intentionally mirrors the official @cloudflare/workers-types | ||
| * definitions so that users get type-safety when passing real bindings, | ||
| * while keeping this package free of a hard dependency on that package. | ||
| */ | ||
| export interface D1Result<T = Record<string, unknown>> { | ||
| results: T[]; | ||
| success: boolean; | ||
| meta: Record<string, unknown>; | ||
| } | ||
|
|
||
| export interface D1PreparedStatement { | ||
| bind(...values: unknown[]): D1PreparedStatement; | ||
| first<T = Record<string, unknown>>(colName?: string): Promise<T | null>; | ||
| run<T = Record<string, unknown>>(): Promise<D1Result<T>>; | ||
| all<T = Record<string, unknown>>(): Promise<D1Result<T>>; | ||
| raw<T = unknown[]>(options?: {columnNames?: boolean}): Promise<T[]>; | ||
| } | ||
|
|
||
| export interface D1Database { | ||
| prepare(query: string): D1PreparedStatement; | ||
| batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>; | ||
| exec(query: string): Promise<{count: number; duration: number}>; | ||
| } | ||
|
|
||
| export type D1Settings = Settings & { | ||
| /** The D1Database binding provided by the Cloudflare Worker runtime. */ | ||
| d1Database?: D1Database; | ||
| }; | ||
|
|
||
| export default class CloudflareD1DB extends AbstractDatabase { | ||
| private _d1db: D1Database | null; | ||
|
|
||
| constructor(settings: D1Settings) { | ||
| super(settings); | ||
| this._d1db = settings.d1Database ?? null; | ||
| this.settings.json = true; | ||
| this.settings.cache = 1000; | ||
| this.settings.writeInterval = 100; | ||
| } | ||
|
|
||
| get isAsync() { | ||
| return true; | ||
| } | ||
|
|
||
| async init(): Promise<void> { | ||
| if (!this._d1db) { | ||
| throw new Error( | ||
| 'CloudflareD1DB requires a D1Database binding passed via settings.d1Database', | ||
| ); | ||
| } | ||
| await this._d1db.exec( | ||
| 'CREATE TABLE IF NOT EXISTS store (key TEXT PRIMARY KEY NOT NULL, value TEXT NOT NULL)', | ||
| ); | ||
| } | ||
|
|
||
| async get(key: string): Promise<string | null> { | ||
| const row = await this._d1db! | ||
| .prepare('SELECT value FROM store WHERE key = ?') | ||
| .bind(key) | ||
| .first<{value: string}>(); | ||
| return row ? row.value : null; | ||
| } | ||
|
|
||
| async findKeys(key: string, notKey?: string | null): Promise<string[]> { | ||
| const likeKey = key.replace(/\*/g, '%'); | ||
| let stmt: D1PreparedStatement; | ||
| if (notKey != null) { | ||
| const likeNotKey = notKey.replace(/\*/g, '%'); | ||
| stmt = this._d1db! | ||
| .prepare('SELECT key FROM store WHERE key LIKE ? AND key NOT LIKE ?') | ||
| .bind(likeKey, likeNotKey); | ||
| } else { | ||
| stmt = this._d1db!.prepare('SELECT key FROM store WHERE key LIKE ?').bind(likeKey); | ||
| } | ||
| const result = await stmt.all<{key: string}>(); | ||
| return result.results.map((row) => row.key); | ||
| } | ||
|
|
||
| async set(key: string, value: string): Promise<void> { | ||
| if (key.length > 100) throw new Error('Your Key can only be 100 chars'); | ||
| await this._d1db! | ||
| .prepare('INSERT OR REPLACE INTO store (key, value) VALUES (?, ?)') | ||
| .bind(key, value) | ||
| .run(); | ||
| } | ||
|
|
||
| async remove(key: string): Promise<void> { | ||
| await this._d1db!.prepare('DELETE FROM store WHERE key = ?').bind(key).run(); | ||
| } | ||
|
|
||
| async doBulk(bulk: BulkObject[]): Promise<void> { | ||
| if (bulk.length === 0) return; | ||
| const statements: D1PreparedStatement[] = []; | ||
| for (const op of bulk) { | ||
| if (op.type === 'set') { | ||
| statements.push( | ||
| this._d1db! | ||
| .prepare('INSERT OR REPLACE INTO store (key, value) VALUES (?, ?)') | ||
| .bind(op.key, op.value), | ||
| ); | ||
| } else if (op.type === 'remove') { | ||
| statements.push( | ||
| this._d1db!.prepare('DELETE FROM store WHERE key = ?').bind(op.key), | ||
| ); | ||
| } | ||
| } | ||
| await this._d1db!.batch(statements); | ||
| } | ||
|
|
||
| close(): void { | ||
| this._d1db = null; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| import {describe} from 'vitest'; | ||
| import {test_db} from '../lib/test_lib'; | ||
|
|
||
| describe('cloudflare_d1 test', () => { | ||
| test_db('cloudflare_d1'); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| /** | ||
| * A lightweight mock implementation of the Cloudflare D1 API backed by | ||
| * Node.js's built-in `node:sqlite` module. Used only in tests. | ||
| * | ||
| * The mock mirrors the interface defined in cloudflare_d1_db.ts so that | ||
| * the driver can be exercised locally without a real Cloudflare runtime. | ||
| */ | ||
|
|
||
| import {DatabaseSync} from 'node:sqlite'; | ||
| import type {D1Database, D1PreparedStatement, D1Result} from '../../databases/cloudflare_d1_db'; | ||
|
|
||
| class MockD1PreparedStatement implements D1PreparedStatement { | ||
| private readonly _db: DatabaseSync; | ||
| private readonly _sql: string; | ||
| private readonly _bindings: unknown[]; | ||
|
|
||
| constructor(db: DatabaseSync, sql: string, bindings: unknown[] = []) { | ||
| this._db = db; | ||
| this._sql = sql; | ||
| this._bindings = bindings; | ||
| } | ||
|
|
||
| bind(...values: unknown[]): D1PreparedStatement { | ||
| return new MockD1PreparedStatement(this._db, this._sql, values); | ||
| } | ||
|
|
||
| async run<T = Record<string, unknown>>(): Promise<D1Result<T>> { | ||
| const stmt = this._db.prepare(this._sql); | ||
| stmt.run(...(this._bindings as Parameters<typeof stmt.run>)); | ||
| return {results: [], success: true, meta: {}}; | ||
| } | ||
|
|
||
| async first<T = Record<string, unknown>>(colName?: string): Promise<T | null> { | ||
| const stmt = this._db.prepare(this._sql); | ||
| const row = stmt.get(...(this._bindings as Parameters<typeof stmt.get>)) as | ||
| | Record<string, unknown> | ||
| | undefined; | ||
| if (row == null) return null; | ||
| if (colName != null) return (row[colName] ?? null) as T | null; | ||
| return row as T; | ||
| } | ||
|
|
||
| async all<T = Record<string, unknown>>(): Promise<D1Result<T>> { | ||
| const stmt = this._db.prepare(this._sql); | ||
| const results = stmt.all(...(this._bindings as Parameters<typeof stmt.all>)) as T[]; | ||
| return {results, success: true, meta: {}}; | ||
| } | ||
|
|
||
| async raw<T = unknown[]>(options?: {columnNames?: boolean}): Promise<T[]> { | ||
| // Simplified: return rows as arrays without column names unless requested | ||
| const result = await this.all<Record<string, unknown>>(); | ||
| if (!result.results.length) return [] as unknown as T[]; | ||
| const cols = Object.keys(result.results[0]); | ||
| const rows: unknown[][] = result.results.map((r) => cols.map((c) => r[c])); | ||
| if (options?.columnNames) { | ||
| return [cols, ...rows] as unknown as T[]; | ||
| } | ||
| return rows as unknown as T[]; | ||
| } | ||
| } | ||
|
|
||
| export class MockD1Database implements D1Database { | ||
| private readonly _db: DatabaseSync; | ||
|
|
||
| constructor() { | ||
| this._db = new DatabaseSync(':memory:'); | ||
| } | ||
|
|
||
| prepare(sql: string): D1PreparedStatement { | ||
| return new MockD1PreparedStatement(this._db, sql); | ||
| } | ||
|
|
||
| async batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]> { | ||
| return Promise.all(statements.map((s) => s.run<T>())); | ||
| } | ||
|
|
||
| async exec(sql: string): Promise<{count: number; duration: number}> { | ||
| this._db.exec(sql); | ||
| return {count: 0, duration: 0}; | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
1. Bulk bypasses key limit
🐞 Bug≡ CorrectnessAgent Prompt
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools