Add built-in database migration support

main
sudoer777 2021-12-02 12:49:37 -07:00
parent dd85df48c5
commit b5d42a4cd3
3 changed files with 33 additions and 6 deletions

View File

@ -27,17 +27,40 @@ async function Initialize() {
async function checkForDatabaseInitialization() { async function checkForDatabaseInitialization() {
const scoresSchemaExistsQuery = `SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'scores'`; const databaseIsSetupQuery = `SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'scores'`;
let result = await executeQuery(scoresSchemaExistsQuery); let result = await executeQuery(databaseIsSetupQuery);
const scoresSchemaExists = result.length !== 0; const databaseIsSetup = result.length !== 0;
if(!scoresSchemaExists) { if(!databaseIsSetup) {
await Initialize(); 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(); 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}`);
}
}

View File

@ -1,3 +1,5 @@
/* ADD METADATA TABLE */
BEGIN; BEGIN;
CREATE TABLE IF NOT EXISTS metadata( CREATE TABLE IF NOT EXISTS metadata(
@ -6,6 +8,6 @@ CREATE TABLE IF NOT EXISTS metadata(
); );
INSERT INTO metadata(property, value) INSERT INTO metadata(property, value)
VALUES("latest_migration", "1"); VALUES('latest_migration', '1');
COMMIT; COMMIT;

View File

@ -1,3 +1,5 @@
/* ADD ACCOUNT NAME COLUMN */
BEGIN; BEGIN;
ALTER TABLE accounts.users ALTER TABLE accounts.users
@ -5,6 +7,6 @@ ADD COLUMN full_name TEXT;
UPDATE metadata UPDATE metadata
SET value = '2' SET value = '2'
WHERE property = "latest_migration"; WHERE property = 'latest_migration';
COMMIT; COMMIT;