-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathSchemaManager.php
308 lines (262 loc) · 11.5 KB
/
SchemaManager.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
<?php
namespace DH\Auditor\Provider\Doctrine\Persistence\Schema;
use DH\Auditor\Provider\Doctrine\Configuration;
use DH\Auditor\Provider\Doctrine\DoctrineProvider;
use DH\Auditor\Provider\Doctrine\Persistence\Helper\DoctrineHelper;
use DH\Auditor\Provider\Doctrine\Persistence\Helper\PlatformHelper;
use DH\Auditor\Provider\Doctrine\Persistence\Helper\SchemaHelper;
use DH\Auditor\Provider\Doctrine\Service\AuditingService;
use DH\Auditor\Provider\Doctrine\Service\StorageService;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\SchemaException;
use Doctrine\DBAL\Schema\Table;
use Doctrine\ORM\EntityManagerInterface;
class SchemaManager
{
/**
* @var DoctrineProvider
*/
private $provider;
public function __construct(DoctrineProvider $provider)
{
$this->provider = $provider;
}
public function updateAuditSchema(?array $sqls = null, ?callable $callback = null): void
{
if (null === $sqls) {
$sqls = $this->getUpdateAuditSchemaSql();
}
/** @var StorageService[] $storageServices */
$storageServices = $this->provider->getStorageServices();
foreach ($sqls as $name => $queries) {
foreach ($queries as $index => $sql) {
$statement = $storageServices[$name]->getEntityManager()->getConnection()->prepare($sql);
$statement->execute();
if (null !== $callback) {
$callback([
'total' => \count($sqls),
'current' => $index,
]);
}
}
}
}
/**
* Returns an array of audit table names indexed by entity FQN.
* Only auditable entities are considered.
*
* @throws \Doctrine\ORM\ORMException
*/
public function getAuditableTableNames(EntityManagerInterface $entityManager): array
{
$metadataDriver = $entityManager->getConfiguration()->getMetadataDriverImpl();
$entities = [];
if (null !== $metadataDriver) {
$entities = $metadataDriver->getAllClassNames();
}
$audited = [];
foreach ($entities as $entity) {
if ($this->provider->isAuditable($entity)) {
$audited[$entity] = $entityManager->getClassMetadata($entity)->getTableName();
}
}
ksort($audited);
return $audited;
}
public function getUpdateAuditSchemaSql(): array
{
/** @var Configuration $configuration */
$configuration = $this->provider->getConfiguration();
/** @var StorageService[] $storageServices */
$storageServices = $this->provider->getStorageServices();
// auditable entities by storage entity manager
$repository = [];
// Collect auditable entities from auditing entity managers
/** @var AuditingService[] $auditingServices */
$auditingServices = $this->provider->getAuditingServices();
foreach ($auditingServices as $name => $auditingService) {
$classes = $this->getAuditableTableNames($auditingService->getEntityManager());
// Populate the auditable entities repository
foreach ($classes as $entity => $tableName) {
$storageService = $this->provider->getStorageServiceForEntity($entity);
$key = array_search($storageService, $this->provider->getStorageServices(), true);
if (!isset($repository[$key])) {
$repository[$key] = [];
}
$repository[$key][$entity] = $tableName;
}
}
$findEntityByTablename = static function (string $tableName) use ($repository): ?string {
foreach ($repository as $emName => $map) {
$result = array_search($tableName, $map, true);
if (false !== $result) {
return (string) $result;
}
}
return null;
};
// Compute and collect SQL queries
$sqls = [];
foreach ($repository as $name => $classes) {
$storageSchemaManager = $storageServices[$name]->getEntityManager()->getConnection()->getSchemaManager();
$storageSchema = $storageSchemaManager->createSchema();
$fromSchema = clone $storageSchema;
$processed = [];
foreach ($classes as $entity => $tableName) {
if (!\in_array($tableName, $processed, true)) {
/** @var string $auditTablename */
$auditTablename = preg_replace(
sprintf('#^([^\.]+\.)?(%s)$#', preg_quote($tableName, '#')),
sprintf(
'$1%s$2%s',
preg_quote($configuration->getTablePrefix(), '#'),
preg_quote($configuration->getTableSuffix(), '#')
),
$tableName
);
if ($storageSchema->hasTable($auditTablename)) {
// Audit table exists, let's update it if needed
$this->updateAuditTable($findEntityByTablename($tableName), $storageSchema->getTable($auditTablename), $storageSchema);
} else {
// Audit table does not exists, let's create it
$this->createAuditTable($findEntityByTablename($tableName), $tableName, $storageSchema);
}
$processed[] = $tableName;
}
}
$sqls[$name] = $fromSchema->getMigrateToSql($storageSchema, $storageSchemaManager->getDatabasePlatform());
}
return $sqls;
}
/**
* Creates an audit table.
*
* @param mixed $table
*/
public function createAuditTable(string $entity, $table, ?Schema $schema = null): Schema
{
/** @var StorageService $storageService */
$storageService = $this->provider->getStorageServiceForEntity($entity);
$connection = $storageService->getEntityManager()->getConnection();
if (null === $schema) {
$schemaManager = $connection->getSchemaManager();
$schema = $schemaManager->createSchema();
}
/** @var Configuration $configuration */
$configuration = $this->provider->getConfiguration();
$tableName = $table instanceof Table ? $table->getName() : (string) $table;
$auditTablename = preg_replace(
sprintf('#^([^\.]+\.)?(%s)$#', preg_quote($tableName, '#')),
sprintf(
'$1%s$2%s',
preg_quote($configuration->getTablePrefix(), '#'),
preg_quote($configuration->getTableSuffix(), '#')
),
$tableName
);
if (null !== $auditTablename && !$schema->hasTable($auditTablename)) {
$auditTable = $schema->createTable($auditTablename);
// Add columns to audit table
$isJsonSupported = PlatformHelper::isJsonSupported($connection);
foreach (SchemaHelper::getAuditTableColumns() as $columnName => $struct) {
if (DoctrineHelper::getDoctrineType('JSON') === $struct['type'] && $isJsonSupported) {
$type = DoctrineHelper::getDoctrineType('TEXT');
} else {
$type = $struct['type'];
}
$auditTable->addColumn($columnName, $type, $struct['options']);
}
// Add indices to audit table
foreach (SchemaHelper::getAuditTableIndices($auditTablename) as $columnName => $struct) {
if ('primary' === $struct['type']) {
$auditTable->setPrimaryKey([$columnName]);
} else {
$auditTable->addIndex(
[$columnName],
$struct['name'],
[],
PlatformHelper::isIndexLengthLimited($columnName, $connection) ? ['lengths' => [191]] : []
);
}
}
}
return $schema;
}
/**
* Ensures an audit table's structure is valid.
*
* @throws SchemaException
*/
public function updateAuditTable(string $entity, Table $table, ?Schema $schema = null): Schema
{
/** @var StorageService $storageService */
$storageService = $this->provider->getStorageServiceForEntity($entity);
$connection = $storageService->getEntityManager()->getConnection();
$schemaManager = $connection->getSchemaManager();
if (null === $schema) {
$schema = $schemaManager->createSchema();
}
$table = $schema->getTable($table->getName());
$columns = $schemaManager->listTableColumns($table->getName());
// process columns
$this->processColumns($table, $columns, SchemaHelper::getAuditTableColumns(), $connection);
// process indices
$this->processIndices($table, SchemaHelper::getAuditTableIndices($table->getName()), $connection);
return $schema;
}
private function processColumns(Table $table, array $columns, array $expectedColumns, Connection $connection): void
{
$processed = [];
$isJsonSupported = PlatformHelper::isJsonSupported($connection);
foreach ($columns as $column) {
if (\array_key_exists($column->getName(), $expectedColumns)) {
// column is part of expected columns
$table->dropColumn($column->getName());
if (DoctrineHelper::getDoctrineType('JSON') === $expectedColumns[$column->getName()]['type'] && $isJsonSupported) {
$type = DoctrineHelper::getDoctrineType('TEXT');
} else {
$type = $expectedColumns[$column->getName()]['type'];
}
$table->addColumn($column->getName(), $type, $expectedColumns[$column->getName()]['options']);
} else {
// column is not part of expected columns so it has to be removed
$table->dropColumn($column->getName());
}
$processed[] = $column->getName();
}
foreach ($expectedColumns as $columnName => $options) {
if (!\in_array($columnName, $processed, true)) {
// expected column in not part of concrete ones so it's a new column, we need to add it
if (DoctrineHelper::getDoctrineType('JSON') === $options['type'] && $isJsonSupported) {
$type = DoctrineHelper::getDoctrineType('TEXT');
} else {
$type = $options['type'];
}
$table->addColumn($columnName, $options['type'], $options['options']);
}
}
}
/**
* @throws SchemaException
*/
private function processIndices(Table $table, array $expectedIndices, Connection $connection): void
{
foreach ($expectedIndices as $columnName => $options) {
if ('primary' === $options['type']) {
$table->dropPrimaryKey();
$table->setPrimaryKey([$columnName]);
} else {
if ($table->hasIndex($options['name'])) {
$table->dropIndex($options['name']);
}
$table->addIndex(
[$columnName],
$options['name'],
[],
PlatformHelper::isIndexLengthLimited($columnName, $connection) ? ['lengths' => [191]] : []
);
}
}
}
}