-
Notifications
You must be signed in to change notification settings - Fork 11
/
TargetDb.php
244 lines (199 loc) · 6.55 KB
/
TargetDb.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
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
<?php
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Plugins\Migration;
use Piwik\Common;
use Piwik\Db;
use Piwik\DbHelper;
use Piwik\Sequence;
use Exception;
class TargetDb
{
/**
* @var \Zend_Db_Adapter_Abstract
*/
private $db;
private $config = [];
private $dryRun = false;
private $useTransactions = true;
public function __construct($config)
{
foreach (Db::getDatabaseConfig() as $key => $val) {
$this->config[$key] = $val; // otherwise we change the reference of DB config :(
}
foreach ($config as $key => $val) {
$this->config[$key] = $val;
}
$this->db = $this->testConnection($this->config);
return $this->db;
}
public function disableTransactions()
{
$this->useTransactions = false;
}
public function enableDryRun()
{
$this->dryRun = true;
}
public function beginTransaction()
{
if ($this->useTransactions) {
$this->db->beginTransaction();
}
}
public function rollBack()
{
if ($this->useTransactions) {
$this->db->rollBack();
}
}
public function commit()
{
if ($this->useTransactions) {
$this->db->commit();
}
}
public function fetchRow($sql, $bind = [], $fetchMode = null)
{
return $this->db->fetchRow($sql, $bind, $fetchMode);
}
/**
* @ignore tests only
*/
public function getDb()
{
return $this->db;
}
public function getTableColumns($tableName)
{
$allColumns = $this->db->fetchAll("SHOW COLUMNS FROM `$tableName`");
$fields = [];
foreach ($allColumns as $column) {
$fields[trim($column['Field'])] = $column;
}
return $fields;
}
public function doesTableExist($targetDbTableName)
{
$foundTable = $this->db->fetchAll("SHOW TABLES LIKE '" . $targetDbTableName . "'");
return !empty($foundTable);
}
public function createArchiveTableIfNeeded($table)
{
$sourceDbTableName = Common::prefixTable($table);
$targetDbTableName = $this->prefixTable($table);
if (!$this->doesTableExist($targetDbTableName)) {
$type = 'archive_numeric';
if (strpos($table, 'blob') !== false) {
$type = 'archive_blob';
}
$createTableSql = DbHelper::getTableCreateSql($type);
$createTableSql = str_replace($type, $table, $createTableSql);
$createTableSql = str_replace($sourceDbTableName, $targetDbTableName, $createTableSql);
if (!$this->dryRun) {
$this->db->query($createTableSql);
}
}
$numericTableName = str_replace('archive_blob', 'archive_numeric', $targetDbTableName);
if (!$this->dryRun) {
// need to make sure the correct sequence entry exists otherwise there may be random issues where it never gets created properly
$this->makeSequenceEnsureExists($numericTableName);
}
if ($this->doesTableExist($numericTableName)) {
// make sure sequence value is correct in case it is out of sync see #30
$val = $this->getMaxArchiveId($numericTableName);
if (!empty($val)) {
$val = $val + 20; // +20 to allow other sequences to be created concurrently
if (!$this->dryRun) {
$sequenceTable = $this->prefixTable(Sequence::TABLE_NAME);
// we also do +1 if the value is already high just to be safe...
$this->db->query("UPDATE `$sequenceTable` SET `value` = if(`value` < ?, ?, `value` + 1) WHERE `name` = ?", [$val, $val, $targetDbTableName]);
}
}
}
}
public function getMaxArchiveId($targetDbTableNamePrefixed)
{
$val = $this->db->fetchOne("SELECT max(idarchive) FROM `$targetDbTableNamePrefixed`");
if (empty($val)) {
$val = 0;
}
return $val;
}
private function makeSequenceEnsureExists($prefixedArchiveNumericTableName)
{
$sequence = new Sequence($prefixedArchiveNumericTableName, $this->db, $this->prefixTable(''));
if (!$sequence->exists()) {
$sequence->create();
}
return $sequence;
}
public function createArchiveId($table)
{
if ($this->dryRun) {
return mt_rand(1, 9999);
}
$name = $this->prefixTable($table);
$sequence = $this->makeSequenceEnsureExists($name);
return $sequence->getNextId();
}
public function prefixTable($table)
{
return $this->config['tables_prefix'] . $table;
}
public function insert($table, $row)
{
$columns = implode('`,`', array_keys($row));
$fields = Common::getSqlStringFieldsArray($row);
$tablePrefixed = $this->prefixTable($table);
$sql = sprintf('INSERT INTO `%s` (`%s`) VALUES(%s)', $tablePrefixed, $columns, $fields);
$bind = array_values($row);
if ($this->dryRun) {
return mt_rand(1, 999999);
}
$this->db->query($sql, $bind);
$id = $this->db->lastInsertId();
return (int) $id;
}
public function update($table, $columns, $whereColumns)
{
if (!empty($columns)) {
$fields = [];
$bind = [];
foreach ($columns as $key => $value) {
$fields[] = " `$key` = ?";
$bind[] = $value;
}
$fields = implode(',', $fields);
$where = [];
foreach ($whereColumns as $col => $val) {
$where[] = " `$col` = ?";
$bind[] = $val;
}
$where = implode(' AND ', $where);
$query = sprintf('UPDATE `%s` SET %s WHERE %s', $this->prefixTable($table), $fields, $where);
$this->db->query($query, $bind);
}
}
/**
* @param array $config
* @return Db\AdapterInterface
*/
private function testConnection($config)
{
try {
$adapter = $config['adapter'];
if ($adapter === 'WordPress') {
$adapter = 'Mysqli';
}
$db = @Db\Adapter::factory($adapter, $config);
} catch (Exception $e) {
throw new Exception('Cannot connect to the target database: ' . $e->getMessage(), $e->getCode(), $e);
}
return $db;
}
}