-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmigrate-php
executable file
·94 lines (83 loc) · 2.45 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
#!/usr/bin/env php
<?php
function success_message($string)
{
return "\033[0;32m$string\033[0m";
}
function error_message($string)
{
return "\033[0;31m$string\033[0m";
}
function get_pdo($dsn, $username, $password, $driver_options)
{
try
{
$pdo_object = new PDO($dsn, $username, $password, $driver_options);
echo success_message("Database connection success.") . "\n\n";
return $pdo_object;
}
catch (PDOException $e)
{
exit(error_message("Database connection error: ") . $e->getMessage() . "\n");
}
}
array_shift($argv);
$options = getopt("H:P:n:t:c:u:p:");
if (empty($options)) {
$usage = <<< STRING
Usage: migrate -H {hostname} -P {port} -n {db_name} -t {db_type} -c {charset}
[Options]
-H Hostname (default: localhost)
-P Port (default: 3306)
-n Database name (default: example)
-t Database type (default: mysql)
-c Charset (default: utf8)
-u Username (default: root)
-p Password (default: root)
STRING;
print("$usage\n");
exit();
}
$db_type = !isset($options["t"]) ? "mysql" : $options["t"];
$host = !isset($options["H"]) ? "localhost" : $options["H"];
$port = !isset($options["P"]) ? "3306" : $options["P"];
$db_name = !isset($options["n"]) ? "example" : $options["n"];
$charset = !isset($options["c"]) ? "utf8" : $options["c"];
if ($db_type === "pgsql") {
$dsn = "$db_type:host=$host;port=$port;dbname=$db_name";
} else {
$dsn = "$db_type:host=$host;port=$port;dbname=$db_name;charset=$charset";
}
$db_user = !isset($options["u"]) ? "root" : $options["u"];
$db_pass = !isset($options["p"]) ? "root" : $options["p"];
$pdo = get_pdo($dsn, $db_user, $db_pass, []);
$migration_files = glob('migrations/*.sql');
if (!empty($migration_files)) {
$success_count = 0;
$error_count = 0;
foreach ($migration_files as $file) {
$sql = file_get_contents($file);
$stmt = $pdo->prepare($sql);
try
{
if ($stmt->execute()) {
echo success_message("Migrated: " . "$file\n\n");
$success_count++;
} else {
// For PHP <= 7.4x
throw new PDOException();
}
}
catch (PDOException $e)
{
$error = $stmt->errorInfo();
echo error_message("Error(" . $error[1] . "): ") . $error[2] . "\n-> " . error_message("$file\n\n");
$error_count++;
}
}
echo success_message("Success: $success_count\n");
echo error_message("Failed: $error_count\n");
echo "\nDone.\n";
} else {
exit("\033[0;31mError: \033[0mNo migration files found.\n");
}