Skip to content
This repository was archived by the owner on Mar 13, 2025. It is now read-only.

Commit 2d0fbc6

Browse files
authored
Implement D1Database using D1JS and D1 API (#480)
Previously, Miniflare had its own implementations of `BetaDatabase` and `Statement`. These were subtly different to the implementations in the D1 Wrangler shim D1JS, causing behaviour mismatches. This change switches the implementation to use the shim, with Miniflare implementing the underlying D1 HTTP API instead. We'll need to do this anyway when adding D1 support to Miniflare 3 using `workerd`. Specific changes: - Throw when calling `D1PreparedStatement#run()` with statements that return data, closes #441 - Fix response envelope format, closes #442 and cloudflare/workers-sdk#2504 - Fix binding/return of `BLOB`-typed values, closes cloudflare/workers-sdk#2527 - Fix `D1Database#raw()` return, closes cloudflare/workers-sdk#2238 (already fixed in #474) - Add support for `D1Database#dump()` - Run `D1Database#{batch,exec}()` statements in implicit transaction - Only run first statement when calling `D1PreparedStatement#{first,run,all,raw}()`
1 parent 24916c6 commit 2d0fbc6

File tree

12 files changed

+993
-229
lines changed

12 files changed

+993
-229
lines changed

packages/core/src/standards/http.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -752,7 +752,7 @@ class MiniflareDispatcher extends Dispatcher {
752752
}
753753

754754
export async function fetch(
755-
this: Dispatcher | void,
755+
this: Dispatcher | unknown,
756756
input: RequestInfo,
757757
init?: RequestInit
758758
): Promise<Response> {

packages/d1/src/api.ts

+204
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
1+
import crypto from "crypto";
2+
import fs from "fs/promises";
3+
import os from "os";
4+
import path from "path";
5+
import { performance } from "perf_hooks";
6+
import { Request, RequestInfo, RequestInit, Response } from "@miniflare/core";
7+
import type { SqliteDB } from "@miniflare/shared";
8+
import type { Statement as SqliteStatement } from "better-sqlite3";
9+
import splitSqlQuery from "./splitter";
10+
11+
// query
12+
interface SingleQuery {
13+
sql: string;
14+
params?: any[] | null;
15+
}
16+
17+
// response
18+
interface ErrorResponse {
19+
error: string;
20+
success: false;
21+
served_by: string;
22+
}
23+
interface ResponseMeta {
24+
duration: number;
25+
last_row_id: number | null;
26+
changes: number | null;
27+
served_by: string;
28+
internal_stats: null;
29+
}
30+
interface SuccessResponse {
31+
results: any;
32+
duration: number;
33+
lastRowId: number | null;
34+
changes: number | null;
35+
success: true;
36+
served_by: string;
37+
meta: ResponseMeta | null;
38+
}
39+
40+
const served_by = "miniflare.db";
41+
42+
function ok(results: any, start: number): SuccessResponse {
43+
const duration = performance.now() - start;
44+
return {
45+
results,
46+
duration,
47+
// These are all `null`ed out in D1
48+
lastRowId: null,
49+
changes: null,
50+
success: true,
51+
served_by,
52+
meta: {
53+
duration,
54+
last_row_id: null,
55+
changes: null,
56+
served_by,
57+
internal_stats: null,
58+
},
59+
};
60+
}
61+
function err(error: any): ErrorResponse {
62+
return {
63+
error: String(error),
64+
success: false,
65+
served_by,
66+
};
67+
}
68+
69+
type QueryRunner = (query: SingleQuery) => SuccessResponse;
70+
71+
function normaliseParams(params: SingleQuery["params"]): any[] {
72+
return (params ?? []).map((param) =>
73+
// If `param` is an array, assume it's a byte array
74+
Array.isArray(param) ? new Uint8Array(param) : param
75+
);
76+
}
77+
function normaliseResults(rows: any[]): any[] {
78+
return rows.map((row) =>
79+
Object.fromEntries(
80+
Object.entries(row).map(([key, value]) => [
81+
key,
82+
// If `value` is an array, convert it to a regular numeric array
83+
value instanceof Buffer ? Array.from(value) : value,
84+
])
85+
)
86+
);
87+
}
88+
89+
const DOESNT_RETURN_DATA_MESSAGE =
90+
"The columns() method is only for statements that return data";
91+
const EXECUTE_RETURNS_DATA_MESSAGE =
92+
"SQL execute error: Execute returned results - did you mean to call query?";
93+
function returnsData(stmt: SqliteStatement): boolean {
94+
try {
95+
stmt.columns();
96+
return true;
97+
} catch (e) {
98+
// `columns()` fails on statements that don't return data
99+
if (e instanceof TypeError && e.message === DOESNT_RETURN_DATA_MESSAGE) {
100+
return false;
101+
}
102+
throw e;
103+
}
104+
}
105+
106+
export class D1DatabaseAPI {
107+
constructor(private readonly db: SqliteDB) {}
108+
109+
#query: QueryRunner = (query) => {
110+
const start = performance.now();
111+
// D1 only respects the first statement
112+
const sql = splitSqlQuery(query.sql)[0];
113+
const stmt = this.db.prepare(sql);
114+
const params = normaliseParams(query.params);
115+
let results: any[];
116+
if (returnsData(stmt)) {
117+
results = stmt.all(params);
118+
} else {
119+
// `/query` does support queries that don't return data,
120+
// returning `[]` instead of `null`
121+
stmt.run(params);
122+
results = [];
123+
}
124+
return ok(normaliseResults(results), start);
125+
};
126+
127+
#execute: QueryRunner = (query) => {
128+
const start = performance.now();
129+
// D1 only respects the first statement
130+
const sql = splitSqlQuery(query.sql)[0];
131+
const stmt = this.db.prepare(sql);
132+
// `/execute` only supports queries that don't return data
133+
if (returnsData(stmt)) throw new Error(EXECUTE_RETURNS_DATA_MESSAGE);
134+
const params = normaliseParams(query.params);
135+
stmt.run(params);
136+
return ok(null, start);
137+
};
138+
139+
async #handleQueryExecute(
140+
request: Request,
141+
runner: QueryRunner
142+
): Promise<Response> {
143+
// `D1Database#batch()` will call `/query` with an array of queries
144+
const query = await request.json<SingleQuery | SingleQuery[]>();
145+
let results: SuccessResponse | SuccessResponse[];
146+
if (Array.isArray(query)) {
147+
// Run batches in an implicit transaction. Note we have to use savepoints
148+
// here as the SQLite transaction stack may not be empty if we're running
149+
// inside the Miniflare testing environment, and nesting regular
150+
// transactions is not permitted.
151+
const savepointName = `MINIFLARE_D1_BATCH_${Date.now()}_${Math.floor(
152+
Math.random() * Number.MAX_SAFE_INTEGER
153+
)}`;
154+
this.db.exec(`SAVEPOINT ${savepointName};`); // BEGIN TRANSACTION;
155+
try {
156+
results = query.map(runner);
157+
this.db.exec(`RELEASE ${savepointName};`); // COMMIT;
158+
} catch (e) {
159+
this.db.exec(`ROLLBACK TO ${savepointName};`); // ROLLBACK;
160+
this.db.exec(`RELEASE ${savepointName};`);
161+
throw e;
162+
}
163+
} else {
164+
results = runner(query);
165+
}
166+
return Response.json(results);
167+
}
168+
169+
async #handleDump(): Promise<Response> {
170+
// `better-sqlite3` requires us to back up to a file, so create a temp one
171+
const random = crypto.randomBytes(8).toString("hex");
172+
const tmpPath = path.join(os.tmpdir(), `miniflare-d1-dump-${random}.db`);
173+
await this.db.backup(tmpPath);
174+
const buffer = await fs.readFile(tmpPath);
175+
// Delete file in the background, ignore errors as they don't really matter
176+
void fs.unlink(tmpPath).catch(() => {});
177+
return new Response(buffer, {
178+
headers: { "Content-Type": "application/octet-stream" },
179+
});
180+
}
181+
182+
async fetch(input: RequestInfo, init?: RequestInit) {
183+
// `D1Database` may call fetch with a relative URL, so resolve it, making
184+
// sure to only construct a `new URL()` once.
185+
if (typeof input === "string") input = new URL(input, "http://localhost");
186+
const request = new Request(input, init);
187+
if (!(input instanceof URL)) input = new URL(request.url);
188+
const pathname = input.pathname;
189+
190+
if (request.method !== "POST") return new Response(null, { status: 405 });
191+
try {
192+
if (pathname === "/query") {
193+
return await this.#handleQueryExecute(request, this.#query);
194+
} else if (pathname === "/execute") {
195+
return await this.#handleQueryExecute(request, this.#execute);
196+
} else if (pathname === "/dump") {
197+
return await this.#handleDump();
198+
}
199+
} catch (e) {
200+
return Response.json(err(e));
201+
}
202+
return new Response(null, { status: 404 });
203+
}
204+
}

0 commit comments

Comments
 (0)