// The hub's database: Postgres in production (DATABASE_URL), or PGlite (Postgres compiled to WebAssembly, in // process) for development and tests, so nothing needs installing. import { drizzle as drizzleBun } from "drizzle-orm/bun-sql"; import { migrate as migrateBun } from "drizzle-orm/bun-sql/migrator"; import { drizzle as drizzlePglite } from "drizzle-orm/pglite"; import { migrate as migratePglite } from "drizzle-orm/pglite/migrator"; import { PGlite } from "@electric-sql/pglite"; import { SQL } from "bun"; import { mkdirSync } from "node:fs"; import { fileURLToPath } from "node:url"; import * as schema from "./schema"; export { schema }; export type { DecorationItem, FileEntry, ParentInfo, RoomModerator, SceneItem } from "./schema"; export * from "drizzle-orm"; const migrationsFolder = fileURLToPath(new URL("../drizzle", import.meta.url)); export type Database = ReturnType>; /** * Opens the database and brings its schema up to date. * @param url a postgres:// URL, "memory" (a fresh in-process database), or a directory for PGlite's files. */ export async function openDatabase(url: string): Promise<{ db: Database; close: () => Promise }> { if (url.startsWith("postgres://") || url.startsWith("postgresql://")) { const client = new SQL(url); const db = drizzleBun({ client, schema }); await migrateBun(db, { migrationsFolder }); // Both drivers speak the same query builder; the PGlite type stands for both. return { db: db as unknown as Database, close: async () => client.close() }; } if (url !== "memory") mkdirSync(url, { recursive: true }); const client = url === "memory" ? new PGlite() : new PGlite(url); const db = drizzlePglite({ client, schema }); await migratePglite(db, { migrationsFolder }); return { db, close: async () => client.close() }; }