-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDatabaseRestoreCommand.php
More file actions
358 lines (280 loc) · 10.3 KB
/
Copy pathDatabaseRestoreCommand.php
File metadata and controls
358 lines (280 loc) · 10.3 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
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
<?php
declare(strict_types=1);
namespace Zero\Lib\Console\Commands;
use Zero\Lib\Console\Command\CommandInterface;
use function config;
use function storage_path;
final class DatabaseRestoreCommand implements CommandInterface
{
public function getName(): string
{
return 'db:restore';
}
public function getDescription(): string
{
return 'Restore the configured database from an SQL dump file.';
}
public function getUsage(): string
{
return 'php zero db:restore [--connection=mysql] [--file=storage/database/dumps/backup.sql]';
}
public function execute(array $argv): int
{
[, $options] = $this->parseOptions($argv);
$connectionOption = $options['connection'] ?? null;
$connection = is_string($connectionOption) && trim($connectionOption) !== ''
? $connectionOption
: (string) config('database.connection', 'mysql');
$config = (array) config('database.' . $connection, []);
if ($config === []) {
fwrite(STDERR, sprintf('Database connection [%s] is not defined.%s', $connection, PHP_EOL));
return 1;
}
$driver = (string) ($config['driver'] ?? $connection);
$fileOption = $options['file'] ?? null;
$userProvided = is_string($fileOption) && trim($fileOption) !== '';
if ($userProvided) {
$file = $this->normalisePath(trim((string) $fileOption));
if (!is_file($file)) {
fwrite(STDERR, sprintf('Dump file [%s] does not exist.%s', $file, PHP_EOL));
return 1;
}
} else {
$file = $this->latestDump(storage_path('database/dumps'));
if ($file === null) {
fwrite(STDERR, 'No dump file found. Use --file to specify one.' . PHP_EOL);
return 1;
}
echo sprintf('Restoring from latest dump: %s%s', $file, PHP_EOL);
}
return match ($driver) {
'mysql' => $this->restoreMysql($config, $file),
'pgsql', 'postgres' => $this->restorePostgres($config, $file),
'sqlite', 'sqlite3' => $this->restoreSqlite($config, $file),
default => $this->unsupportedDriver($driver),
};
}
private function restoreMysql(array $config, string $file): int
{
$binary = $this->findBinary('mysql');
if ($binary === null) {
fwrite(STDERR, 'mysql client binary was not found in PATH.' . PHP_EOL);
return 1;
}
$host = (string) ($config['host'] ?? '127.0.0.1');
$port = (string) ($config['port'] ?? '3306');
$username = (string) ($config['username'] ?? 'root');
$database = (string) ($config['database'] ?? '');
$password = (string) ($config['password'] ?? '');
if ($database === '') {
fwrite(STDERR, 'MySQL database name is not configured.' . PHP_EOL);
return 1;
}
$command = sprintf(
'%s --host=%s --port=%s --user=%s %s < %s',
escapeshellcmd($binary),
escapeshellarg($host),
escapeshellarg($port),
escapeshellarg($username),
escapeshellarg($database),
escapeshellarg($file)
);
$previous = getenv('MYSQL_PWD');
if ($password !== '') {
putenv('MYSQL_PWD=' . $password);
}
$exitCode = $this->runCommand($command, $output);
if ($password !== '') {
if ($previous === false) {
putenv('MYSQL_PWD');
} else {
putenv('MYSQL_PWD=' . $previous);
}
}
if ($exitCode !== 0) {
fwrite(STDERR, sprintf('mysql exited with status %d.%s', $exitCode, PHP_EOL));
return $exitCode ?: 1;
}
echo sprintf('Database restored from %s%s', $file, PHP_EOL);
return 0;
}
private function restorePostgres(array $config, string $file): int
{
$binary = $this->findBinary('psql');
if ($binary === null) {
fwrite(STDERR, 'psql binary was not found in PATH.' . PHP_EOL);
return 1;
}
$host = (string) ($config['host'] ?? '127.0.0.1');
$port = (string) ($config['port'] ?? '5432');
$username = (string) ($config['username'] ?? 'postgres');
$database = (string) ($config['database'] ?? '');
$password = (string) ($config['password'] ?? '');
if ($database === '') {
fwrite(STDERR, 'PostgreSQL database name is not configured.' . PHP_EOL);
return 1;
}
$command = sprintf(
'%s --host=%s --port=%s --username=%s --dbname=%s < %s',
escapeshellcmd($binary),
escapeshellarg($host),
escapeshellarg($port),
escapeshellarg($username),
escapeshellarg($database),
escapeshellarg($file)
);
$previous = getenv('PGPASSWORD');
if ($password !== '') {
putenv('PGPASSWORD=' . $password);
}
$exitCode = $this->runCommand($command, $output);
if ($password !== '') {
if ($previous === false) {
putenv('PGPASSWORD');
} else {
putenv('PGPASSWORD=' . $previous);
}
}
if ($exitCode !== 0) {
fwrite(STDERR, sprintf('psql exited with status %d.%s', $exitCode, PHP_EOL));
return $exitCode ?: 1;
}
echo sprintf('Database restored from %s%s', $file, PHP_EOL);
return 0;
}
private function restoreSqlite(array $config, string $file): int
{
$databasePath = (string) ($config['database'] ?? '');
if ($databasePath === '') {
fwrite(STDERR, 'SQLite database path is not configured.' . PHP_EOL);
return 1;
}
if (!@copy($file, $databasePath)) {
fwrite(STDERR, sprintf('Unable to copy dump [%s] to [%s].%s', $file, $databasePath, PHP_EOL));
return 1;
}
echo sprintf('SQLite database restored from %s%s', $file, PHP_EOL);
return 0;
}
private function latestDump(string $directory): ?string
{
if (!is_dir($directory)) {
return null;
}
$files = glob(rtrim($directory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . '*');
if (!is_array($files) || $files === []) {
return null;
}
rsort($files, SORT_STRING);
return $files[0] ?? null;
}
private function unsupportedDriver(string $driver): int
{
fwrite(STDERR, sprintf('Database driver [%s] is not supported by db:restore.%s', $driver, PHP_EOL));
return 1;
}
private function runCommand(string $command, ?array &$output = null): int
{
$output = [];
if (function_exists('exec')) {
exec($command, $output, $exitCode);
return $exitCode;
}
if (!function_exists('shell_exec')) {
fwrite(STDERR, 'Shell execution functions are disabled.' . PHP_EOL);
return 1;
}
$marker = '__ZERO_EXIT_CODE__';
$result = shell_exec($command . '; printf "\n' . $marker . '%s" $?');
if ($result === null) {
fwrite(STDERR, 'Shell execution failed.' . PHP_EOL);
return 1;
}
$parts = explode("\n" . $marker, $result, 2);
$outputText = $parts[0] ?? '';
$exitCode = (int) ($parts[1] ?? 1);
$output = $outputText === '' ? [] : preg_split("/\r\n|\n|\r/", rtrim($outputText));
return $exitCode;
}
private function normalisePath(string $path): string
{
$path = trim($path);
if ($path === '') {
return $path;
}
if ($path[0] === '~') {
$home = getenv('HOME') ?: getenv('USERPROFILE');
if ($home !== false && $home !== '') {
$path = $home . DIRECTORY_SEPARATOR . ltrim(substr($path, 1), DIRECTORY_SEPARATOR);
}
}
if ($this->isAbsolutePath($path)) {
return $path;
}
return getcwd() . DIRECTORY_SEPARATOR . $path;
}
private function isAbsolutePath(string $path): bool
{
return str_starts_with($path, DIRECTORY_SEPARATOR)
|| (strlen($path) > 1 && ctype_alpha($path[0]) && $path[1] === ':');
}
private function findBinary(string $binary): ?string
{
$candidates = [
trim((string) @shell_exec('command -v ' . escapeshellcmd($binary))),
trim((string) @shell_exec('which ' . escapeshellcmd($binary))),
];
foreach ($candidates as $candidate) {
if ($candidate !== '') {
return $candidate;
}
}
return null;
}
/**
* @return array{0: array<int, string>, 1: array<string, mixed>}
*/
private function parseOptions(array $argv): array
{
$arguments = [];
$options = [];
$count = count($argv);
for ($i = 2; $i < $count; $i++) {
$token = $argv[$i];
if ($token === '--') {
$arguments = array_merge($arguments, array_slice($argv, $i + 1));
break;
}
if (str_starts_with($token, '--')) {
$segment = substr($token, 2);
if ($segment === '') {
continue;
}
if (str_contains($segment, '=')) {
[$key, $value] = explode('=', $segment, 2);
} else {
$key = $segment;
if ($i + 1 < $count && !str_starts_with((string) $argv[$i + 1], '-')) {
$value = $argv[++$i];
} else {
$value = true;
}
}
$options[$key] = $value;
continue;
}
if (str_starts_with($token, '-')) {
$flags = substr($token, 1);
if ($flags === '') {
continue;
}
foreach (str_split($flags) as $flag) {
$options[$flag] = true;
}
continue;
}
$arguments[] = $token;
}
return [$arguments, $options];
}
}