-
Notifications
You must be signed in to change notification settings - Fork 11
/
migrate.php
434 lines (374 loc) · 15.1 KB
/
migrate.php
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
<?php
/**
* Author: Igor Ilić <[email protected]>
* Date: 2021-08-13
* Project: Good Food Tracker - API
*/
include_once __DIR__ . "/classes/autoload.php";
include_once __DIR__ . "/drivers/autoload.php";
use JetBrains\PhpStorm\NoReturn;
$shortOptions = "";
$longOptions = [
"driver::" => "Which database driver is going to be used to establish a database connection (available: PGSQL,MySQL,MSSQL).",
"host::" => "Database host name or IP",
"port::" => "Database port",
"username::" => "Database login username",
"password::" => "Database login password",
"database::" => "On which database should the changes be applied to",
"folder::" => "Location of the migrations folder (def: ./migrations)",
"init::" => "Initialize migrations for the first time by creating the migrations table",
"create::" => "Create a new migration",
"up::" => "Run all the UP migrations, you can also do --up=\"migration-name\" to run a specific migration",
"down::" => "Run all the DOWN migrations, you can also do --down=\"migration-id\" to run all the migrations up until the specified one (not running the specified one)",
"help::" => "Prints this help text",
];
$options = getopt($shortOptions, array_keys($longOptions));
main($options);
/**
* Main function that gets called when the cli runs this file
*
* @param array|null $args arguments that get passed down from the cli
*/
#[NoReturn] function main(array|null $args): void
{
if (file_exists(__DIR__ . "/../.migration.conf")) {
output("Loading data from config file");
import_config_data();
}
$_ENV["args"] = array_merge($args, $_ENV["args"]);
foreach ($args as $key => $value) {
switch (mb_strtolower($key)) {
case CLICommands::INIT:
init_migrations();
// no break
case CLICommands::CREATE:
create_new_migration($value);
// no break
case CLICommands::UP:
case CLICommands::DOWN:
migrate($key, !empty($value) ? mb_strtolower($value) : null);
// no break
case CLICommands::HELP:
print_help_menu();
}
}
print("Try using --help\r\n");
exit(1);
}
/**
* Import configuration information from the .migration.conf file
*/
function import_config_data()
{
$file = file_get_contents(__DIR__ . "/../.migration.conf");
$options = explode("\n", $file);
foreach ($options as $option) {
$item = explode("=", $option);
if (empty($item[0])) {
continue;
}
$_ENV["args"][strtolower(trim($item[0]))] = trim($item[1]);
}
}
/**
* Method used for printing out the help text in the cli
*/
#[NoReturn] function print_help_menu()
{
global $longOptions;
print("To run the migrations: " . PHP_EOL);
print("php migrate.php [arguments] " . PHP_EOL . PHP_EOL);
print("Arguments: " . PHP_EOL);
foreach ($longOptions as $key => $argument) {
$key = str_replace("::", "", $key);
print("--$key $argument" . PHP_EOL);
}
exit(0);
}
/**
* Method used for running migration either up or down based on the selected option
*
* @param int|string $key Direction of the migrations (up/down)
* @param string|null $migrationName Name of the migration file to execute or run all migration for up, and
* when doing down it should be the ID from the migrations table up until you wish to downgrade or all
*/
#[NoReturn] function migrate(int|string $key, string|null $migrationName = null): void
{
if (!isset($_ENV["args"][CLIArgs::DRIVER])) {
output("No database driver specified", LogLevel::ERROR);
exit(1);
}
try {
output("Starting to migrate $key");
$nameOrID = $migrationName ?? "all";
if ($key == "up") {
cli_migrate_up($nameOrID);
}
if ($key == "down") {
cli_migrate_down($nameOrID === "all" ? null : $nameOrID);
}
} catch (Exception $ex) {
output("Migration failed because: {$ex->getMessage()}", LogLevel::ERROR);
exit(1);
}
exit(0);
}
/**
* Method used to handle the up migration logic
*
* @param string $migrationName Name of the migration file to be executed or `all` for all un run migrations to execute
*
* @throws Exception Throws an exception when there is an error running migrations
*/
function cli_migrate_up(string $migrationName = "all"): void
{
$folder = $_ENV['args'][CLIArgs::FOLDER] ?? __DIR__ . '/migrations';
output('Getting migration driver');
$driver = get_migration_driver();
if ($migrationName === "all") {
$executedMigrations = $driver->get_migrations();
$migrationFiles = get_migration_files();
} else {
$migrationName .= ".sql";
if (!file_exists("$folder/up/$migrationName")) {
throw new Exception("Migration file $migrationName not found");
}
$executedMigrations = $driver->get_migrations($migrationName);
if (count($executedMigrations) > 0) {
throw new Exception("Migration $migrationName already executed");
}
$migrationFiles = [ "$folder/$migrationName" ];
}
if (count($migrationFiles) === 0) {
output("No migrations found", LogLevel::WARNING);
exit(0);
}
$cnt = 0;
output("Found " . count($migrationFiles) . " migration(s)");
foreach ($migrationFiles as $migrationFile) {
$migrationFileName = pathinfo($migrationFile, PATHINFO_FILENAME) . ".sql";
if (array_search($migrationFileName, array_column($executedMigrations, 'file_name')) !== false) {
continue;
}
if (!file_exists($migrationFile)) {
throw new Exception("Migration file $migrationFile not found");
}
output("Found migration $migrationFileName");
$path = (pathinfo($migrationFile, PATHINFO_DIRNAME));
$sql = file_get_contents("$path/$migrationFileName");
$driver->run_migration($sql);
$driver->store_migration_info(CLICommands::UP, $migrationFileName);
output("Executed migration $migrationFileName successfully", LogLevel::SUCCESS);
$cnt++;
}
if ($cnt > 0) {
output("Successfully executed $cnt migration(s)", LogLevel::SUCCESS);
} else {
output("All migrations have been executed");
}
}
/**
* Method used to handle the up migration logic
*
* @param int|null $migrationID ID of migration to run the down method until (not running down for that one) or null tu run all down migrations
*
* @throws Exception Throws an exception when there is an error running migrations
*/
function cli_migrate_down(int $migrationID = null): void
{
$folder = $_ENV['args'][CLIArgs::FOLDER] ?? __DIR__ . '/migrations';
$driver = get_migration_driver();
if (is_null($migrationID)) {
$migrations = $driver->get_migrations();
} else {
$migrations = $driver->execute_query("SELECT * FROM migrations WHERE id > ?", [ $migrationID ]);
}
output("Found " . count($migrations) . " migration(s) to run");
$cnt = 0;
foreach ($migrations as $migration) {
$migrationName = $migration->file_name;
if (!file_exists("$folder/down/$migrationName")) {
throw new Exception("Migration file $migrationName not found");
}
output("Running down migration for $migrationName");
$sql = file_get_contents("$folder/down/$migrationName");
$driver->run_migration($sql);
$driver->store_migration_info(CLICommands::DOWN, $migrationName);
output("Down migration $migrationName executed successfully", LogLevel::SUCCESS);
$cnt++;
}
if ($cnt > 0) {
output('Successfully executed ' . count($migrations) . ' migration(s)', LogLevel::SUCCESS);
} else {
output('All migrations have been executed');
}
}
/**
* Method used to get all the migrations files in the migrations folder
*
* @throws Exception Throws an exception when the migration folder is not found
*
* @return array Returns a list of migration files or an empty array if there aren't any
*/
function get_migration_files(): array
{
$folder = $_ENV['args'][CLIArgs::FOLDER] ?? __DIR__ . '/migrations';
if (!is_dir($folder)) {
throw new Exception("Migrations folder doesn't exist");
}
$result = [];
$folder = rtrim($folder, "/") . "/up/";
foreach (glob($folder . '*.*') as $file) {
if ($file === "." || $file === "..") {
continue;
}
$result[] = $file;
}
sort($result);
return $result;
}
/**
* Method used for creating new migration files
*
* @param string|null $migrationName Name of the new migration to be created, if none is provided it will use `new-migration` for name
*/
#[NoReturn] function create_new_migration(mixed $migrationName): void
{
$migrationName = preg_replace("/\s/", "-", mb_strtolower($migrationName) ?? "new-migration");
output("Creating new migration $migrationName");
$now = time();
$name = "$now-" . $migrationName;
$folder = $_ENV['args'][CLIArgs::FOLDER] ?? './migrations';
try {
if (!is_dir($folder)) {
output("Creating migrations folder");
mkdir($folder, 0644, true);
}
if (!is_dir($folder . "/up/")) {
output('Creating migrations up folder');
mkdir($folder . "/up", 0644, true);
}
if (!is_dir($folder . '/down/')) {
output('Creating migrations down folder');
mkdir($folder . '/down', 0644, true);
}
$sqlName = "$name.sql";
$resultUp = file_put_contents("$folder/up/$sqlName", "-- Migration created on: " . date("Y-m-d H:i:s"));
if ($resultUp === false) {
throw new Exception("Unable to create file $folder/up/$sqlName");
}
$resultDown = file_put_contents(
"$folder/down/$sqlName",
"-- Migration created on: " . date("Y-m-d H:i:s")
);
if ($resultDown === false) {
throw new Exception("Unable to create file $folder/down/$sqlName");
}
output("New migration $migrationName created successfully", LogLevel::SUCCESS);
} catch (Exception $ex) {
if (file_exists("$folder/up/$name.sql")) {
unlink("$folder/up/$name.sql");
}
if (file_exists("$folder/down/$name.sql")) {
unlink("$folder/down/$name.sql");
}
output("Unable to create new migration because: {$ex->getMessage()}", LogLevel::ERROR);
exit(1);
}
exit(0);
}
/**
* Method used for creating the migrations table to track of all the migrations
*/
#[NoReturn] function init_migrations(): void
{
if (!isset($_ENV["args"][CLIArgs::DRIVER])) {
output("No database driver specified", LogLevel::ERROR);
exit(1);
}
output("Initializing migrations table");
output("Creating new DB driver");
try {
$driver = get_migration_driver();
output("DB driver created", LogLevel::SUCCESS);
$res = $driver->initialize();
if ($res !== true) {
output($res, LogLevel::ERROR);
exit(1);
}
output('Migrations table created successfully', LogLevel::SUCCESS);
if (isset($_ENV['args'][CLIArgs::FOLDER])) {
$folder = $_ENV['args'][CLIArgs::FOLDER];
if (!is_dir($folder)) {
output("Creating migrations folder [$folder]");
mkdir($folder, 0644, true);
}
if (!is_dir($folder . '/up/')) {
output("Creating migrations up folder [$folder/up]");
mkdir($folder . '/up', 0644, true);
}
if (!is_dir($folder . '/down/')) {
output("Creating migrations down folder [$folder/down]");
mkdir($folder . '/down', 0644, true);
}
output("Migrations folders created successfully", LogLevel::SUCCESS);
}
exit(0);
} catch (Exception $ex) {
$cls = new ReflectionClass($ex);
output("[{$cls->getShortName()}] " . $ex->getMessage(), LogLevel::ERROR);
exit(1);
}
}
/**
* Method used for getting the database driver based on the cli argument
*
* @throws Exception Throws an exception when it can't find the specified database driver
*
* @return DatabaseInterface Returns an instance of a selected database driver class
*/
function get_migration_driver(): DatabaseInterface
{
if (!isset(DBDrivers::getConstants()[$_ENV['args'][CLIArgs::DRIVER]])) {
throw new Exception('Invalid driver selected');
}
return new (DBDrivers::getConstants()[$_ENV['args'][CLIArgs::DRIVER]]);
}
/**
* Method used for showing preformatted messages with colors in the cli
*
* @param string $msg Message to be printed
* @param string $lvl Type of message being printed (info, warning, error)
* @param bool $silent Should the output be hidden unless it's level is error
* @param bool $newLine Should it output a new line after the message
*/
function output(string $msg, string $lvl = LogLevel::INFO, bool $silent = false, bool $newLine = true): void
{
$color = "\e[37m";
$prefix = "[INFO]";
switch ($lvl) {
case LogLevel::SUCCESS:
$color = "\e[32m";
$prefix = "[SUCCESS]";
break;
case LogLevel::WARNING:
$color = "\e[93m";
$prefix = "[WARNING]";
break;
case LogLevel::ERROR:
$color = "\e[91m";
$prefix = "[ERROR]";
break;
case LogLevel::INFO:
$color = "\e[37m";
$prefix = "[INFO]";
break;
}
if ($silent && $lvl !== LogLevel::ERROR) {
return;
}
print "$color$prefix $msg \e[0m";
if ($newLine) {
print "\r\n";
}
}