-
-
Notifications
You must be signed in to change notification settings - Fork 203
Expand file tree
/
Copy pathAbstractMultiPlatformMigration.php
More file actions
221 lines (186 loc) · 7.95 KB
/
AbstractMultiPlatformMigration.php
File metadata and controls
221 lines (186 loc) · 7.95 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
<?php
declare(strict_types=1);
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2022 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace App\Migration;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Exception;
use Doctrine\DBAL\Platforms\AbstractMySQLPlatform;
use Doctrine\DBAL\Platforms\PostgreSQLPlatform;
use Doctrine\DBAL\Platforms\SQLitePlatform;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
use Psr\Log\LoggerInterface;
abstract class AbstractMultiPlatformMigration extends AbstractMigration
{
final public const ADMIN_PW_LENGTH = 10;
protected ?string $admin_pw = null;
protected ?string $admin_api_token = null;
/** @noinspection SenselessProxyMethodInspection
* This method is required to redefine the logger type hint to protected
*/
public function __construct(Connection $connection, protected LoggerInterface $logger)
{
parent::__construct($connection, $logger);
}
public function up(Schema $schema): void
{
$db_type = $this->getDatabaseType();
match ($db_type) {
'mysql' => $this->mySQLUp($schema),
'sqlite' => $this->sqLiteUp($schema),
'postgresql' => $this->postgreSQLUp($schema),
default => $this->abortIf(true, "Database type '$db_type' is not supported!"),
};
}
public function down(Schema $schema): void
{
$db_type = $this->getDatabaseType();
match ($db_type) {
'mysql' => $this->mySQLDown($schema),
'sqlite' => $this->sqLiteDown($schema),
'postgresql' => $this->postgreSQLDown($schema),
default => $this->abortIf(true, "Database type is not supported!"),
};
}
/**
* Gets the legacy Part-DB version number. Returns 0, if target database is not a legacy Part-DB database.
*/
public function getOldDBVersion(): int
{
if ('mysql' !== $this->getDatabaseType()) {
//Old Part-DB version only supported MySQL therefore only
return 0;
}
try {
$version = $this->connection->fetchOne("SELECT keyValue AS version FROM `internal` WHERE `keyName` = 'dbVersion'");
if (is_bool($version)) {
return 0;
}
return (int) $version;
} catch (Exception) {
//when the table was not found, we can proceed, because we have an empty DB!
return 0;
}
}
/**
* Returns the hash of a new random password, created for the initial admin user, which can be written to DB.
* The plaintext version of the password will be outputed to user after this migration.
*/
public function getInitalAdminPW(): string
{
if ($this->admin_pw === null) {
if (!empty($_ENV['INITIAL_ADMIN_PW'])) {
$this->admin_pw = $_ENV['INITIAL_ADMIN_PW'];
} else {
$this->admin_pw = substr(md5(random_bytes(10)), 0, static::ADMIN_PW_LENGTH);
}
}
//As we don't have access to container, just use the default PHP pw hash function
return password_hash((string) $this->admin_pw, PASSWORD_DEFAULT);
}
/**
* Returns the initial admin API token if configured via environment variable.
* If not configured, returns empty string (no token will be created).
*/
public function getInitialAdminApiToken(): string
{
if ($this->admin_api_token === null) {
$apiKey = $_ENV('INITIAL_ADMIN_API_KEY');
if (!empty($apiKey)) {
//Ensure the length of the API key is correct
if (strlen($apiKey) < 64) {
$this->abortIf(true, 'The provided INITIAL_ADMIN_API_KEY is too short! It must be at least 64 characters long! You can generate a valid key with "openssl rand -hex 32"');
}
// Use the provided API key directly (should be generated with openssl rand -hex 32)
$this->admin_api_token = $apiKey;
}
}
return $this->admin_api_token;
}
public function postUp(Schema $schema): void
{
parent::postUp($schema);
if ($this->admin_pw !== '') {
$this->logger->warning('');
$this->logger->warning('<bg=yellow;fg=black>The initial password for the "admin" user is: '.$this->admin_pw.'</>');
$this->logger->warning('');
}
if ($this->admin_api_token !== '') {
$this->logger->warning('');
$this->logger->warning('<bg=green;fg=black>Initial admin API token has been created with the provided key</>');
$this->logger->warning('<bg=yellow;fg=black>Use this token in Authorization header: Bearer tcp_'.$this->admin_api_token.'</>');
$this->logger->warning('');
}
}
/**
* Checks if a foreign key on a table exists in the database.
* This method is only supported for MySQL/MariaDB databases yet!
* @return bool Returns true, if the foreign key exists
* @throws Exception
*/
public function doesFKExists(string $table, string $fk_name): bool
{
$db_type = $this->getDatabaseType();
if ($db_type !== 'mysql') {
throw new \RuntimeException('This method is only supported for MySQL/MariaDB databases!');
}
$sql = "SELECT COUNT(*) FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE() AND CONSTRAINT_NAME = '$fk_name' AND TABLE_NAME = '$table' AND CONSTRAINT_TYPE = 'FOREIGN KEY'";
$result = (int) $this->connection->fetchOne($sql);
return $result > 0;
}
/**
* Checks if a column exists in a table.
* @return bool Returns true, if the column exists
* @throws Exception
*/
public function doesColumnExist(string $table, string $column_name): bool
{
$db_type = $this->getDatabaseType();
if ($db_type !== 'mysql') {
throw new \RuntimeException('This method is only supported for MySQL/MariaDB databases!');
}
$sql = "SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '$table' AND COLUMN_NAME = '$column_name'";
$result = (int) $this->connection->fetchOne($sql);
return $result > 0;
}
/**
* Returns the database type of the used database.
* @return string|null Returns 'mysql' for MySQL/MariaDB and 'sqlite' for SQLite. Returns null if unknown type
*/
public function getDatabaseType(): ?string
{
if ($this->connection->getDatabasePlatform() instanceof AbstractMySQLPlatform) {
return 'mysql';
}
if ($this->connection->getDatabasePlatform() instanceof SQLitePlatform) {
return 'sqlite';
}
if ($this->connection->getDatabasePlatform() instanceof PostgreSqlPlatform) {
return 'postgresql';
}
return null;
}
abstract public function mySQLUp(Schema $schema): void;
abstract public function mySQLDown(Schema $schema): void;
abstract public function sqLiteUp(Schema $schema): void;
abstract public function sqLiteDown(Schema $schema): void;
abstract public function postgreSQLUp(Schema $schema): void;
abstract public function postgreSQLDown(Schema $schema): void;
}