umami/scripts/check-db.js

94 lines
2.2 KiB
JavaScript
Raw Normal View History

2022-06-19 09:07:01 +02:00
require('dotenv').config();
const { PrismaClient } = require('@prisma/client');
2022-06-22 10:50:33 +02:00
const chalk = require('chalk');
const spawn = require('cross-spawn');
2022-06-28 07:09:47 +02:00
const { execSync } = require('child_process');
2022-06-19 09:07:01 +02:00
2022-06-28 08:08:58 +02:00
const prisma = new PrismaClient();
2022-06-22 10:50:33 +02:00
function success(msg) {
console.log(chalk.greenBright(`${msg}`));
}
async function checkEnv() {
if (!process.env.DATABASE_URL) {
throw new Error('DATABASE_URL is not defined.');
} else {
success('DATABASE_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.');
}
2022-06-19 09:07:01 +02:00
}
2022-06-22 10:50:33 +02:00
async function checkTables() {
try {
await prisma.account.findFirst();
success('Database tables found.');
} catch (e) {
2022-06-28 07:09:47 +02:00
console.log('Adding tables...');
2022-06-28 07:09:47 +02:00
console.log(execSync('prisma migrate deploy').toString());
2022-06-22 10:50:33 +02:00
}
}
async function run(cmd, args) {
const buffer = [];
const proc = spawn(cmd, args);
return new Promise((resolve, reject) => {
proc.stdout.on('data', data => buffer.push(data));
proc.on('error', () => {
reject(new Error('Failed to run Prisma.'));
});
proc.on('exit', () => resolve(buffer.join('')));
2022-06-19 09:07:01 +02:00
});
2022-06-22 10:50:33 +02:00
}
async function checkMigrations() {
const output = await run('prisma', ['migrate', 'status']);
2022-06-28 08:00:14 +02:00
const missingMigrations = output.includes('have not yet been applied');
const missingInitialMigration = output.includes('01_init');
2022-06-22 10:50:33 +02:00
const notManaged = output.includes('The current database is not managed');
2022-06-28 07:09:47 +02:00
if (notManaged || missingMigrations) {
console.log('Running update...');
2022-06-22 10:50:33 +02:00
if (missingInitialMigration) {
console.log(execSync('prisma migrate resolve --applied "01_init"').toString());
}
console.log(execSync('prisma migrate deploy').toString());
2022-06-22 10:50:33 +02:00
}
success('Database is up to date.');
}
(async () => {
let err = false;
for (let fn of [checkEnv, checkConnection, checkTables, checkMigrations]) {
try {
await fn();
} catch (e) {
console.log(chalk.red(`${e.message}`));
err = true;
} finally {
await prisma.$disconnect();
if (err) {
process.exit(1);
}
}
}
})();