Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ leveldb-store
npm-debug.log
.idea
dist
package-lock.json
140 changes: 140 additions & 0 deletions databases/cloudflare_d1_db.ts
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);
}
Comment on lines +118 to +135
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

1. Bulk bypasses key limit 🐞 Bug ≡ Correctness

CloudflareD1DB.doBulk() writes keys without enforcing the 100-character limit, so oversized keys can
be persisted when write buffering triggers bulk flushes. This creates inconsistent behavior vs
immediate writes (set() throws) and vs other drivers that constrain keys at the schema level.
Agent Prompt
## Issue description
`CloudflareD1DB.set()` rejects keys longer than 100 chars, but `CloudflareD1DB.doBulk()` does not. Because the cache/buffer layer prefers `doBulk()` for multi-op flushes, long keys can be persisted successfully (and without throwing) whenever buffering is enabled.

## Issue Context
- In this driver, the `store` table schema does not enforce a 100-char limit (`key TEXT ...`).
- The cache/buffer layer uses `wrappedDB.doBulk(ops)` for multi-op flushes, bypassing `wrappedDB.set()`.

## Fix Focus Areas
- databases/cloudflare_d1_db.ts[72-135]
- lib/CacheAndBufferLayer.ts[489-555]

## What to change
1. Enforce the same key length validation in `doBulk()` for `set` operations (and consider validating `remove` too for consistency).
   - If any key is >100 chars, throw an Error so the cache layer falls back to individual writes (which will then consistently fail via `set()`), rather than silently persisting invalid keys.
2. (Optional but recommended) Align the D1 schema with other drivers by adding a DB-level constraint, e.g. `CHECK(length(key) <= 100)` on the key column in the CREATE TABLE statement. (Note: `VARCHAR(100)` is not sufficient on SQLite for enforcement.)

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


close(): void {
this._d1db = null;
}
}
5 changes: 5 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export type {Logger} from './lib/logging';

export type DatabaseType =
| 'cassandra'
| 'cloudflare_d1'
| 'couch'
| 'dirty'
| 'dirtygit'
Expand Down Expand Up @@ -103,6 +104,10 @@ export class Database {
return new (await import('./databases/redis_db')).default(this.dbSettings as Settings);
case 'cassandra':
return new (await import('./databases/cassandra_db')).default(this.dbSettings as Settings);
case 'cloudflare_d1': {
const {default: CloudflareD1DB} = await import('./databases/cloudflare_d1_db');
return new CloudflareD1DB(this.dbSettings as import('./databases/cloudflare_d1_db').D1Settings);
}
case 'dirty':
return new (await import('./databases/dirty_db')).default(this.dbSettings as Settings);
case 'dirtygit':
Expand Down
2 changes: 2 additions & 0 deletions lib/AbstractDatabase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export type Settings = {
data?: unknown;
table?: string;
db?: string;
/** Cloudflare D1Database binding (used by the cloudflare_d1 driver). */
d1Database?: unknown;
idleTimeoutMillis?: number;
min?: number;
max?: number;
Expand Down
6 changes: 6 additions & 0 deletions test/cloudflare_d1/test.cloudflared1.spec.ts
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');
});
8 changes: 8 additions & 0 deletions test/lib/databases.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
import os from 'os';
import {MockD1Database} from './mock_d1';

type DatabaseType ={
[key:string]:any
}

export const databases:DatabaseType = {
memory: {},
cloudflare_d1: {
// A fresh MockD1Database is constructed for each property access so that
// every test gets its own isolated in-memory SQLite instance.
get d1Database() {
return new MockD1Database();
},
},
dirty: {
filename: `${os.tmpdir()}/ueberdb-test.db`,
speeds: {
Expand Down
81 changes: 81 additions & 0 deletions test/lib/mock_d1.ts
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};
}
}