1: <?php
2:
3: App::uses('DatasourceDumper', 'Datasources.Lib');
4:
5: class MysqlDumper implements DatasourceDumper {
6:
7: private $dumpCommand = 'mysqldump';
8: private $loadCommand = 'mysql';
9:
10: public function dump(\Datasource $ds, $filepath) {
11: if (!$this->_commandExists($this->dumpCommand)) {
12: throw new Exception("Command \"{$this->dumpCommand}\" no exists");
13: }
14: $this->_executeMysqlCommand(
15: $ds,
16: escapeshellarg($this->dumpCommand) .
17: ' ' . escapeshellarg('--lock-tables=false'),
18: ' > ' . escapeshellarg($filepath));
19: }
20:
21: public function load(\Datasource $ds, $filepath) {
22: if (!$this->_commandExists($this->loadCommand)) {
23: throw new Exception("Command \"{$this->loadCommand}\" no exists");
24: }
25: $this->_executeMysqlCommand(
26: $ds, escapeshellarg($this->loadCommand),
27: ' < ' . escapeshellarg($filepath));
28: }
29:
30: private function _executeMysqlCommand(\Datasource $ds, $command, $append) {
31: if ($ds->config['host']) {
32: $command .= ' -h ' . escapeshellarg($ds->config['host']);
33: }
34:
35: if ($ds->config['port']) {
36: $command .= ' -P ' . escapeshellarg($ds->config['port']);
37: }
38:
39: if ($ds->config['password']) {
40: $command .= ' ' . escapeshellarg('-p' . $ds->config['password']);
41: }
42:
43: if ($ds->config['login']) {
44: $command .= ' -u ' . escapeshellarg($ds->config['login']);
45: }
46:
47: $command .= ' ' . escapeshellarg($ds->config['database']);
48: $command .= ' ' . $append;
49: exec($command, $output, $return);
50:
51: if ($return != 0) {
52: throw new Exception("Command \"$command\" returned $return. Output: " . implode("\n", $output));
53: }
54: }
55:
56: private function _commandExists($command) {
57: exec(escapeshellarg($command) . ' --version', $output, $returnVar);
58: return $returnVar === 0;
59: }
60:
61: public function clear(Datasource $ds) {
62: foreach ($this->_listTables($ds) as $table) {
63: $this->_dropTable($ds, $table);
64: }
65: }
66:
67: private function _listTables(Mysql $ds) {
68: $result = $ds->query('show tables');
69: $tables = array();
70: foreach ($result as $r1) {
71: foreach ($r1 as $r2) {
72: foreach ($r2 as $r3) {
73: if ($ds->config['prefix'] == '' || strpos($r3, $ds->config['prefix']) === 0) {
74: $tables[] = $r3;
75: }
76: }
77: }
78: }
79: return $tables;
80: }
81:
82: private function _dropTable(Mysql $ds, $table) {
83: $ds->query("Drop table `$table`");
84: }
85:
86: }
87: