-
Notifications
You must be signed in to change notification settings - Fork 129
Expand file tree
/
Copy pathDbDumpCommand.php
More file actions
365 lines (330 loc) · 16.2 KB
/
DbDumpCommand.php
File metadata and controls
365 lines (330 loc) · 16.2 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
359
360
361
362
363
364
365
<?php
namespace Platformsh\Cli\Command\Db;
use Platformsh\Cli\Command\CommandBase;
use Platformsh\Cli\Model\Host\LocalHost;
use Platformsh\Cli\Model\Host\RemoteHost;
use Platformsh\Cli\Service\Relationships;
use Platformsh\Cli\Service\Ssh;
use Platformsh\Cli\Util\OsUtil;
use Platformsh\Client\Model\Environment;
use Symfony\Component\Console\Helper\Helper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class DbDumpCommand extends CommandBase
{
protected function configure()
{
$this->setName('db:dump')
->setDescription('Create a local dump of the remote database');
$this->addOption('schema', null, InputOption::VALUE_REQUIRED, 'The schema to dump. Omit to use the default schema (usually "main").')
->addOption('pg-namespace', null, InputOption::VALUE_REQUIRED| InputOption::VALUE_IS_ARRAY, 'Dump the named namespace/schema(s) only (Postgresql specific)')
->addOption('pg-exclude-namespace', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Do NOT dump the named namespace/schema(s) (Postgresql specific)')
->addOption('file', 'f', InputOption::VALUE_REQUIRED, 'A custom filename for the dump')
->addOption('directory', 'd', InputOption::VALUE_REQUIRED, 'A custom directory for the dump')
->addOption('gzip', 'z', InputOption::VALUE_NONE, 'Compress the dump using gzip')
->addOption('timestamp', 't', InputOption::VALUE_NONE, 'Add a timestamp to the dump filename')
->addOption('stdout', 'o', InputOption::VALUE_NONE, 'Output to STDOUT instead of a file')
->addOption('table', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Table(s) to include')
->addOption('exclude-table', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Table(s) to exclude')
->addOption('schema-only', null, InputOption::VALUE_NONE, 'Dump only schemas, no data')
->addOption('charset', null, InputOption::VALUE_REQUIRED, 'The character set encoding for the dump');
$this->addProjectOption()->addEnvironmentOption()->addAppOption();
Relationships::configureInput($this->getDefinition());
Ssh::configureInput($this->getDefinition());
$this->setHiddenAliases(['sql-dump', 'environment:sql-dump']);
$this->addExample('Create an SQL dump file');
$this->addExample('Create a gzipped SQL dump file named "dump.sql.gz"', '--gzip -f dump.sql.gz');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
/** @var \Platformsh\Cli\Service\Relationships $relationships */
$relationships = $this->getService('relationships');
$host = $this->selectHost($input, $relationships->hasLocalEnvVar());
if ($host instanceof LocalHost && $this->api()->isLoggedIn()) {
$this->validateInput($input, true);
}
$timestamp = $input->getOption('timestamp') ? date('Ymd-His-T') : null;
$gzip = $input->getOption('gzip');
$includedTables = $input->getOption('table');
$excludedTables = $input->getOption('exclude-table');
$pgSchemas = $input->getOption('pg-namespace');
$pgExcludedSchemas = $input->getOption('pg-exclude-namespace');
$schemaOnly = $input->getOption('schema-only');
$projectRoot = $this->getProjectRoot();
/** @var \Platformsh\Cli\Service\Filesystem $fs */
$fs = $this->getService('fs');
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
$database = $relationships->chooseDatabase($host, $input, $output);
if (empty($database)) {
return 1;
}
$service = false;
if ($this->hasSelectedEnvironment()) {
// Get information about the deployed service associated with the
// selected relationship.
$deployment = $this->api()->getCurrentDeployment($this->getSelectedEnvironment());
$service = isset($database['service']) ? $deployment->getService($database['service']) : false;
}
$schema = $input->getOption('schema');
if (empty($schema)) {
// Get a list of schemas from the service configuration.
$schemas = [];
if ($service) {
$schemas = !empty($service->configuration['schemas'])
? $service->configuration['schemas']
: ['main'];
}
// Filter the list by the schemas accessible from the endpoint.
if (isset($database['rel'])
&& $service
&& isset($service->configuration['endpoints'][$database['rel']]['privileges'])) {
$schemas = array_intersect(
$schemas,
array_keys($service->configuration['endpoints'][$database['rel']]['privileges'])
);
}
// If the database path is not in the list of schemas, we have to
// use that.
if (!empty($database['path']) && !in_array($database['path'], $schemas, true)) {
$schemas = [$database['path']];
}
// Provide the user with a choice of schemas.
$choices = [];
foreach ($schemas as $schema) {
$choices[$schema] = $schema;
if ($schema === $database['path']) {
$choices[$schema] .= ' (default)';
}
}
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
$schema = $questionHelper->choose($choices, 'Enter a number to choose a schema:', $database['path'], true);
if (empty($schema)) {
$this->stdErr->writeln('The --schema is required.');
if (!empty($schemas)) {
$this->stdErr->writeln('Available schemas: ' . implode(', ', $schemas));
}
return 1;
}
}
$dumpFile = null;
if (!$input->getOption('stdout')) {
// Process the user --file option.
if ($fileOption = $input->getOption('file')) {
if (is_dir($fileOption)) {
$this->stdErr->writeln(sprintf('Filename is a directory: <error>%s</error>', $fileOption));
$this->stdErr->writeln('Use the --directory option to specify a directory.');
return 1;
}
$dumpFile = rtrim($fileOption, '/');
if (!$gzip && preg_match('/\.gz$/i', $dumpFile)) {
$this->stdErr->writeln('Warning: the filename ends with ".gz", but the dump will be plain-text.');
$this->stdErr->writeln('Use <comment>--gzip</comment> to create a compressed dump.');
$this->stdErr->writeln('');
}
} else {
$defaultFilename = $this->getDefaultFilename(
$this->hasSelectedEnvironment() ? $this->getSelectedEnvironment() : null,
$database['service'],
$schema,
$includedTables,
$excludedTables,
$pgSchemas,
$pgExcludedSchemas,
$schemaOnly,
$gzip
);
$dumpFile = $projectRoot ? $projectRoot . '/' . $defaultFilename : $defaultFilename;
}
// Process the user --directory option.
if ($directoryOption = $input->getOption('directory')) {
if (!is_dir($directoryOption)) {
$this->stdErr->writeln(sprintf('Directory not found: <error>%s</error>', $directoryOption));
return 1;
}
$dumpFile = rtrim($directoryOption, '/') . '/' . basename($dumpFile);
}
// Insert a timestamp into the filename, before the
// extension.
if ($timestamp !== null && strpos($dumpFile, $timestamp) === false) {
$basename = basename($dumpFile);
$prefix = substr($dumpFile, 0, - strlen($basename));
if (($dotPos = strpos($basename, '.')) > 0) {
$basenameWithTimestamp = substr($basename, 0, $dotPos) . '--' . $timestamp . substr($basename, $dotPos);
} else {
$basenameWithTimestamp = $basename . '--' . $timestamp;
}
$dumpFile = $prefix . $basenameWithTimestamp;
}
// Make the filename absolute.
$dumpFile = $fs->makePathAbsolute($dumpFile);
}
if ($dumpFile) {
if (file_exists($dumpFile)) {
if (!$questionHelper->confirm("File exists: <comment>$dumpFile</comment>. Overwrite?", false)) {
return 1;
}
}
$this->stdErr->writeln(sprintf(
'Creating %s file: <info>%s</info>',
$gzip ? 'gzipped SQL dump' : 'SQL dump',
$dumpFile
));
}
switch ($database['scheme']) {
case 'pgsql':
$dumpCommand = 'pg_dump --no-owner --if-exists --clean --blobs ' . $relationships->getDbCommandArgs('pg_dump', $database, $schema);
if ($schemaOnly) {
$dumpCommand .= ' --schema-only';
}
foreach ($includedTables as $table) {
$dumpCommand .= ' ' . OsUtil::escapePosixShellArg('--table=' . $table);
}
foreach ($excludedTables as $table) {
$dumpCommand .= ' ' . OsUtil::escapePosixShellArg('--exclude-table=' . $table);
}
foreach ($pgSchemas as $pgSChema) {
$dumpCommand .= ' ' . OsUtil::escapePosixShellArg('--schema=' . $pgSChema);
}
foreach ($pgExcludedSchemas as $pgExcludedSChema) {
$dumpCommand .= ' ' . OsUtil::escapePosixShellArg('--exclude-schema=' . $pgExcludedSChema);
}
if ($input->getOption('charset') !== null) {
$dumpCommand .= ' ' . OsUtil::escapePosixShellArg('--encoding=' . $input->getOption('charset'));
}
if ($output->isVeryVerbose()) {
$dumpCommand .= ' --verbose';
}
break;
default:
$dumpCommand = 'mysqldump --single-transaction '
. $relationships->getDbCommandArgs('mysqldump', $database, $schema);
if ($schemaOnly) {
$dumpCommand .= ' --no-data';
}
foreach ($excludedTables as $table) {
$dumpCommand .= ' ' . OsUtil::escapePosixShellArg(sprintf('--ignore-table=%s.%s', $database['path'], $table));
}
if ($includedTables) {
$dumpCommand .= ' --tables '
. implode(' ', array_map(function ($table) {
return OsUtil::escapePosixShellArg($table);
}, $includedTables));
}
if (!empty($service->configuration['properties']['max_allowed_packet'])) {
$dumpCommand .= ' --max_allowed_packet=' . $service->configuration['properties']['max_allowed_packet'] . 'MB';
}
if ($input->getOption('charset') !== null) {
$dumpCommand .= ' ' . OsUtil::escapePosixShellArg('--default-character-set=' . $input->getOption('charset'));
}
if ($output->isVeryVerbose()) {
$dumpCommand .= ' --verbose';
}
break;
}
if ($gzip) {
// If dump compression is enabled, pipe the dump command into gzip.
$dumpCommand .= ' | gzip --stdout';
// If it's supported, then switch on "pipefail" to ensure a
// non-zero exit code is returned if any part of the pipe fails.
$setOptions = $host->runCommand('set -o', false);
if (is_string($setOptions) && stripos($setOptions, 'pipefail') !== false) {
$dumpCommand = 'set -o pipefail; ' . $dumpCommand;
}
} elseif ($host instanceof RemoteHost) {
// If dump compression is not enabled, data can still be compressed
// transparently as it's streamed over the SSH connection.
$host->setExtraSshArgs(['-C']);
}
$append = '';
if ($dumpFile) {
$append .= ' > ' . escapeshellarg($dumpFile);
}
set_time_limit(0);
// Execute the command.
$start = microtime(true);
$exitCode = $host->runCommandDirect($dumpCommand, $append);
if ($exitCode === 0) {
$this->stdErr->writeln('The dump completed successfully', OutputInterface::VERBOSITY_VERBOSE);
$this->stdErr->writeln(sprintf(' Time: %ss', number_format(microtime(true) - $start, 2)), OutputInterface::VERBOSITY_VERBOSE);
if ($dumpFile && ($size = filesize($dumpFile)) !== false) {
$this->stdErr->writeln(sprintf(' Size: %s', Helper::formatMemory($size)), OutputInterface::VERBOSITY_VERBOSE);
}
}
// If a dump file exists, check that it's excluded in the project's
// .gitignore configuration.
if ($dumpFile && file_exists($dumpFile) && $projectRoot && strpos($dumpFile, $projectRoot) === 0) {
/** @var \Platformsh\Cli\Service\Git $git */
$git = $this->getService('git');
if (!$git->checkIgnore($dumpFile, $projectRoot)) {
$this->stdErr->writeln('<comment>Warning: the dump file is not excluded by Git</comment>');
if ($pos = strrpos($dumpFile, '--dump.sql')) {
$extension = substr($dumpFile, $pos);
$this->stdErr->writeln(' You should probably exclude these files using .gitignore:');
$this->stdErr->writeln(' *' . $extension);
}
}
}
return $exitCode;
}
/**
* Get the default dump filename.
*
* @param Environment $environment
* @param string|null $dbServiceName
* @param string|null $schema
* @param array $includedTables
* @param array $excludedTables
* @param bool $schemaOnly
* @param bool $gzip
*
* @return string
*/
private function getDefaultFilename(
Environment $environment = null,
$dbServiceName = null,
$schema = null,
array $includedTables = [],
array $excludedTables = [],
array $pgSchemas = [],
array $pgExcludedSchemas = [],
$schemaOnly = false,
$gzip = false)
{
$prefix = $this->config()->get('service.env_prefix');
$projectId = $environment ? $environment->project : getenv($prefix . 'PROJECT');
$environmentMachineName = $environment ? $environment->machine_name : getenv($prefix . 'ENVIRONMENT');
$defaultFilename = $projectId ?: 'db';
if ($environmentMachineName) {
$defaultFilename .= '--' . $environmentMachineName;
}
if ($dbServiceName !== null) {
$defaultFilename .= '--' . $dbServiceName;
}
if ($schema !== null) {
$defaultFilename .= '--' . $schema;
}
if ($includedTables) {
$defaultFilename .= '--' . implode(',', $includedTables);
}
if ($excludedTables) {
$defaultFilename .= '--excl-' . implode(',', $excludedTables);
}
if ($pgSchemas){
$defaultFilename .= '--n-' . implode(',', $pgSchemas);
}
if ($pgExcludedSchemas){
$defaultFilename .= '--N-' . implode(',', $pgExcludedSchemas);
}
if ($schemaOnly) {
$defaultFilename .= '--schema';
}
$defaultFilename .= '--dump.sql';
if ($gzip) {
$defaultFilename .= '.gz';
}
return $defaultFilename;
}
}