Skip to content
File

Blob: src/worker/db/d1/client.ts

typescript27 lines
1import { drizzle, type DrizzleD1Database } from "drizzle-orm/d1";
2 
3import * as schema from "./schema";
4 
5// Global D1 client. Request-scoped D1 access in Hono routes runs through
6// a per-request `D1DatabaseSession` opened by `requestServicesMiddleware`
7// in `src/worker/routes/hono.ts`; non-request paths (queue tasks in
8// `tasks/context.ts`, plus the defensive fallbacks in `repositories/route.ts`,
9// `auth/gitAuth.ts`, and `auth/pat.ts`) keep plain `D1Database` semantics,
10// which Cloudflare reads as `first-primary` by default. The overload lets
11// both shapes share one helper; drizzle's runtime accepts either, so the
12// cast collapses the overload boundary inside this module only.
13export type D1Executor = D1Database | D1DatabaseSession;
14export type Db<TClient extends D1Executor = D1Executor> = DrizzleD1Database<typeof schema> & {
15 $client: TClient;
16};
17 
18export function createDb(executor: D1Database): Db<D1Database>;
19export function createDb(executor: D1DatabaseSession): Db<D1DatabaseSession>;
20export function createDb(executor: D1Executor): Db {
21 return drizzle(executor as D1Database, { schema });
22}
23 
24// Type alias used by DAL function signatures so callers can pass the
25// session-backed or plain client without changing the helper.
26export type DbExecutor = Db;