Migrate stack to SQLite and set Coolify defaults
This commit is contained in:
@@ -1,37 +1,54 @@
|
||||
import { drizzle } from 'drizzle-orm/node-postgres';
|
||||
import { Pool } from 'pg';
|
||||
import { mkdirSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
import { Database } from 'bun:sqlite';
|
||||
import { drizzle } from 'drizzle-orm/bun-sqlite';
|
||||
import { schema } from './schema';
|
||||
|
||||
type AppDrizzleDb = ReturnType<typeof createDb>;
|
||||
|
||||
declare global {
|
||||
// eslint-disable-next-line no-var
|
||||
var __fiscalPgPool: Pool | undefined;
|
||||
var __fiscalSqliteClient: Database | undefined;
|
||||
// eslint-disable-next-line no-var
|
||||
var __fiscalDrizzleDb: AppDrizzleDb | undefined;
|
||||
}
|
||||
|
||||
function getConnectionString() {
|
||||
const connectionString = process.env.DATABASE_URL?.trim();
|
||||
if (!connectionString) {
|
||||
throw new Error('DATABASE_URL is required for PostgreSQL.');
|
||||
function getDatabasePath() {
|
||||
const raw = process.env.DATABASE_URL?.trim() || 'file:data/fiscal.sqlite';
|
||||
let databasePath = raw.startsWith('file:') ? raw.slice(5) : raw;
|
||||
|
||||
if (databasePath.startsWith('///')) {
|
||||
databasePath = databasePath.slice(2);
|
||||
}
|
||||
|
||||
return connectionString;
|
||||
if (!databasePath) {
|
||||
throw new Error('DATABASE_URL must point to a SQLite file path.');
|
||||
}
|
||||
|
||||
return databasePath;
|
||||
}
|
||||
|
||||
export function getPool() {
|
||||
if (!globalThis.__fiscalPgPool) {
|
||||
globalThis.__fiscalPgPool = new Pool({
|
||||
connectionString: getConnectionString()
|
||||
});
|
||||
export function getSqliteClient() {
|
||||
if (!globalThis.__fiscalSqliteClient) {
|
||||
const databasePath = getDatabasePath();
|
||||
|
||||
if (databasePath !== ':memory:') {
|
||||
mkdirSync(dirname(databasePath), { recursive: true });
|
||||
}
|
||||
|
||||
const client = new Database(databasePath, { create: true });
|
||||
client.exec('PRAGMA foreign_keys = ON;');
|
||||
client.exec('PRAGMA journal_mode = WAL;');
|
||||
client.exec('PRAGMA busy_timeout = 5000;');
|
||||
|
||||
globalThis.__fiscalSqliteClient = client;
|
||||
}
|
||||
|
||||
return globalThis.__fiscalPgPool;
|
||||
return globalThis.__fiscalSqliteClient;
|
||||
}
|
||||
|
||||
function createDb() {
|
||||
return drizzle(getPool(), { schema });
|
||||
return drizzle(getSqliteClient(), { schema });
|
||||
}
|
||||
|
||||
export const db = globalThis.__fiscalDrizzleDb ?? createDb();
|
||||
|
||||
Reference in New Issue
Block a user