69 lines
1.9 KiB
JavaScript
69 lines
1.9 KiB
JavaScript
const app = require('../app');
|
|
const { Client } = require('pg');
|
|
const fs = require('fs');
|
|
|
|
if (process.env.NODE_ENV !== 'production' || process.env.NODE_ENV !== 'testing') {
|
|
require('dotenv').config();
|
|
}
|
|
|
|
const client = new Client();
|
|
client.connect();
|
|
|
|
async function executeQuery(query, values = []) {
|
|
const result = await client.query({
|
|
rowMode: 'array',
|
|
text: query,
|
|
values: values
|
|
});
|
|
return result.rows;
|
|
}
|
|
|
|
async function Initialize() {
|
|
console.log("Initializing database...")
|
|
const sql = fs.readFileSync('database/init_database.sql').toString();
|
|
await executeQuery(sql);
|
|
console.log("Database initialized.")
|
|
}
|
|
|
|
|
|
async function checkForDatabaseInitialization() {
|
|
const databaseIsSetupQuery = `SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'scores'`;
|
|
let result = await executeQuery(databaseIsSetupQuery);
|
|
|
|
const databaseIsSetup = result.length !== 0;
|
|
|
|
if(!databaseIsSetup) {
|
|
await Initialize();
|
|
}
|
|
|
|
|
|
let latestMigration;
|
|
try {
|
|
const latestMigrationQuery = `SELECT value FROM metadata WHERE property = 'latest_migration';`;
|
|
latestMigration = +((await executeQuery(latestMigrationQuery))[0][0]);
|
|
} catch {
|
|
latestMigration = 0;
|
|
}
|
|
|
|
|
|
await performMigrations(latestMigration);
|
|
}
|
|
const initializationStatus = checkForDatabaseInitialization();
|
|
|
|
async function performMigrations(currentMigration) {
|
|
const migrationFileList = fs.readdirSync('database/migrations');
|
|
const latestMigration = +migrationFileList[migrationFileList.length - 1].slice(0, 1);
|
|
|
|
for(let i = +currentMigration + 1; i <= latestMigration; i++) {
|
|
const sql = fs.readFileSync(`database/migrations/${i}.sql`).toString();
|
|
await executeQuery(sql);
|
|
console.log(`Performed database migration ${i}`);
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
exports.executeQuery = executeQuery;
|
|
exports.initializationStatus = initializationStatus; |