-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmigrate.php
More file actions
executable file
·99 lines (79 loc) · 2.66 KB
/
migrate.php
File metadata and controls
executable file
·99 lines (79 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('max_execution_time', 0);
require_once 'config/directories.php';
require_once DIR_CORE . 'registry.php';
require_once DIR_CORE . 'autoload.php';
$registry = new Registry();
$registry->set('env', new Env());
$db = new Db($registry);
$command = $argv[1] ?? null;
switch ($command) {
case 'migrate':
migrate($db);
break;
case 'rollback':
rollback($db);
break;
case 'status':
migrationStatus($db);
break;
default:
echo "Usage: php migrate.php [migrate|rollback|status]\n";
break;
}
function migrate($db) {
echo "Running migrations...\n";
// Ensure migrations table exists
$db->query("
CREATE TABLE IF NOT EXISTS migrations (
id INT AUTO_INCREMENT PRIMARY KEY,
migration VARCHAR(255),
applied_at DATETIME
)
");
$appliedMigrations = array_column(
$db->query("SELECT migration FROM migrations", true),
'migration'
);
$files = glob(__DIR__ . '/migrations/*.php');
foreach ($files as $file) {
$migrationName = basename($file, '.php');
if (!in_array($migrationName, $appliedMigrations)) {
require_once $file;
$migration = new Migration();
$migration->up($db);
$db->query("INSERT INTO migrations (migration, applied_at) VALUES ('$migrationName', NOW())");
echo "Applied: $migrationName\n";
}
}
}
function rollback($db) {
echo "Rolling back last migration...\n";
$lastMigration = $db->query("SELECT migration FROM migrations ORDER BY id DESC LIMIT 1", true)[0]['migration'] ?? null;
if ($lastMigration) {
require_once __DIR__ . "/migrations/$lastMigration.php";
$migration = new Migration();
$migration->down($db);
$db->query("DELETE FROM migrations WHERE migration = '$lastMigration'");
echo "Rolled back: $lastMigration\n";
} else {
echo "No migrations to roll back.\n";
}
}
function migrationStatus($db) {
echo "Migration status:\n";
$migrations = $db->query("SELECT migration, applied_at FROM migrations ORDER BY applied_at", true);
foreach ($migrations as $migration) {
echo "Applied: {$migration['migration']} at {$migration['applied_at']}\n";
}
$files = glob(__DIR__ . '/migrations/*.php');
foreach ($files as $file) {
$migrationName = basename($file, '.php');
if (!in_array($migrationName, array_column($migrations, 'migration'))) {
echo "Pending: $migrationName\n";
}
}
}