···11-import { drizzle } from "drizzle-orm/postgres-js";
11+import { drizzle as drizzlePg } from "drizzle-orm/postgres-js";
22+import { drizzle as drizzleSqlite } from "drizzle-orm/libsql";
33+import { createClient } from "@libsql/client";
24import postgres from "postgres";
33-import * as schema from "./schema.js";
55+import * as pgSchema from "./schema.js";
66+import * as sqliteSchema from "./schema.sqlite.js";
4755-export function createDb(databaseUrl: string) {
66- const client = postgres(databaseUrl);
77- return drizzle(client, { schema });
88+/**
99+ * Create a Drizzle database instance from a connection URL.
1010+ *
1111+ * URL prefix determines the driver:
1212+ * postgres:// or postgresql:// → postgres.js (PostgreSQL)
1313+ * file: → @libsql/client (SQLite file)
1414+ * file::memory: → @libsql/client (SQLite in-memory, tests)
1515+ * libsql:// → @libsql/client (Turso cloud)
1616+ */
1717+export function createDb(databaseUrl: string): Database {
1818+ if (databaseUrl.startsWith("postgres")) {
1919+ return drizzlePg(postgres(databaseUrl), { schema: pgSchema }) as Database;
2020+ }
2121+ return drizzleSqlite(
2222+ createClient({ url: databaseUrl }),
2323+ { schema: sqliteSchema }
2424+ ) as unknown as Database;
825}
9261010-export type Database = ReturnType<typeof createDb>;
2727+// Database type uses the Postgres schema as the TypeScript source of truth.
2828+// Both dialects produce compatible column names and TypeScript types,
2929+// so the cast is safe at the app layer.
3030+export type Database = ReturnType<typeof drizzlePg<typeof pgSchema>>;
11311212-/**
1313- * Transaction type extracted from Drizzle's database instance.
1414- * Use this when you need to work with a transaction object directly.
1515- */
1616-export type Transaction = Parameters<Parameters<Database['transaction']>[0]>[0];
3232+export type Transaction = Parameters<Parameters<Database["transaction"]>[0]>[0];
17331818-/**
1919- * Union type for functions that need to work with either the database
2020- * instance or an active transaction. This is useful for helper functions
2121- * that can be called both standalone and within a transaction context.
2222- *
2323- * Example:
2424- * ```typescript
2525- * async function getUser(id: string, dbOrTx: DbOrTransaction = db) {
2626- * return dbOrTx.select().from(users).where(eq(users.id, id));
2727- * }
2828- *
2929- * // Can be called standalone
3030- * await getUser('123', db);
3131- *
3232- * // Or within a transaction
3333- * await db.transaction(async (tx) => {
3434- * await getUser('123', tx);
3535- * });
3636- * ```
3737- */
3834export type DbOrTransaction = Database | Transaction;
39354036export * from "./schema.js";