diff --git a/database/database.js b/database/database.js index 7390426..08c1a37 100644 --- a/database/database.js +++ b/database/database.js @@ -27,17 +27,40 @@ async function Initialize() { async function checkForDatabaseInitialization() { - const scoresSchemaExistsQuery = `SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'scores'`; - let result = await executeQuery(scoresSchemaExistsQuery); + const databaseIsSetupQuery = `SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'scores'`; + let result = await executeQuery(databaseIsSetupQuery); - const scoresSchemaExists = result.length !== 0; + const databaseIsSetup = result.length !== 0; - if(!scoresSchemaExists) { + 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}`); + } +} + diff --git a/database/migrations/1_add_metadata_table.sql b/database/migrations/1.sql similarity index 67% rename from database/migrations/1_add_metadata_table.sql rename to database/migrations/1.sql index 2bfb449..f9a5c78 100644 --- a/database/migrations/1_add_metadata_table.sql +++ b/database/migrations/1.sql @@ -1,3 +1,5 @@ +/* ADD METADATA TABLE */ + BEGIN; CREATE TABLE IF NOT EXISTS metadata( @@ -6,6 +8,6 @@ CREATE TABLE IF NOT EXISTS metadata( ); INSERT INTO metadata(property, value) - VALUES("latest_migration", "1"); + VALUES('latest_migration', '1'); COMMIT; \ No newline at end of file diff --git a/database/migrations/2_add_account_names.sql b/database/migrations/2.sql similarity index 56% rename from database/migrations/2_add_account_names.sql rename to database/migrations/2.sql index efb1da5..6a22cdb 100644 --- a/database/migrations/2_add_account_names.sql +++ b/database/migrations/2.sql @@ -1,3 +1,5 @@ +/* ADD ACCOUNT NAME COLUMN */ + BEGIN; ALTER TABLE accounts.users @@ -5,6 +7,6 @@ ADD COLUMN full_name TEXT; UPDATE metadata SET value = '2' -WHERE property = "latest_migration"; +WHERE property = 'latest_migration'; COMMIT; \ No newline at end of file