server/drizzle/db.ts
Jesse Wierzbinski 138f4fade3
Some checks failed
CodeQL Scan / Analyze (javascript-typescript) (push) Failing after 1s
Build Docker Images / lint (push) Failing after 7s
Build Docker Images / check (push) Failing after 7s
Build Docker Images / tests (push) Failing after 7s
Deploy Docs to GitHub Pages / build (push) Failing after 0s
Build Docker Images / build (server, Dockerfile, ${{ github.repository_owner }}/server) (push) Has been skipped
Build Docker Images / build (worker, Worker.Dockerfile, ${{ github.repository_owner }}/worker) (push) Has been skipped
Deploy Docs to GitHub Pages / Deploy (push) Has been skipped
Mirror to Codeberg / Mirror (push) Failing after 0s
Nix Build / check (push) Failing after 0s
refactor(database): ♻️ Use Bun.SQL instead of pg
2025-04-19 14:15:08 +02:00

82 lines
2.5 KiB
TypeScript

import { getLogger } from "@logtape/logtape";
import { SQL } from "bun";
import chalk from "chalk";
import { type BunSQLDatabase, drizzle } from "drizzle-orm/bun-sql";
import { withReplicas } from "drizzle-orm/pg-core";
import { migrate } from "drizzle-orm/postgres-js/migrator";
import { config } from "~/config.ts";
import * as schema from "./schema.ts";
const primaryDb = new SQL({
host: config.postgres.host,
port: config.postgres.port,
user: config.postgres.username,
password: config.postgres.password,
database: config.postgres.database,
});
const replicas = config.postgres.replicas.map(
(replica) =>
new SQL({
host: replica.host,
port: replica.port,
user: replica.username,
password: replica.password,
database: replica.database,
}),
);
export const db =
(replicas.length ?? 0) > 0
? withReplicas(
drizzle(primaryDb, { schema }),
replicas.map((r) => drizzle(r, { schema })) as [
// biome-ignore lint/style/useNamingConvention: <explanation>
BunSQLDatabase<typeof schema> & { $client: SQL },
// biome-ignore lint/style/useNamingConvention: <explanation>
...(BunSQLDatabase<typeof schema> & { $client: SQL })[],
],
)
: drizzle(primaryDb, { schema });
export const setupDatabase = async (info = true): Promise<void> => {
const logger = getLogger("database");
for (const dbPool of [primaryDb, ...replicas]) {
try {
await dbPool.connect();
} catch (e) {
if (
(e as Error).message ===
"Client has already been connected. You cannot reuse a client."
) {
return;
}
logger.fatal`Failed to connect to database ${chalk.bold(
// Index of the database in the array
replicas.indexOf(dbPool) === -1
? "primary"
: `replica-${replicas.indexOf(dbPool)}`,
)}. Please check your configuration.`;
throw e;
}
}
// Migrate the database
info && logger.info`Migrating database...`;
try {
await migrate(db, {
migrationsFolder: "./drizzle/migrations",
});
} catch (e) {
logger.fatal`Failed to migrate database. Please check your configuration.`;
throw e;
}
info && logger.info`Database migrated`;
};