Skip to content

Commit

Permalink
Add migration feature
Browse files Browse the repository at this point in the history
  • Loading branch information
ttam committed Nov 14, 2023
1 parent fefed2d commit 16706e6
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
33 changes: 33 additions & 0 deletions db/migrate.php
Original file line number Diff line number Diff line change
@@ -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 changes: 8 additions & 0 deletions migrations/000001.php
Original file line number Diff line number Diff line change
@@ -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
)');
3 changes: 3 additions & 0 deletions startup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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/
Expand Down

0 comments on commit 16706e6

Please sign in to comment.