Debian Codegraph @

classes/Database/Mariadb/UpgraderMapper.php

raw symbols SCIP
1 <?php
2
3 /**
4 * dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
5 * Copyright (C) 2022-2023 Aleksey Andreev (liuch)
6 *
7 * Available at:
8 * https://github.com/liuch/dmarc-srg
9 *
10 * This program is free software: you can redistribute it and/or modify it
11 * under the terms of the GNU General Public License as published by the Free
12 * Software Foundation, either version 3 of the License.
13 *
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
17 * more details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * this program. If not, see <http://www.gnu.org/licenses/>.
21 *
22 * =========================
23 *
24 * This file contains the UpgraderMapper class
25 *
26 * @category API
27 * @package DmarcSrg
28 * @author Aleksey Andreev (liuch)
29 * @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
30 */
31
32 namespace Liuch\DmarcSrg\Database\Mariadb;
33
34 use Liuch\DmarcSrg\Database\UpgraderMapperInterface;
35 use Liuch\DmarcSrg\Exception\SoftException;
36 use Liuch\DmarcSrg\Exception\DatabaseFatalException;
37 use Liuch\DmarcSrg\Exception\DatabaseNotFoundException;
38
39 /**
40 * UpgraderMapper class implementation for MariaDB
41 */
42 class UpgraderMapper implements UpgraderMapperInterface
43 {
44 /** @var Connector */
45 private $connector = null;
46
47 /**
48 * The constructor
49 *
50 * @param Connector $connector
51 */
52 public function __construct(object $connector)
53 {
54 $this->connector = $connector;
55 }
56
57 /**
58 * Starts upgrading the database structure
59 *
60 * @param string $target Target version of the database structure to upgrade to
61 *
62 * @return void
63 */
64 public function go(string $target): void
65 {
66 try {
67 $cur_ver = $this->connector->getMapper('setting')->value('version', 0);
68 } catch (DatabaseNotFoundException $e) {
69 $cur_ver = 'null';
70 }
71
72 while ($cur_ver !== $target) {
73 if (!isset(self::$upways['ver_' . $cur_ver])) {
74 throw new SoftException(
75 "Upgrading failed: There is no way to upgrade from {$cur_ver} to {$target}"
76 );
77 }
78 $um = self::$upways['ver_' . $cur_ver];
79 $cur_ver = $this->$um();
80 }
81 }
82
83 /**
84 * Upgrades the database structure from None to 0.1
85 *
86 * @return string New version of the database structure
87 */
88 private function upNull(): string
89 {
90 $db = $this->connector->dbh();
91 $db->beginTransaction();
92 try {
93 $this->connector->setANSIMode(false);
94 $db->query(
95 'INSERT INTO `' . $this->connector->tablePrefix('system')
96 . '` (`key`, value) VALUES ("version", "0.1")'
97 );
98 $db->commit();
99 } catch (\PDOException $e) {
100 $db->rollBack();
101 throw $this->dbFatalException($e);
102 } catch (\Exception $e) {
103 $db->rollBack();
104 throw $e;
105 } finally {
106 $this->connector->setANSIMode(true);
107 }
108 return '0.1';
109 }
110
111 /**
112 * Upgrades the database structure from 0.1 to 1.0
113 *
114 * @return string New version of the database structure
115 */
116 private function up01(): string
117 {
118 $db = $this->connector->dbh();
119 // Transaction would be useful here but it doesn't work with ALTER TABLE in MySQL/MariaDB
120 try {
121 $this->connector->setANSIMode(false);
122 $dom_tn = $this->connector->tablePrefix('domains');
123 if (!$this->columnExists($db, $dom_tn, 'active')) {
124 $db->query(
125 'ALTER TABLE ' . $dom_tn . ' ADD COLUMN active boolean NOT NULL AFTER fqdn'
126 );
127 }
128 if (!$this->columnExists($db, $dom_tn, 'created_time')) {
129 $db->query(
130 'ALTER TABLE ' . $dom_tn . ' ADD COLUMN created_time datetime NOT NULL'
131 );
132 }
133 if (!$this->columnExists($db, $dom_tn, 'updated_time')) {
134 $db->query(
135 'ALTER TABLE ' . $dom_tn . ' ADD COLUMN updated_time datetime NOT NULL'
136 );
137 }
138 $db->query(
139 'UPDATE ' . $dom_tn . ' SET active = TRUE, created_time = NOW(), updated_time = NOW()'
140 );
141 $db->query(
142 'UPDATE `' . $this->connector->tablePrefix('system') . '` SET value = "1.0" WHERE `key` = "version"'
143 );
144 } catch (\PDOException $e) {
145 throw $this->dbFatalException($e);
146 } finally {
147 $this->connector->setANSIMode(true);
148 }
149 return '1.0';
150 }
151
152 /**
153 * Upgrades the database structure from 1.0 to 2.0
154 *
155 * @return string New version of the database structure
156 */
157 private function up10(): string
158 {
159 $db = $this->connector->dbh();
160 // Transaction would be useful here but it doesn't work with ALTER TABLE in MySQL/MariaDB
161 try {
162 $this->connector->setANSIMode(false);
163 $sys_tn = $this->connector->tablePrefix('system');
164 $db->query(
165 'ALTER TABLE `' . $sys_tn . '` MODIFY COLUMN `key` varchar(64) NOT NULL'
166 );
167 $db->query(
168 'UPDATE `' . $sys_tn . '` SET value = "2.0" WHERE `key` = "version"'
169 );
170 } catch (\PDOException $e) {
171 throw $this->dbFatalException($e);
172 } finally {
173 $this->connector->setANSIMode(true);
174 }
175 return '2.0';
176 }
177
178 /**
179 * Upgrades the database structure from v2.0 to v3.0
180 *
181 * @return string New version of the database structure
182 */
183 private function up20(): string
184 {
185 $db = $this->connector->dbh();
186 // Transaction would be useful here but it doesn't work with ALTER TABLE in MySQL/MariaDB
187 try {
188 $this->connector->setANSIMode(false);
189 $rep_tn = $this->connector->tablePrefix('reports');
190 if (!$this->columnExists($db, $rep_tn, 'policy_np')) {
191 $db->query(
192 'ALTER TABLE ' . $rep_tn . ' ADD COLUMN policy_np varchar(20) NULL AFTER policy_sp'
193 );
194 }
195 $sys_tn = $this->connector->tablePrefix('system');
196 $db->query(
197 'UPDATE `' . $sys_tn . '` SET value = "3.0" WHERE `key` = "version"'
198 );
199 } catch (\PDOException $e) {
200 throw $this->dbFatalException($e);
201 } finally {
202 $this->connector->setANSIMode(true);
203 }
204 return '3.0';
205 }
206
207 /**
208 * Upgrades the database structure from v3.0 to v3.1
209 *
210 * @return string New version of the database
211 */
212 private function up30(): string
213 {
214 $db = $this->connector->dbh();
215 try {
216 $this->connector->setANSIMode(false);
217 $rep_tn = $this->connector->tablePrefix('reports');
218 if (!$this->indexExists($db, $rep_tn, 'org_time_id')) {
219 $db->query(
220 'CREATE INDEX org_time_id ON ' . $rep_tn . ' (domain_id, begin_time, org, external_id)'
221 );
222 }
223 if ($this->indexExists($db, $rep_tn, 'external_id')) {
224 $db->query(
225 'DROP INDEX external_id ON ' . $rep_tn
226 );
227 }
228 $sys_tn = $this->connector->tablePrefix('system');
229 $db->query(
230 'UPDATE `' . $sys_tn . '` SET value = "3.1" WHERE `key` = "version"'
231 );
232 } catch (\PDOException $e) {
233 throw $this->dbFatalException($e);
234 } finally {
235 $this->connector->setANSIMode(true);
236 }
237 return '3.1';
238 }
239
240 /**
241 * Upgrades the database structure from v3.1 to v3.2
242 *
243 * @return string New version of the database structure
244 */
245 private function up31(): string
246 {
247 $db = $this->connector->dbh();
248 try {
249 $this->connector->setANSIMode(false);
250 $rep_tn = $this->connector->tablePrefix('reports');
251 // Remove duplicates
252 $db->query(
253 'CREATE TEMPORARY TABLE up31_ids AS (SELECT MIN(id) AS id FROM ' . $rep_tn
254 . ' GROUP BY domain_id, begin_time, org, external_id)'
255 );
256 $db->query('DELETE FROM ' . $rep_tn . ' WHERE id NOT IN (SELECT id FROM up31_ids)');
257 // Create a new unique index
258 if (!$this->indexExists($db, $rep_tn, 'org_time_id_u')) {
259 $db->query(
260 'CREATE UNIQUE INDEX org_time_id_u ON ' . $rep_tn
261 . ' (domain_id, begin_time, org, external_id)'
262 );
263 }
264 // Remove the old index
265 if ($this->indexExists($db, $rep_tn, 'org_time_id')) {
266 $db->query(
267 'DROP INDEX org_time_id ON ' . $rep_tn
268 );
269 }
270 // Update version
271 $sys_tn = $this->connector->tablePrefix('system');
272 $db->query(
273 'UPDATE `' . $sys_tn . '` SET value = "3.2" WHERE `key` = "version"'
274 );
275 } catch (\PDOException $e) {
276 throw $this->dbFatalException($e);
277 } finally {
278 $this->connector->setANSIMode(true);
279 }
280 return '3.2';
281 }
282
283 /**
284 * Upgrades the database structure from v3.2 to v4.0
285 *
286 * @return string New version of the database structure
287 */
288 private function up32(): string
289 {
290 $db = $this->connector->dbh();
291 try {
292 $this->connector->setANSIMode(false);
293 $usr_tn = $this->connector->tablePrefix('users');
294 $db->query(
295 'CREATE TABLE IF NOT EXISTS ' . $usr_tn . ' (id int(10) unsigned NOT NULL AUTO_INCREMENT,'
296 . ' name varchar(32) NOT NULL, level smallint unsigned NOT NULL, enabled boolean NOT NULL,'
297 . ' password varchar(255) NULL, email varchar(64) NULL, `key` varchar(64) NULL,'
298 . ' session int(10) NOT NULL, created_time datetime NOT NULL, updated_time datetime NOT NULL,'
299 . ' PRIMARY KEY (id), UNIQUE KEY name (name)) ENGINE=InnoDB DEFAULT CHARSET=utf8'
300 );
301
302 $ud_tn = $this->connector->tablePrefix('userdomains');
303 $db->query(
304 'CREATE TABLE IF NOT EXISTS ' . $ud_tn . ' (domain_id int(10) unsigned NOT NULL,'
305 . ' user_id int(10) unsigned NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8'
306 );
307 if (!$this->indexExists($db, $ud_tn, 'PRIMARY')) {
308 $db->query('ALTER TABLE ' . $ud_tn . ' ADD PRIMARY KEY (domain_id, user_id)');
309 }
310
311 $sys_tn = $this->connector->tablePrefix('system');
312 if (!$this->columnExists($db, $sys_tn, 'user_id')) {
313 $db->query(
314 'ALTER TABLE `' . $sys_tn . '` ADD COLUMN user_id int(10) NOT NULL DEFAULT 0 AFTER `key`'
315 );
316 }
317 $db->query('UPDATE `' . $sys_tn . '` SET user_id = 0');
318 if ($this->indexExists($db, $sys_tn, 'PRIMARY')) {
319 $db->query('ALTER TABLE ' . $sys_tn . ' DROP PRIMARY KEY');
320 }
321 $db->query('ALTER TABLE ' . $sys_tn . ' ADD PRIMARY KEY (user_id, `key`)');
322
323 $log_tn = $this->connector->tablePrefix('reportlog');
324 if (!$this->columnExists($db, $log_tn, 'user_id')) {
325 $db->query(
326 'ALTER TABLE ' . $log_tn . ' ADD COLUMN user_id int(10) NOT NULL DEFAULT 0 AFTER id'
327 );
328 }
329 if (!$this->indexExists($db, $log_tn, 'user_id')) {
330 $db->query('ALTER TABLE ' . $log_tn . ' ADD KEY user_id (user_id, event_time)');
331 }
332
333 $db->query(
334 'UPDATE ' . $sys_tn . ' SET value = "4.0" WHERE user_id = 0 AND `key` = "version"'
335 );
336 } catch (\PDOException $e) {
337 throw $this->dbFatalException($e);
338 } finally {
339 $this->connector->setANSIMode(true);
340 }
341 return '4.0';
342 }
343
344 /**
345 * Checks if the specified column exists in the specified table of the database
346 *
347 * @param object $db Connection handle of the database
348 * @param string $table Table name with the prefix
349 * @param string $column Column name
350 *
351 * @return bool
352 */
353 private function columnExists($db, string $table, string $column): bool
354 {
355 $st = $db->prepare(
356 'SELECT NULL FROM INFORMATION_SCHEMA.COLUMNS'
357 . ' WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?'
358 );
359 $st->bindValue(1, $table, \PDO::PARAM_STR);
360 $st->bindValue(2, $column, \PDO::PARAM_STR);
361 $st->execute();
362 $res = $st->fetch(\PDO::FETCH_NUM);
363 $st->closeCursor();
364 return $res ? true : false;
365 }
366
367 /**
368 * Checks if the specified index exists in the specified table of the database
369 *
370 * @param object $db Database connection handle
371 * @param string $table Table name with the prefix
372 * @param string $index Index name to check
373 *
374 * @return bool
375 */
376 private function indexExists($db, string $table, string $index): bool
377 {
378 $st = $db->prepare(
379 'SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS'
380 . ' WHERE table_schema = DATABASE() AND table_name = ? AND index_name = ? LIMIT 1'
381 );
382 $st->bindValue(1, $table, \PDO::PARAM_STR);
383 $st->bindValue(2, $index, \PDO::PARAM_STR);
384 $st->execute();
385 $res = $st->fetch(\PDO::FETCH_NUM);
386 $st->closeCursor();
387 return $res ? true : false;
388 }
389
390 /**
391 * Return an instance of DatabaseFatalException
392 *
393 * @param \Exception $e The original exception
394 *
395 * @return DatabaseFatalException
396 */
397 private function dbFatalException($e)
398 {
399 return new DatabaseFatalException('Failed to upgrade the database structure', -1, $e);
400 }
401
402 private static $upways = [
403 'ver_null' => 'upNull',
404 'ver_0.1' => 'up01',
405 'ver_1.0' => 'up10',
406 'ver_2.0' => 'up20',
407 'ver_3.0' => 'up30',
408 'ver_3.1' => 'up31',
409 'ver_3.2' => 'up32'
410 ];
411 }