Skip to content

Commit

Permalink
fix: d1 shim fallback logic
Browse files Browse the repository at this point in the history
  • Loading branch information
JacobLinCool committed Dec 14, 2023
1 parent fe0598d commit cd94990
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/tricky-garlics-pump.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"d1-manager": patch
---

Change D1 shim fallback logic
10 changes: 5 additions & 5 deletions src/lib/server/d1.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
// adapted from https://github.com/cloudflare/workers-sdk/blob/main/packages/wrangler/templates/d1-beta-facade.js
export class D1Database {
export class D1Shim {
binding: Fetcher;

constructor(binding: Fetcher) {
Expand Down Expand Up @@ -102,11 +102,11 @@ export class D1Database {
}

class D1PreparedStatement {
database: D1Database;
database: D1Shim;
statement: any;
params: any;

constructor(database: D1Database, statement: any, values?: any) {
constructor(database: D1Shim, statement: any, values?: any) {
this.database = database;
this.statement = statement;
this.params = values || [];
Expand Down Expand Up @@ -160,7 +160,7 @@ class D1PreparedStatement {
async all() {
return firstIfArray(await this.database._send("/query", this.statement, this.params));
}
async raw() {
async raw<T>(): Promise<T[]> {
const s = firstIfArray(await this.database._send("/query", this.statement, this.params));
const raw = [];
for (const r in s.results) {
Expand All @@ -169,7 +169,7 @@ class D1PreparedStatement {
});
raw.push(entry);
}
return raw;
return raw as any;
}
}

Expand Down
11 changes: 8 additions & 3 deletions src/lib/server/db/dbms.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
import { D1Database } from "../d1";
import type { D1Database } from "@cloudflare/workers-types";
import { D1Shim } from "../d1";

export function DBMS(env: Record<string, Fetcher | string>): Record<string, D1Database> {
export function DBMS(
env: Record<string, Fetcher | D1Database | string>,
): Record<string, D1Database> {
const keys = Object.keys(env).filter(
(k) => k.startsWith("DB") || k.startsWith("__D1_BETA__DB"),
);
console.log("Database Bindings:", keys.join(", "));

const results: Record<string, D1Database> = {};
for (const k of keys) {
const e = env[k];
if (typeof e === "string") {
continue;
}
const db = "fetch" in e ? new D1Database(e) : e;
const db = "prepare" in e ? e : new D1Shim(e);
results[k.replace(/^(__D1_BETA__)?DB_?/, "") || "default"] = db;
}
return results;
Expand Down

0 comments on commit cd94990

Please sign in to comment.