aboutsummaryrefslogtreecommitdiff
path: root/scripts/check-db.js
diff options
context:
space:
mode:
authorFuwn <[email protected]>2026-01-24 13:09:50 +0000
committerFuwn <[email protected]>2026-01-24 13:09:50 +0000
commit396acf3bbbe00a192cb0ea0a9ccf91b1d8d2850b (patch)
treeb9df4ca6a70db45cfffbae6fdd7252e20fb8e93c /scripts/check-db.js
downloadumami-396acf3bbbe00a192cb0ea0a9ccf91b1d8d2850b.tar.xz
umami-396acf3bbbe00a192cb0ea0a9ccf91b1d8d2850b.zip
Initial commitHEADmain
Created from https://vercel.com/new
Diffstat (limited to 'scripts/check-db.js')
-rw-r--r--scripts/check-db.js90
1 files changed, 90 insertions, 0 deletions
diff --git a/scripts/check-db.js b/scripts/check-db.js
new file mode 100644
index 0000000..68374f6
--- /dev/null
+++ b/scripts/check-db.js
@@ -0,0 +1,90 @@
+/* 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) {
+ console.log(execSync('prisma migrate deploy').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);
+ }
+ }
+ }
+})();