Completed
Push — develop ( 3676ae...babe21 )
by Tom
03:56
created

DumpCommand::getTableDefinitionHelp()   B

Complexity

Conditions 6
Paths 15

Size

Total Lines 49
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 49
rs 8.5906
cc 6
eloc 25
nc 15
nop 0
1
<?php
2
3
namespace N98\Magento\Command\Database;
4
5
use N98\Magento\Command\Database\Compressor\Compressor;
6
use N98\Util\Console\Enabler;
7
use N98\Util\Console\Helper\DatabaseHelper;
8
use N98\Util\Exec;
9
use N98\Util\VerifyOrDie;
10
use RuntimeException;
11
use Symfony\Component\Console\Helper\DialogHelper;
12
use Symfony\Component\Console\Input\InputArgument;
13
use Symfony\Component\Console\Input\InputInterface;
14
use Symfony\Component\Console\Input\InputOption;
15
use Symfony\Component\Console\Output\OutputInterface;
16
17
class DumpCommand extends AbstractDatabaseCommand
18
{
19
    /**
20
     * @var array
21
     */
22
    protected $tableDefinitions = null;
23
24
    /**
25
     * @var array
26
     */
27
    protected $commandConfig = null;
28
29
    protected function configure()
30
    {
31
        $this
32
            ->setName('db:dump')
33
            ->addArgument('filename', InputArgument::OPTIONAL, 'Dump filename')
34
            ->addOption('add-time', 't', InputOption::VALUE_OPTIONAL,
35
                'Adds time to filename (only if filename was not provided)')
36
            ->addOption('compression', 'c', InputOption::VALUE_REQUIRED,
37
                'Compress the dump file using one of the supported algorithms')
38
            ->addOption('xml', null, InputOption::VALUE_NONE, 'Dump database in xml format')
39
            ->addOption('hex-blob', null, InputOption::VALUE_NONE,
40
                'Dump binary columns using hexadecimal notation (for example, "abc" becomes 0x616263)')
41
            ->addOption('only-command', null, InputOption::VALUE_NONE, 'Print only mysqldump command. Do not execute')
42
            ->addOption('print-only-filename', null, InputOption::VALUE_NONE,
43
                'Execute and prints no output except the dump filename')
44
            ->addOption('no-single-transaction', null, InputOption::VALUE_NONE,
45
                'Do not use single-transaction (not recommended, this is blocking)')
46
            ->addOption('human-readable', null, InputOption::VALUE_NONE,
47
                'Use a single insert with column names per row. Useful to track database differences. Use db:import --optimize for speeding up the import.')
48
            ->addOption('add-routines', null, InputOption::VALUE_NONE,
49
                'Include stored routines in dump (procedures & functions)')
50
            ->addOption('stdout', null, InputOption::VALUE_NONE, 'Dump to stdout')
51
            ->addOption('strip', 's', InputOption::VALUE_OPTIONAL,
52
                'Tables to strip (dump only structure of those tables)')
53
            ->addOption('exclude', 'e', InputOption::VALUE_OPTIONAL, 'Tables to exclude from the dump')
54
            ->addOption('force', 'f', InputOption::VALUE_NONE, 'Do not prompt if all options are defined')
55
            ->setDescription('Dumps database with mysqldump cli client according to informations from local.xml');
56
57
        $help = <<<HELP
58
Dumps configured magento database with `mysqldump`. You must have installed
59
the MySQL client tools.
60
61
On debian systems run `apt-get install mysql-client` to do that.
62
63
The command reads app/etc/local.xml to find the correct settings.
64
65
See it in action: http://youtu.be/ttjZHY6vThs
66
67
- If you like to prepend a timestamp to the dump name the --add-time option
68
  can be used.
69
70
- The command comes with a compression function. Add i.e. `--compression=gz`
71
  to dump directly in gzip compressed file.
72
73
HELP;
74
        $this->setHelp($help);
75
76
    }
77
78
    /**
79
     * @return array
80
     *
81
     * @deprecated Use database helper
82
     * @throws RuntimeException
83
     */
84
    public function getTableDefinitions()
85
    {
86
        $this->commandConfig = $this->getCommandConfig();
87
88
        if (is_null($this->tableDefinitions)) {
89
            /* @var $dbHelper DatabaseHelper */
90
            $dbHelper = $this->getHelper('database');
91
92
            $this->tableDefinitions = $dbHelper->getTableDefinitions($this->commandConfig);
93
        }
94
95
        return $this->tableDefinitions;
96
    }
97
98
    /**
99
     * Generate help for table definitions
100
     *
101
     * @return string
102
     */
103
    public function getTableDefinitionHelp()
104
    {
105
        $messages = PHP_EOL;
106
        $this->commandConfig = $this->getCommandConfig();
107
        $messages .= <<<HELP
108
<comment>Strip option</comment>
109
 If you like to skip data of some tables you can use the --strip option.
110
 The strip option creates only the structure of the defined tables and
111
 forces `mysqldump` to skip the data.
112
113
 Separate each table to strip by a space.
114
 You can use wildcards like * and ? in the table names to strip multiple
115
 tables. In addition you can specify pre-defined table groups, that start
116
 with an
117
118
 Example: "dataflow_batch_export unimportant_module_* @log
119
120
    $ n98-magerun.phar db:dump --strip="@stripped"
121
122
<comment>Available Table Groups</comment>
123
124
HELP;
125
126
        $definitions = $this->getTableDefinitions();
0 ignored issues
show
Deprecated Code introduced by
The method N98\Magento\Command\Data...::getTableDefinitions() has been deprecated with message: Use database helper

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
127
        $list = array();
128
        $maxNameLen = 0;
129
        foreach ($definitions as $id => $definition) {
130
            $name = '@' . $id;
131
            $description = isset($definition['description']) ? $definition['description'] . '.' : '';
132
            $nameLen = strlen($name);
133
            if ($nameLen > $maxNameLen) {
134
                $maxNameLen = $nameLen;
135
            }
136
            $list[] = array($name, $description);
137
        }
138
139
        $decrSize = 78 - $maxNameLen - 3;
140
141
        foreach ($list as $entry) {
142
            list($name, $description) = $entry;
143
            $delta = max(0, $maxNameLen - strlen($name));
144
            $spacer = $delta ? str_repeat(' ', $delta) : '';
145
            $buffer = wordwrap($description, $decrSize);
146
            $buffer = strtr($buffer, array("\n" => "\n" . str_repeat(' ', 3 + $maxNameLen)));
147
            $messages .= sprintf(" <info>%s</info>%s  %s\n", $name, $spacer, $buffer);
148
        }
149
150
        return $messages;
151
    }
152
153
    public function getHelp()
154
    {
155
        return
156
            parent::getHelp() . PHP_EOL
157
            . $this->getCompressionHelp() . PHP_EOL
158
            . $this->getTableDefinitionHelp();
159
    }
160
161
    /**
162
     * @param InputInterface $input
163
     * @param OutputInterface $output
164
     *
165
     * @return int|void
166
     */
167
    protected function execute(InputInterface $input, OutputInterface $output)
168
    {
169
        // communicate early what is required for this command to run (is enabled)
170
        $enabler = new Enabler($this);
171
        $enabler->functionExists('exec');
172
        $enabler->functionExists('passthru');
173
        $enabler->operatingSystemIsNotWindows();
174
175
        $this->detectDbSettings($output);
176
177
        if (!$input->getOption('stdout') && !$input->getOption('only-command')
178
            && !$input->getOption('print-only-filename')
179
        ) {
180
            $this->writeSection($output, 'Dump MySQL Database');
181
        }
182
183
        $compressor = $this->getCompressor($input->getOption('compression'));
184
        $fileName = $this->getFileName($input, $output, $compressor);
185
186
        $stripTables = array();
187 View Code Duplication
        if ($input->getOption('strip')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
188
            /* @var $database DatabaseHelper */
189
            $database = $this->getHelper('database');
190
            $stripTables = $database->resolveTables(explode(' ', $input->getOption('strip')),
191
                $this->getTableDefinitions());
0 ignored issues
show
Deprecated Code introduced by
The method N98\Magento\Command\Data...::getTableDefinitions() has been deprecated with message: Use database helper

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
192
            if (!$input->getOption('stdout') && !$input->getOption('only-command')
193
                && !$input->getOption('print-only-filename')
194
            ) {
195
                $output->writeln('<comment>No-data export for: <info>' . implode(' ', $stripTables)
196
                    . '</info></comment>'
197
                );
198
            }
199
        }
200
201
        $excludeTables = array();
202 View Code Duplication
        if ($input->getOption('exclude')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
203
            $excludeTables = $this->getHelper('database')->resolveTables(explode(' ', $input->getOption('exclude')),
204
                $this->getTableDefinitions());
0 ignored issues
show
Deprecated Code introduced by
The method N98\Magento\Command\Data...::getTableDefinitions() has been deprecated with message: Use database helper

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
205
            if (!$input->getOption('stdout') && !$input->getOption('only-command')
206
                && !$input->getOption('print-only-filename')
207
            ) {
208
                $output->writeln('<comment>Excluded: <info>' . implode(' ', $excludeTables)
209
                    . '</info></comment>'
210
                );
211
            }
212
        }
213
214
        $dumpOptions = '';
215
        if (!$input->getOption('no-single-transaction')) {
216
            $dumpOptions = '--single-transaction --quick ';
217
        }
218
219
        if ($input->getOption('human-readable')) {
220
            $dumpOptions .= '--complete-insert --skip-extended-insert ';
221
        }
222
223
        if ($input->getOption('add-routines')) {
224
            $dumpOptions .= '--routines ';
225
        }
226
227
        if ($input->getOption('xml')) {
228
            $dumpOptions .= '--xml ';
229
        }
230
231
        if ($input->getOption('hex-blob')) {
232
            $dumpOptions .= '--hex-blob ';
233
        }
234
235
        $execs = array();
236
237
        $ignore = '';
238
        foreach (array_merge($excludeTables, $stripTables) as $tableName) {
239
            $ignore .= '--ignore-table=' . $this->dbSettings['dbname'] . '.' . $tableName . ' ';
240
        }
241
242
        $mysqlClientToolConnectionString = $this->getHelper('database')->getMysqlClientToolConnectionString();
243
244
        if (count($stripTables) > 0) {
245
            // dump structure for strip-tables
246
            $exec = 'mysqldump ' . $dumpOptions . '--no-data ' . $mysqlClientToolConnectionString;
247
            $exec .= ' ' . implode(' ', $stripTables);
248
            $exec .= $this->postDumpPipeCommands();
249
            $exec = $compressor->getCompressingCommand($exec);
250
            if (!$input->getOption('stdout')) {
251
                $exec .= ' > ' . escapeshellarg($fileName);
252
            }
253
            $execs[] = $exec;
254
        }
255
256
        // dump data for all other tables
257
        $exec = 'mysqldump ' . $dumpOptions . $mysqlClientToolConnectionString . ' ' . $ignore;
258
        $exec .= $this->postDumpPipeCommands();
259
        $exec = $compressor->getCompressingCommand($exec);
260
        if (!$input->getOption('stdout')) {
261
            $exec .= (count($stripTables) > 0 ? ' >> ' : ' > ') . escapeshellarg($fileName);
262
        }
263
        $execs[] = $exec;
264
265
        $this->runExecs($execs, $fileName, $input, $output);
266
    }
267
268
    /**
269
     * @param array $execs
270
     * @param string $fileName
271
     * @param InputInterface $input
272
     * @param OutputInterface $output
273
     */
274
    private function runExecs(array $execs, $fileName, InputInterface $input, OutputInterface $output)
275
    {
276
        if ($input->getOption('only-command') && !$input->getOption('print-only-filename')) {
277
            foreach ($execs as $exec) {
278
                $output->writeln($exec);
279
            }
280
        } else {
281
            if (!$input->getOption('stdout') && !$input->getOption('only-command')
282
                && !$input->getOption('print-only-filename')
283
            ) {
284
                $output->writeln('<comment>Start dumping database <info>' . $this->dbSettings['dbname']
285
                    . '</info> to file <info>' . $fileName . '</info>'
286
                );
287
            }
288
289
            foreach ($execs as $exec) {
290
                $commandOutput = '';
291
                if ($input->getOption('stdout')) {
292
                    passthru($exec, $returnValue);
293
                } else {
294
                    Exec::run($exec, $commandOutput, $returnValue);
295
                }
296
                if ($returnValue > 0) {
297
                    $output->writeln('<error>' . $commandOutput . '</error>');
298
                    $output->writeln('<error>Return Code: ' . $returnValue . '. ABORTED.</error>');
299
300
                    return;
301
                }
302
            }
303
304
            if (!$input->getOption('stdout') && !$input->getOption('print-only-filename')) {
305
                $output->writeln('<info>Finished</info>');
306
            }
307
        }
308
309
        if ($input->getOption('print-only-filename')) {
310
            $output->writeln($fileName);
311
        }
312
    }
313
314
    /**
315
     * Commands which filter mysql data. Piped to mysqldump command
316
     *
317
     * @return string
318
     */
319
    protected function postDumpPipeCommands()
320
    {
321
        return ' | LANG=C LC_CTYPE=C LC_ALL=C sed -e ' . escapeshellarg('s/DEFINER[ ]*=[ ]*[^*]*\*/\*/');
322
    }
323
324
    /**
325
     * @param InputInterface $input
326
     * @param OutputInterface $output
327
     * @param Compressor $compressor
328
     *
329
     * @return string
330
     */
331
    protected function getFileName(InputInterface $input, OutputInterface $output, Compressor $compressor)
332
    {
333
        $namePrefix = '';
334
        $nameSuffix = '';
335
        if ($input->getOption('xml')) {
336
            $nameExtension = '.xml';
337
        } else {
338
            $nameExtension = '.sql';
339
        }
340
341
342
        if ($input->getOption('add-time') !== false) {
343
            $timeStamp = date('Y-m-d_His');
344
345
            if ($input->getOption('add-time') == 'suffix') {
346
                $nameSuffix = '_' . $timeStamp;
347
            } else {
348
                $namePrefix = $timeStamp . '_';
349
            }
350
        }
351
352
        if ((($fileName = $input->getArgument('filename')) === null || ($isDir = is_dir($fileName))) && !$input->getOption('stdout')) {
353
            /** @var DialogHelper $dialog */
354
            $dialog = $this->getHelperSet()->get('dialog');
355
            $defaultName = VerifyOrDie::filename($namePrefix . $this->dbSettings['dbname'] . $nameSuffix . $nameExtension);
356
            if (isset($isDir) && $isDir) {
357
                $defaultName = rtrim($fileName, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $defaultName;
358
            }
359
            if (!$input->getOption('force')) {
360
                $fileName = $dialog->ask($output, '<question>Filename for SQL dump:</question> [<comment>'
361
                    . $defaultName . '</comment>]', $defaultName
362
                );
363
            } else {
364
                $fileName = $defaultName;
365
            }
366
        } else {
367
            if ($input->getOption('add-time')) {
368
                $pathParts = pathinfo($fileName);
369
                $fileName = ($pathParts['dirname'] == '.' ? '' : $pathParts['dirname'] . DIRECTORY_SEPARATOR) .
370
                    $namePrefix . $pathParts['filename'] . $nameSuffix . '.' . $pathParts['extension'];
371
            }
372
        }
373
374
        $fileName = $compressor->getFileName($fileName);
375
376
        return $fileName;
377
    }
378
}
379