From 16706e61e169365b8ae95faedd295ce14cd1c0f9 Mon Sep 17 00:00:00 2001 From: Matt Bannon Date: Tue, 14 Nov 2023 21:02:07 +1100 Subject: [PATCH] Add migration feature --- db/migrate.php | 33 +++++++++++++++++++++++++++++++++ migrations/000001.php | 8 ++++++++ startup.sh | 3 +++ 3 files changed, 44 insertions(+) create mode 100644 db/migrate.php create mode 100644 migrations/000001.php diff --git a/db/migrate.php b/db/migrate.php new file mode 100644 index 000000000..7e8035144 --- /dev/null +++ b/db/migrate.php @@ -0,0 +1,33 @@ +query('SELECT name FROM sqlite_master WHERE type="table" AND name="migrations"') + ->fetchArray(SQLITE3_ASSOC) !== false; + +if ($migrationTableExists) { + $migrationQuery = $db->query('SELECT migration FROM migrations'); + while ($row = $migrationQuery->fetchArray(SQLITE3_ASSOC)) { + $completedMigrations[] = $row['migration']; + } +} + +$allMigrations = glob('migrations/*.php'); +$requiredMigrations = array_diff($allMigrations, $completedMigrations); + +if (count($requiredMigrations) === 0) { + echo "No migrations to run.\n"; +} + +foreach ($requiredMigrations as $migration) { + require_once $migration; + + $stmtInsert = $db->prepare('INSERT INTO migrations (migration) VALUES (:migration)'); + $stmtInsert->bindParam(':migration', $migration, SQLITE3_TEXT); + $stmtInsert->execute(); + + echo sprintf("Migration %s completed successfully.\n", $migration); +} diff --git a/migrations/000001.php b/migrations/000001.php new file mode 100644 index 000000000..a787c3788 --- /dev/null +++ b/migrations/000001.php @@ -0,0 +1,8 @@ +exec('CREATE TABLE IF NOT EXISTS migrations ( + id INTEGER PRIMARY KEY, + migration TEXT NOT NULL, + migrated_at DATETIME DEFAULT CURRENT_TIMESTAMP +)'); diff --git a/startup.sh b/startup.sh index 00be7efc7..2235ac0cd 100644 --- a/startup.sh +++ b/startup.sh @@ -14,6 +14,9 @@ sleep 1 # Create database if it does not exist /usr/local/bin/php /var/www/html/endpoints/cronjobs/createdatabase.php +# Perform any database migrations +/usr/local/bin/php /var/www/html/db/migrate.php + # Change permissions on the database directory chmod -R 755 /var/www/html/db/ chown -R www-data:www-data /var/www/html/db/