Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

index.ts

42 lines1.6 KB

1import { drizzle } from 'drizzle-orm/d1'
2​
3import * as schema from './schema.ts'
4​
5export interface DbEnv {
6 DB: D1Database
7}
8​
9export interface GetDbOptions {
10 /**
11 * Public read. Opens a D1 session with `first-unconstrained`, so the
12 * query can run on a read replica once read replication is enabled.
13 * Sessions are safe before that: every query still goes to the primary.
14 * Enable replication on the database only after #554, so replicas copy
15 * the US primary (`read_replication.mode: auto` in the dashboard or API).
16 * There is no wrangler.jsonc switch for it.
17 *
18 * Leave this off for auth, admin, subscriptions, crons, webhooks, and
19 * the changes feed. Those need the latest write.
20 *
21 * Agent JWT `jti`s are not rows in D1. `@better-auth/agent-auth` stores
22 * them in an in-process has-then-add cache (this service sets no
23 * `secondaryStorage`), so a lagging replica cannot accept one twice.
24 * Auth still uses the primary because its other writes must read what
25 * they just wrote.
26 */
27 replica?: boolean
29​
30// Workers have no module-scope env: the D1 binding only exists on the env
31// object passed to fetch/scheduled handlers, so the db client is built per
32// request rather than exported as a singleton.
33export function getDb(env: DbEnv, options?: GetDbOptions) {
34 // Drizzle's D1 driver only calls prepare() and batch(), which a session
35 // has. The session type omits exec()/dump(), so it is not assignable.
36 const client = options?.replica
37 ? (env.DB.withSession('first-unconstrained') as unknown as D1Database)
38 : env.DB
39 return drizzle(client, { schema })
41​
42export type Db = ReturnType<typeof getDb>