Files
sim/packages/db/db.ts
T
51733b8d85 fix(db): correct misleading error message when DATABASE_REPLICA_URL is malformed (#5023)
* v0.6.29: login improvements, posthog telemetry (#4026)

* feat(posthog): Add tracking on mothership abort (#4023)

Co-authored-by: Theodore Li <theo@sim.ai>

* fix(login): fix captcha headers for manual login  (#4025)

* fix(signup): fix turnstile key loading

* fix(login): fix captcha header passing

* Catch user already exists, remove login form captcha

* fix(db): correct misleading error message when DATABASE_REPLICA_URL is malformed

The error message said reads fall back to the primary when unset, but the
code throws a fatal error instead. The misleading parenthetical contradicted
actual behavior and could waste time during incident response when an operator
sees this message and expects graceful degradation.

---------

Co-authored-by: Waleed <walif6@gmail.com>
Co-authored-by: Theodore Li <theodoreqili@gmail.com>
Co-authored-by: Siddharth Ganesan <33737564+Sg312@users.noreply.github.com>
Co-authored-by: Vikhyath Mondreti <vikhyathvikku@gmail.com>
Co-authored-by: Theodore Li <theo@sim.ai>
2026-06-13 09:18:51 -07:00

43 lines
1.3 KiB
TypeScript

import { drizzle } from 'drizzle-orm/postgres-js'
import postgres from 'postgres'
import * as schema from './schema'
import { instrumentPoolClient } from './tx-tripwire'
const connectionString = process.env.DATABASE_URL!
if (!connectionString) {
throw new Error('Missing DATABASE_URL environment variable')
}
const poolOptions = {
prepare: false,
idle_timeout: 20,
connect_timeout: 30,
onnotice: () => {},
}
const postgresClient = instrumentPoolClient(
postgres(connectionString, { ...poolOptions, max: 15 }),
'db'
)
export const db = drizzle(postgresClient, { schema })
/**
* Opt-in read-replica client for reads that tolerate bounded staleness and have
* no read-your-writes dependency (logs, exports, dashboard aggregations). Never
* for auth, workflow state, or billing enforcement. Falls back to the primary
* when `DATABASE_REPLICA_URL` is unset, so call sites never branch.
*/
const replicaUrl = process.env.DATABASE_REPLICA_URL
if (replicaUrl && !/^postgres(ql)?:\/\//.test(replicaUrl)) {
throw new Error(
'DATABASE_REPLICA_URL is set but is not a postgres:// DSN — fix the URL or unset the variable'
)
}
export const dbReplica: typeof db = replicaUrl
? drizzle(instrumentPoolClient(postgres(replicaUrl, { ...poolOptions, max: 10 }), 'dbReplica'), {
schema,
})
: db