Add migration feature

This commit is contained in:
Matt Bannon 2023-11-14 21:02:07 +11:00
parent fefed2db26
commit 16706e61e1
No known key found for this signature in database
GPG Key ID: 187033B38F7D0527
3 changed files with 44 additions and 0 deletions

33
db/migrate.php Normal file
View File

@ -0,0 +1,33 @@
<?php
/** @var \SQLite3 $db */
require_once 'includes/connect_endpoint_crontabs.php';
$completedMigrations = [];
$migrationTableExists = $db
->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);
}

8
migrations/000001.php Normal file
View File

@ -0,0 +1,8 @@
<?php
/** @noinspection PhpUndefinedVariableInspection */
$db->exec('CREATE TABLE IF NOT EXISTS migrations (
id INTEGER PRIMARY KEY,
migration TEXT NOT NULL,
migrated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)');

View File

@ -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/