WIP! A BB-style forum, on the ATmosphere! We're still working... we'll be back soon when we have something to show off!
node typescript hono htmx atproto
at root/atb-56-theme-caching-layer 56 lines 2.2 kB view raw
1import { drizzle as drizzlePg } from "drizzle-orm/postgres-js"; 2import { drizzle as drizzleSqlite } from "drizzle-orm/libsql"; 3import { migrate as libsqlMigrate } from "drizzle-orm/libsql/migrator"; 4import { createClient } from "@libsql/client"; 5import postgres from "postgres"; 6import * as pgSchema from "./schema.js"; 7import * as sqliteSchema from "./schema.sqlite.js"; 8 9/** 10 * Create a Drizzle database instance from a connection URL. 11 * 12 * URL prefix determines the driver: 13 * postgres:// or postgresql:// → postgres.js (PostgreSQL) 14 * file: → @libsql/client (SQLite file) 15 * file::memory: → @libsql/client (SQLite in-memory, tests) 16 * libsql:// → @libsql/client (Turso cloud) 17 */ 18export function createDb(databaseUrl: string): Database { 19 if (databaseUrl.startsWith("postgres")) { 20 return drizzlePg(postgres(databaseUrl), { schema: pgSchema }) as Database; 21 } 22 return drizzleSqlite( 23 createClient({ url: databaseUrl }), 24 { schema: sqliteSchema } 25 ) as unknown as Database; 26} 27 28/** 29 * Run SQLite migrations on a database created with createDb(). 30 * Uses the same drizzle-orm instance as createDb() to avoid cross-package 31 * module boundary issues that occur when using the migrator from a different 32 * drizzle-orm installation. 33 * 34 * Only works with SQLite databases (file: or libsql: URLs). 35 * For PostgreSQL, use drizzle-kit migrate directly. 36 * 37 * @param db - Database created with createDb() for a SQLite URL 38 * @param migrationsFolder - Absolute path to the folder containing migration SQL files 39 */ 40export async function runSqliteMigrations( 41 db: Database, 42 migrationsFolder: string 43): Promise<void> { 44 await libsqlMigrate(db as any, { migrationsFolder }); 45} 46 47// Database type uses the Postgres schema as the TypeScript source of truth. 48// Both dialects produce compatible column names and TypeScript types, 49// so the cast is safe at the app layer. 50export type Database = ReturnType<typeof drizzlePg<typeof pgSchema>>; 51 52export type Transaction = Parameters<Parameters<Database["transaction"]>[0]>[0]; 53 54export type DbOrTransaction = Database | Transaction; 55 56export * from "./schema.js";