Files
umami/scripts/check-db.js
Aitor Alonso 3070189537 fix: fixes 4186
Some database providers, like supabase, provides two URLs to access the database. A main URL behind pgBouncer's for load balancing, and a direct separated URL to perform migrations (running DDL operations), as does not support
advisory locks or multi-statement DDL required by migrations.

Before v3.1.0, adding `directUrl` along with `url` to `prisma/schema.prisma` was enought. Now, I'm making a commit to use direct url when set
2026-04-20 21:58:54 +02:00

92 lines
2.2 KiB
JavaScript

/* eslint-disable no-console */
import 'dotenv/config';
import { execSync } from 'node:child_process';
import { PrismaPg } from '@prisma/adapter-pg';
import chalk from 'chalk';
import semver from 'semver';
import { PrismaClient } from '../generated/prisma/client.js';
const MIN_VERSION = '9.4.0';
if (process.env.SKIP_DB_CHECK) {
console.log('Skipping database check.');
process.exit(0);
}
const url = new URL(process.env.DATABASE_URL);
const adapter = new PrismaPg(
{ connectionString: url.toString() },
{ schema: url.searchParams.get('schema') },
);
const prisma = new PrismaClient({ adapter });
function success(msg) {
console.log(chalk.greenBright(`${msg}`));
}
function error(msg) {
console.log(chalk.redBright(`${msg}`));
}
async function checkEnv() {
if (!process.env.DATABASE_URL) {
throw new Error('DATABASE_URL is not defined.');
} else {
success('DATABASE_URL is defined.');
}
if (process.env.REDIS_URL) {
success('REDIS_URL is defined.');
}
}
async function checkConnection() {
try {
await prisma.$connect();
success('Database connection successful.');
} catch (e) {
throw new Error(`Unable to connect to the database: ${e.message}`);
}
}
async function checkDatabaseVersion() {
const query = await prisma.$queryRaw`select version() as version`;
const version = semver.valid(semver.coerce(query[0].version));
if (semver.lt(version, MIN_VERSION)) {
throw new Error(
`Database version is not compatible. Please upgrade to ${MIN_VERSION} or greater.`,
);
}
success('Database version check successful.');
}
async function applyMigration() {
if (!process.env.SKIP_DB_MIGRATION) {
const directUrl = process.env.DIRECT_DATABASE_URL || process.env.DATABASE_URL;
console.log(execSync('prisma migrate deploy', { env: { ...process.env, DATABASE_URL: directUrl } }).toString());
success('Database is up to date.');
}
}
(async () => {
let err = false;
for (const fn of [checkEnv, checkConnection, checkDatabaseVersion, applyMigration]) {
try {
await fn();
} catch (e) {
error(e.message);
err = true;
} finally {
if (err) {
process.exit(1);
}
}
}
})();