forked from umami-software/umami
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck-db.js
105 lines (86 loc) · 2.46 KB
/
check-db.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/* eslint-disable no-console */
require('dotenv').config();
const { PrismaClient } = require('@prisma/client');
const chalk = require('chalk');
const { execSync } = require('child_process');
const semver = require('semver');
if (process.env.SKIP_DB_CHECK) {
console.log('Skipping database check.');
process.exit(0);
}
function getDatabaseType(url = process.env.DATABASE_URL) {
const type = url && url.split(':')[0];
if (type === 'postgres') {
return 'postgresql';
}
return type;
}
const prisma = new PrismaClient();
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.');
}
}
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));
const databaseType = getDatabaseType();
const minVersion = databaseType === 'postgresql' ? '9.4.0' : '5.7.0';
if (semver.lt(version, minVersion)) {
throw new Error(
`Database version is not compatible. Please upgrade ${databaseType} version to ${minVersion} or greater`,
);
}
success('Database version check successful.');
}
async function checkV1Tables() {
try {
// check for v1 migrations before v2 release date
const record =
await prisma.$queryRaw`select * from _prisma_migrations where started_at < '2023-04-17'`;
if (record.length > 0) {
error(
'Umami v1 tables detected. For how to upgrade from v1 to v2 go to https://umami.is/docs/migrate-v1-v2.',
);
process.exit(1);
}
} catch (e) {
// Ignore
}
}
async function applyMigration() {
console.log(execSync('prisma migrate deploy').toString());
success('Database is up to date.');
}
(async () => {
let err = false;
for (let fn of [checkEnv, checkConnection, checkDatabaseVersion, checkV1Tables, applyMigration]) {
try {
await fn();
} catch (e) {
error(e.message);
err = true;
} finally {
await prisma.$disconnect();
if (err) {
process.exit(1);
}
}
}
})();