2021-11-15 17:39:03 +00:00
|
|
|
const app = require('../app');
|
|
|
|
const { Client } = require('pg');
|
2021-11-18 21:13:03 +00:00
|
|
|
const fs = require('fs');
|
2021-11-15 17:39:03 +00:00
|
|
|
|
|
|
|
if (process.env.NODE_ENV !== 'production' || process.env.NODE_ENV !== 'testing') {
|
|
|
|
require('dotenv').config();
|
|
|
|
}
|
|
|
|
|
|
|
|
const client = new Client();
|
2021-11-18 21:13:03 +00:00
|
|
|
client.connect();
|
|
|
|
|
|
|
|
async function executeQuery(query, values = []) {
|
|
|
|
const result = await client.query({
|
|
|
|
rowMode: 'array',
|
|
|
|
text: query,
|
|
|
|
values: values
|
|
|
|
});
|
|
|
|
return result.rows;
|
|
|
|
}
|
|
|
|
|
2021-11-20 23:51:49 +00:00
|
|
|
async function Initialize() {
|
2021-11-18 21:13:03 +00:00
|
|
|
console.log("Initializing database...")
|
|
|
|
const sql = fs.readFileSync('database/init_database.sql').toString();
|
|
|
|
await executeQuery(sql);
|
|
|
|
console.log("Database initialized.")
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
async function checkForDatabaseInitialization() {
|
2021-12-02 19:49:37 +00:00
|
|
|
const databaseIsSetupQuery = `SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'scores'`;
|
|
|
|
let result = await executeQuery(databaseIsSetupQuery);
|
2021-11-18 21:13:03 +00:00
|
|
|
|
2021-12-02 19:49:37 +00:00
|
|
|
const databaseIsSetup = result.length !== 0;
|
2021-11-18 21:13:03 +00:00
|
|
|
|
2021-12-02 19:49:37 +00:00
|
|
|
if(!databaseIsSetup) {
|
2021-11-26 02:21:21 +00:00
|
|
|
await Initialize();
|
2021-11-18 21:13:03 +00:00
|
|
|
}
|
2021-12-02 19:49:37 +00:00
|
|
|
|
|
|
|
|
|
|
|
let latestMigration;
|
|
|
|
try {
|
|
|
|
const latestMigrationQuery = `SELECT value FROM metadata WHERE property = 'latest_migration';`;
|
2021-12-07 17:32:59 +00:00
|
|
|
latestMigration = +((await executeQuery(latestMigrationQuery))[0][0]);
|
2021-12-02 19:49:37 +00:00
|
|
|
} catch {
|
|
|
|
latestMigration = 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
await performMigrations(latestMigration);
|
2021-11-18 21:13:03 +00:00
|
|
|
}
|
2021-11-26 21:49:08 +00:00
|
|
|
const initializationStatus = checkForDatabaseInitialization();
|
2021-11-20 23:51:49 +00:00
|
|
|
|
2021-12-02 19:49:37 +00:00
|
|
|
async function performMigrations(currentMigration) {
|
|
|
|
const migrationFileList = fs.readdirSync('database/migrations');
|
|
|
|
const latestMigration = +migrationFileList[migrationFileList.length - 1].slice(0, 1);
|
|
|
|
|
2021-12-07 17:32:59 +00:00
|
|
|
for(let i = +currentMigration + 1; i <= latestMigration; i++) {
|
2021-12-02 19:49:37 +00:00
|
|
|
const sql = fs.readFileSync(`database/migrations/${i}.sql`).toString();
|
|
|
|
await executeQuery(sql);
|
|
|
|
console.log(`Performed database migration ${i}`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-20 23:51:49 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2021-11-26 21:49:08 +00:00
|
|
|
exports.executeQuery = executeQuery;
|
|
|
|
exports.initializationStatus = initializationStatus;
|