File
Blob: src/worker/db/d1/client.ts
| 1 | import { drizzle, type DrizzleD1Database } from "drizzle-orm/d1"; |
| 2 | |
| 3 | import * as schema from "./schema"; |
| 4 | |
| 5 | export type D1SessionInput = D1SessionConstraint | string; |
| 6 | export type D1Client = D1Database | D1DatabaseSession; |
| 7 | export type Db = DrizzleD1Database<typeof schema> & { $client: D1Client }; |
| 8 | |
| 9 | export function createDb(d1: D1Client): Db { |
| 10 | return drizzle(d1 as D1Database, { schema }) as Db; |
| 11 | } |
| 12 | |
| 13 | export function createSessionDb( |
| 14 | d1: D1Database, |
| 15 | constraintOrBookmark: D1SessionInput, |
| 16 | ): { db: Db; session: D1DatabaseSession } { |
| 17 | const session = d1.withSession(constraintOrBookmark); |
| 18 | return { db: createDb(session), session }; |
| 19 | } |
| 20 | |
| 21 | export function selectHttpSessionConstraint(method: string, bookmark?: string | null): D1SessionInput { |
| 22 | switch (method.toUpperCase()) { |
| 23 | case "POST": |
| 24 | case "PATCH": |
| 25 | case "PUT": |
| 26 | case "DELETE": |
| 27 | return "first-primary"; |
| 28 | default: |
| 29 | return bookmark?.trim() || "first-unconstrained"; |
| 30 | } |
| 31 | } |