-
Notifications
You must be signed in to change notification settings - Fork 148
Expand file tree
/
Copy pathDatabaseTableChangeProcessor.class.php
More file actions
1360 lines (1201 loc) · 52.1 KB
/
DatabaseTableChangeProcessor.class.php
File metadata and controls
1360 lines (1201 loc) · 52.1 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
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace wcf\system\database\table;
use wcf\data\package\Package;
use wcf\system\application\ApplicationHandler;
use wcf\system\database\editor\DatabaseEditor;
use wcf\system\database\table\column\AbstractIntDatabaseTableColumn;
use wcf\system\database\table\column\IDatabaseTableColumn;
use wcf\system\database\table\column\IDefaultValueDatabaseTableColumn;
use wcf\system\database\table\column\TinyintDatabaseTableColumn;
use wcf\system\database\table\column\YearDatabaseTableColumn;
use wcf\system\database\table\index\DatabaseTableForeignKey;
use wcf\system\database\table\index\DatabaseTableIndex;
use wcf\system\database\util\PreparedStatementConditionBuilder;
use wcf\system\package\SplitNodeException;
use wcf\system\WCF;
/**
* Processes a given set of changes to database tables.
*
* @author Matthias Schmidt
* @copyright 2001-2020 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @since 5.2
*/
final class DatabaseTableChangeProcessor
{
/**
* maps the registered database table column names to the ids of the packages they belong to
* @var int[][]
*/
private array $columnPackageIDs = [];
/**
* database table columns that will be added grouped by the name of the table to which they
* will be added
* @var IDatabaseTableColumn[][]
*/
private array $columnsToAdd = [];
/**
* database table columns that will be altered grouped by the name of the table to which
* they belong
* @var IDatabaseTableColumn[][]
*/
private array $columnsToAlter = [];
/**
* database table columns that will be dropped grouped by the name of the table from which
* they will be dropped
* @var IDatabaseTableColumn[][]
*/
private array $columnsToDrop = [];
/**
* database editor to apply the relevant changes to the table layouts
*/
private DatabaseEditor $dbEditor;
/**
* list of all existing tables in the used database
* @var string[]
*/
private array $existingTableNames = [];
/**
* existing database tables
* @var DatabaseTable[]
*/
private array $existingTables = [];
/**
* maps the registered database table index names to the ids of the packages they belong to
* @var int[][]
*/
private array $indexPackageIDs = [];
/**
* indices that will be added grouped by the name of the table to which they will be added
* @var DatabaseTableIndex[][]
*/
private array $indicesToAdd = [];
/**
* indices that will be dropped grouped by the name of the table from which they will be dropped
* @var DatabaseTableIndex[][]
*/
private array $indicesToDrop = [];
/**
* maps the registered database table foreign key names to the ids of the packages they belong to
* @var int[][]
*/
private array $foreignKeyPackageIDs = [];
/**
* foreign keys that will be added grouped by the name of the table to which they will be
* added
* @var DatabaseTableForeignKey[][]
*/
private array $foreignKeysToAdd = [];
/**
* foreign keys that will be dropped grouped by the name of the table from which they will
* be dropped
* @var DatabaseTableForeignKey[][]
*/
private array $foreignKeysToDrop = [];
/**
* package that wants to apply the changes
*/
private Package $package;
/**
* message for the split node exception thrown after the changes have been applied
*/
private string $splitNodeMessage = '';
/**
* layouts/layout changes of the relevant database table
* @var DatabaseTable[]
*/
private array $tables;
/**
* maps the registered database table names to the ids of the packages they belong to
* @var int[]
*/
private array $tablePackageIDs = [];
/**
* database table that will be created
* @var DatabaseTable[]
*/
private array $tablesToCreate = [];
/**
* database tables that will be dropped
* @var DatabaseTable[]
*/
private array $tablesToDrop = [];
/**
* database tables, that are unknown (but belongs theoretically to the WoltLab Suite)
* and must be dropped before installation
* @var DatabaseTable[]
* @since 5.5
*/
private array $tablesToCleanup = [];
/**
* Creates a new instance of `DatabaseTableChangeProcessor`.
*
* @param DatabaseTable[] $tables
*/
public function __construct(Package $package, array $tables, DatabaseEditor $dbEditor)
{
$this->package = $package;
$tableNames = [];
foreach ($tables as $table) {
if (!($table instanceof DatabaseTable)) {
throw new \InvalidArgumentException("Tables must be instance of '" . DatabaseTable::class . "'");
}
$tableNames[] = $table->getName();
}
$this->tables = $tables;
$this->dbEditor = $dbEditor;
$this->existingTableNames = $dbEditor->getTableNames();
$conditionBuilder = new PreparedStatementConditionBuilder();
$conditionBuilder->add('sqlTable IN (?)', [$tableNames]);
$conditionBuilder->add('isDone = ?', [1]);
$sql = "SELECT *
FROM wcf1_package_installation_sql_log
{$conditionBuilder}";
$statement = WCF::getDB()->prepare($sql);
$statement->execute($conditionBuilder->getParameters());
while ($row = $statement->fetchArray()) {
if ($row['sqlIndex'] === '' && $row['sqlColumn'] === '') {
$this->tablePackageIDs[$row['sqlTable']] = $row['packageID'];
} elseif ($row['sqlIndex'] === '') {
$this->columnPackageIDs[$row['sqlTable']][$row['sqlColumn']] = $row['packageID'];
} elseif (\substr($row['sqlIndex'], -3) === '_fk') {
$this->foreignKeyPackageIDs[$row['sqlTable']][$row['sqlIndex']] = $row['packageID'];
} else {
$this->indexPackageIDs[$row['sqlTable']][$row['sqlIndex']] = $row['packageID'];
}
}
}
/**
* Adds the given index to the table.
*/
private function addForeignKey(string $tableName, DatabaseTableForeignKey $foreignKey): void
{
$this->dbEditor->addForeignKey($tableName, $foreignKey->getName(), $foreignKey->getData());
}
/**
* Adds the given index to the table.
*/
private function addIndex(string $tableName, DatabaseTableIndex $index): void
{
$this->dbEditor->addIndex($tableName, $index->getName(), $index->getData());
}
/**
* Applies all of the previously determined changes to achieve the desired database layout.
*
* @throws SplitNodeException if any change has been applied
*/
private function applyChanges(): void
{
$appliedAnyChange = false;
foreach ($this->tablesToCleanup as $table) {
$this->dropTable($table);
}
foreach ($this->tablesToCreate as $table) {
$appliedAnyChange = true;
$this->prepareTableLog($table);
$this->createTable($table);
$this->finalizeTableLog($table);
}
foreach ($this->tablesToDrop as $table) {
$appliedAnyChange = true;
$this->dropTable($table);
$this->deleteTableLog($table);
}
$columnTables = \array_unique(\array_merge(
\array_keys($this->columnsToAdd),
\array_keys($this->columnsToAlter),
\array_keys($this->columnsToDrop)
));
foreach ($columnTables as $tableName) {
$appliedAnyChange = true;
$columnsToAdd = $this->columnsToAdd[$tableName] ?? [];
$columnsToAlter = $this->columnsToAlter[$tableName] ?? [];
$columnsToDrop = $this->columnsToDrop[$tableName] ?? [];
foreach ($columnsToAdd as $column) {
$this->prepareColumnLog($tableName, $column);
}
$renamedColumnsWithLog = [];
foreach ($columnsToAlter as $column) {
if ($column->getNewName() && $this->getColumnLog($tableName, $column) !== null) {
$this->prepareColumnLog($tableName, $column, true);
$renamedColumnsWithLog[] = $column;
}
}
$this->applyColumnChanges(
$tableName,
$columnsToAdd,
$columnsToAlter,
$columnsToDrop
);
foreach ($columnsToAdd as $column) {
$this->finalizeColumnLog($tableName, $column);
}
foreach ($renamedColumnsWithLog as $column) {
$this->finalizeColumnLog($tableName, $column, true);
$this->deleteColumnLog($tableName, $column);
}
foreach ($columnsToDrop as $column) {
$this->deleteColumnLog($tableName, $column);
}
}
foreach ($this->foreignKeysToDrop as $tableName => $foreignKeys) {
foreach ($foreignKeys as $foreignKey) {
$appliedAnyChange = true;
$this->dropForeignKey($tableName, $foreignKey);
$this->deleteForeignKeyLog($tableName, $foreignKey);
}
}
foreach ($this->foreignKeysToAdd as $tableName => $foreignKeys) {
foreach ($foreignKeys as $foreignKey) {
$appliedAnyChange = true;
$this->prepareForeignKeyLog($tableName, $foreignKey);
$this->addForeignKey($tableName, $foreignKey);
$this->finalizeForeignKeyLog($tableName, $foreignKey);
}
}
foreach ($this->indicesToDrop as $tableName => $indices) {
foreach ($indices as $index) {
$appliedAnyChange = true;
$this->dropIndex($tableName, $index);
$this->deleteIndexLog($tableName, $index);
}
}
foreach ($this->indicesToAdd as $tableName => $indices) {
foreach ($indices as $index) {
$appliedAnyChange = true;
$this->prepareIndexLog($tableName, $index);
$this->addIndex($tableName, $index);
$this->finalizeIndexLog($tableName, $index);
}
}
if ($appliedAnyChange) {
throw new SplitNodeException($this->splitNodeMessage);
}
}
/**
* Adds, alters, and drop columns of the same table.
*
* Before a column is dropped, all of its foreign keys are dropped.
*
* @param IDatabaseTableColumn[] $addedColumns
* @param IDatabaseTableColumn[] $alteredColumns
* @param IDatabaseTableColumn[] $droppedColumns
*/
private function applyColumnChanges(
string $tableName,
array $addedColumns,
array $alteredColumns,
array $droppedColumns
): void {
$dropForeignKeys = [];
$columnData = [];
foreach ($droppedColumns as $droppedColumn) {
$columnData[$droppedColumn->getName()] = [
'action' => 'drop',
];
foreach ($this->getExistingTable($tableName)->getForeignKeys() as $foreignKey) {
if (\in_array($droppedColumn->getName(), $foreignKey->getColumns())) {
$dropForeignKeys[] = $foreignKey;
}
}
}
foreach ($addedColumns as $addedColumn) {
$columnData[$addedColumn->getName()] = [
'action' => 'add',
'data' => $addedColumn->getData(),
];
}
foreach ($alteredColumns as $alteredColumn) {
$columnData[$alteredColumn->getName()] = [
'action' => 'alter',
'data' => $alteredColumn->getData(),
'newColumnName' => $alteredColumn->getNewName() ?? $alteredColumn->getName(),
];
}
if ($columnData !== []) {
foreach ($dropForeignKeys as $foreignKey) {
$this->dropForeignKey($tableName, $foreignKey);
$this->deleteForeignKeyLog($tableName, $foreignKey);
}
$this->dbEditor->alterColumns($tableName, $columnData);
}
}
/**
* Calculates all of the necessary changes to be executed.
*/
private function calculateChanges(): void
{
foreach ($this->tables as $table) {
$tableName = $table->getName();
if ($table->willBeDropped()) {
if (\in_array($tableName, $this->existingTableNames)) {
$this->tablesToDrop[] = $table;
$this->splitNodeMessage .= "Dropped table '{$tableName}'.";
break;
} elseif (isset($this->tablePackageIDs[$tableName])) {
$this->deleteTableLog($table);
}
} elseif (
\in_array($tableName, $this->existingTableNames)
&& !isset($this->tablePackageIDs[$table->getName()])
) {
if ($table instanceof PartialDatabaseTable) {
throw new \LogicException("Partial table '{$tableName}' cannot be created (table exists but is unknown).");
}
// The table is currently unknown to the system and should be removed,
// before it will be created again. This protect us from havely outdated
// tables.
$this->tablesToCleanup[] = $table;
$this->splitNodeMessage .= "Clean up table '{$tableName}'.";
$this->tablesToCreate[] = $table;
$this->splitNodeMessage .= "Created table '{$tableName}'.";
} elseif (!\in_array($tableName, $this->existingTableNames)) {
if ($table instanceof PartialDatabaseTable) {
throw new \LogicException("Partial table '{$tableName}' cannot be created.");
}
$this->tablesToCreate[] = $table;
$this->splitNodeMessage .= "Created table '{$tableName}'.";
break;
} else {
// calculate difference between tables
$existingTable = $this->getExistingTable($tableName);
$existingColumns = $existingTable->getColumns();
foreach ($table->getColumns() as $column) {
if ($column->willBeDropped()) {
if (isset($existingColumns[$column->getName()])) {
if (!isset($this->columnsToDrop[$tableName])) {
$this->columnsToDrop[$tableName] = [];
}
$this->columnsToDrop[$tableName][] = $column;
} elseif (isset($this->columnPackageIDs[$tableName][$column->getName()])) {
$this->deleteColumnLog($tableName, $column);
}
} elseif (!isset($existingColumns[$column->getName()])) {
// It was already checked in `validate()` that for renames, the column either
// exists with the old or new name.
if (!$column->getNewName()) {
if (!isset($this->columnsToAdd[$tableName])) {
$this->columnsToAdd[$tableName] = [];
}
$this->columnsToAdd[$tableName][] = $column;
}
} elseif ($this->diffColumns($existingColumns[$column->getName()], $column)) {
if (!isset($this->columnsToAlter[$tableName])) {
$this->columnsToAlter[$tableName] = [];
}
$this->columnsToAlter[$tableName][] = $column;
}
}
// all column-related changes are executed in one query thus break
// here and not within the previous loop
if ($this->columnsToAdd !== [] || $this->columnsToAlter !== [] || $this->columnsToDrop !== []) {
$this->splitNodeMessage .= "Altered columns of table '{$tableName}'.";
break;
}
$existingForeignKeys = $existingTable->getForeignKeys();
foreach ($table->getForeignKeys() as $foreignKey) {
$matchingExistingForeignKey = null;
foreach ($existingForeignKeys as $existingForeignKey) {
if (\array_diff_assoc($foreignKey->getDiffData(), $existingForeignKey->getDiffData()) === []) {
$matchingExistingForeignKey = $existingForeignKey;
break;
}
}
if ($foreignKey->willBeDropped()) {
if ($matchingExistingForeignKey !== null) {
if (!isset($this->foreignKeysToDrop[$tableName])) {
$this->foreignKeysToDrop[$tableName] = [];
}
$this->foreignKeysToDrop[$tableName][] = $matchingExistingForeignKey;
$this->splitNodeMessage .= "Dropped foreign key '{$tableName}." . \implode(
',',
$foreignKey->getColumns()
) . "'.";
break 2;
} elseif (isset($this->foreignKeyPackageIDs[$tableName][$foreignKey->getName()])) {
$this->deleteForeignKeyLog($tableName, $foreignKey);
}
} elseif ($matchingExistingForeignKey === null) {
// If the referenced database table does not already exists, delay the
// foreign key creation until after the referenced table has been created.
if (!\in_array($foreignKey->getReferencedTable(), $this->existingTableNames)) {
continue;
}
if (!isset($this->foreignKeysToAdd[$tableName])) {
$this->foreignKeysToAdd[$tableName] = [];
}
$this->foreignKeysToAdd[$tableName][] = $foreignKey;
$this->splitNodeMessage .= "Added foreign key '{$tableName}." . \implode(
',',
$foreignKey->getColumns()
) . "'.";
break 2;
} elseif (\array_diff_assoc($foreignKey->getData(), $matchingExistingForeignKey->getData()) !== []) {
if (!isset($this->foreignKeysToDrop[$tableName])) {
$this->foreignKeysToDrop[$tableName] = [];
}
$this->foreignKeysToDrop[$tableName][] = $matchingExistingForeignKey;
if (!isset($this->foreignKeysToAdd[$tableName])) {
$this->foreignKeysToAdd[$tableName] = [];
}
$this->foreignKeysToAdd[$tableName][] = $foreignKey;
$this->splitNodeMessage .= "Replaced foreign key '{$tableName}." . \implode(
',',
$foreignKey->getColumns()
) . "'.";
break 2;
}
}
$existingIndices = $existingTable->getIndices();
foreach ($table->getIndices() as $index) {
$matchingExistingIndex = null;
foreach ($existingIndices as $existingIndex) {
if (!$this->diffIndices($existingIndex, $index)) {
$matchingExistingIndex = $existingIndex;
break;
}
}
if ($index->willBeDropped()) {
if ($matchingExistingIndex !== null) {
if (!isset($this->indicesToDrop[$tableName])) {
$this->indicesToDrop[$tableName] = [];
}
$this->indicesToDrop[$tableName][] = $matchingExistingIndex;
$this->splitNodeMessage .= "Dropped index '{$tableName}." . \implode(
',',
$index->getColumns()
) . "'.";
break 2;
} elseif (isset($this->indexPackageIDs[$tableName][$index->getName()])) {
$this->deleteIndexLog($tableName, $index);
}
} elseif ($matchingExistingIndex !== null) {
// updating index type and index columns is supported with an
// explicit index name is given (automatically generated index
// names are not deterministic)
if (
!$index->hasGeneratedName()
&& \array_diff_assoc($matchingExistingIndex->getData(), $index->getData()) !== []
) {
if (!isset($this->indicesToDrop[$tableName])) {
$this->indicesToDrop[$tableName] = [];
}
$this->indicesToDrop[$tableName][] = $matchingExistingIndex;
if (!isset($this->indicesToAdd[$tableName])) {
$this->indicesToAdd[$tableName] = [];
}
$this->indicesToAdd[$tableName][] = $index;
}
} else {
if (!isset($this->indicesToAdd[$tableName])) {
$this->indicesToAdd[$tableName] = [];
}
$this->indicesToAdd[$tableName][] = $index;
$this->splitNodeMessage .= "Added index '{$tableName}." . \implode(
',',
$index->getColumns()
) . "'.";
break 2;
}
}
}
}
}
/**
* Checks for any pending log entries for the package and either marks them as done or
* deletes them so that after this method finishes, there are no more undone log entries
* for the package.
*/
private function checkPendingLogEntries(): void
{
$sql = "SELECT *
FROM wcf1_package_installation_sql_log
WHERE packageID = ?
AND isDone = ?";
$statement = WCF::getDB()->prepare($sql);
$statement->execute([$this->package->packageID, 0]);
$doneEntries = $undoneEntries = [];
while ($row = $statement->fetchArray()) {
// table
if ($row['sqlIndex'] === '' && $row['sqlColumn'] === '') {
if (\in_array($row['sqlTable'], $this->existingTableNames)) {
$doneEntries[] = $row;
} else {
$undoneEntries[] = $row;
}
} // column
elseif ($row['sqlIndex'] === '') {
if (isset($this->getExistingTable($row['sqlTable'])->getColumns()[$row['sqlColumn']])) {
$doneEntries[] = $row;
} else {
$undoneEntries[] = $row;
}
} // foreign key
elseif (\substr($row['sqlIndex'], -3) === '_fk') {
if (isset($this->getExistingTable($row['sqlTable'])->getForeignKeys()[$row['sqlIndex']])) {
$doneEntries[] = $row;
} else {
$undoneEntries[] = $row;
}
} // index
else {
if (isset($this->getExistingTable($row['sqlTable'])->getIndices()[$row['sqlIndex']])) {
$doneEntries[] = $row;
} else {
$undoneEntries[] = $row;
}
}
}
WCF::getDB()->beginTransaction();
foreach ($doneEntries as $entry) {
$this->finalizeLog($entry);
}
// to achieve a consistent state, undone log entries will be deleted here even though
// they might be re-created later to ensure that after this method finishes, there are
// no more undone entries in the log for the relevant package
foreach ($undoneEntries as $entry) {
$this->deleteLog($entry);
}
WCF::getDB()->commitTransaction();
}
/**
* Creates a done log entry for the given foreign key.
*/
private function createForeignKeyLog(string $tableName, DatabaseTableForeignKey $foreignKey): void
{
$sql = "INSERT INTO wcf1_package_installation_sql_log
(packageID, sqlTable, sqlIndex, isDone)
VALUES (?, ?, ?, ?)";
$statement = WCF::getDB()->prepare($sql);
$statement->execute([
$this->package->packageID,
$tableName,
$foreignKey->getName(),
1,
]);
}
/**
* Creates the given table.
*/
private function createTable(DatabaseTable $table): void
{
$hasPrimaryKey = false;
$columnData = \array_map(static function (IDatabaseTableColumn $column) use (&$hasPrimaryKey) {
$data = $column->getData();
if (isset($data['key']) && $data['key'] === 'PRIMARY') {
$hasPrimaryKey = true;
}
return [
'data' => $data,
'name' => $column->getName(),
];
}, $table->getColumns());
$indexData = \array_map(static function (DatabaseTableIndex $index) {
return [
'data' => $index->getData(),
'name' => $index->getName(),
];
}, $table->getIndices());
// Auto columns are implicitly defined as the primary key by MySQL.
if ($hasPrimaryKey) {
$indexData = \array_filter($indexData, static function ($key) {
return $key !== 'PRIMARY';
}, \ARRAY_FILTER_USE_KEY);
}
$this->dbEditor->createTable($table->getName(), $columnData, $indexData);
foreach ($table->getForeignKeys() as $foreignKey) {
// Only try to create the foreign key if the referenced database table already exists.
// If it will be created later on, delay the foreign key creation until after the
// referenced table has been created.
if (
\in_array($foreignKey->getReferencedTable(), $this->existingTableNames)
|| $foreignKey->getReferencedTable() === $table->getName()
) {
$this->dbEditor->addForeignKey($table->getName(), $foreignKey->getName(), $foreignKey->getData());
// foreign keys need to be explicitly logged for proper uninstallation
$this->createForeignKeyLog($table->getName(), $foreignKey);
}
}
}
/**
* Deletes the log entry for the given column.
*/
private function deleteColumnLog(string $tableName, IDatabaseTableColumn $column): void
{
$this->deleteLog(['sqlTable' => $tableName, 'sqlColumn' => $column->getName()]);
}
/**
* Deletes the log entry for the given foreign key.
*/
private function deleteForeignKeyLog(string $tableName, DatabaseTableForeignKey $foreignKey): void
{
$this->deleteLog(['sqlTable' => $tableName, 'sqlIndex' => $foreignKey->getName()]);
}
/**
* Deletes the log entry for the given index.
*/
private function deleteIndexLog(string $tableName, DatabaseTableIndex $index): void
{
$this->deleteLog(['sqlTable' => $tableName, 'sqlIndex' => $index->getName()]);
}
/**
* Deletes a log entry.
*
* @param array{sqlTable: string, sqlColumn?: string, sqlIndex?: string} $data
*/
private function deleteLog(array $data): void
{
$sql = "DELETE FROM wcf1_package_installation_sql_log
WHERE packageID = ?
AND sqlTable = ?
AND sqlColumn = ?
AND sqlIndex = ?";
$statement = WCF::getDB()->prepare($sql);
$statement->execute([
$this->package->packageID,
$data['sqlTable'],
$data['sqlColumn'] ?? '',
$data['sqlIndex'] ?? '',
]);
}
/**
* Deletes all log entry related to the given table.
*/
private function deleteTableLog(DatabaseTable $table): void
{
$sql = "DELETE FROM wcf1_package_installation_sql_log
WHERE packageID = ?
AND sqlTable = ?";
$statement = WCF::getDB()->prepare($sql);
$statement->execute([
$this->package->packageID,
$table->getName(),
]);
}
/**
* Returns `true` if the two columns differ.
*/
private function diffColumns(IDatabaseTableColumn $oldColumn, IDatabaseTableColumn $newColumn): bool
{
$diff = \array_diff_assoc($oldColumn->getData(), $newColumn->getData());
if ($diff !== []) {
// see https://github.com/WoltLab/WCF/pull/3167
if (\array_key_exists('length', $diff)) {
if (
(
$oldColumn instanceof AbstractIntDatabaseTableColumn
&& (
!($oldColumn instanceof TinyintDatabaseTableColumn)
|| $oldColumn->getLength() != 1
)
)
|| $oldColumn instanceof YearDatabaseTableColumn
) {
unset($diff['length']);
}
}
if (isset($diff['type'])) {
// In MariaDB JSON is an alias for LONGTEXT COLLATE utf8mb4_bin
// introduced for compatibility reasons with MySQL's JSON data type.
if (
$oldColumn->getType() === 'longtext'
&& $newColumn->getType() === 'json'
&& \stripos(WCF::getDB()->getVersion(), 'MariaDB') !== false
) {
unset($diff['type']);
}
}
if ($diff !== []) {
return true;
}
}
if ($newColumn->getNewName()) {
return true;
}
if (
!($oldColumn instanceof IDefaultValueDatabaseTableColumn)
|| !($newColumn instanceof IDefaultValueDatabaseTableColumn)
) {
\assert(
($oldColumn instanceof IDefaultValueDatabaseTableColumn)
=== ($newColumn instanceof IDefaultValueDatabaseTableColumn),
"Default support must be identical, because different types have been rejected above."
);
return false;
}
// default type has to be checked explicitly for `null` to properly detect changing
// from no default value (`null`) and to an empty string as default value (and vice
// versa)
if ($oldColumn->getDefaultValue() === null || $newColumn->getDefaultValue() === null) {
return $oldColumn->getDefaultValue() !== $newColumn->getDefaultValue();
}
// for all other cases, use weak comparison so that `'1'` (from database) and `1`
// (from script PIP) match, for example
return $oldColumn->getDefaultValue() != $newColumn->getDefaultValue();
}
/**
* Returns `true` if the two indices differ.
*/
private function diffIndices(DatabaseTableIndex $oldIndex, DatabaseTableIndex $newIndex): bool
{
if ($newIndex->hasGeneratedName()) {
return \array_diff_assoc($oldIndex->getData(), $newIndex->getData()) !== [];
}
return $oldIndex->getName() !== $newIndex->getName();
}
/**
* Drops the given foreign key.
*/
private function dropForeignKey(string $tableName, DatabaseTableForeignKey $foreignKey): void
{
$this->dbEditor->dropForeignKey($tableName, $foreignKey->getName());
$this->dbEditor->dropIndex($tableName, $foreignKey->getName());
}
/**
* Drops the given index.
*/
private function dropIndex(string $tableName, DatabaseTableIndex $index): void
{
$this->dbEditor->dropIndex($tableName, $index->getName());
}
/**
* Drops the given table.
*/
private function dropTable(DatabaseTable $table): void
{
$this->dbEditor->dropTable($table->getName());
}
/**
* Finalizes the log entry for the creation of the given column.
*/
private function finalizeColumnLog(string $tableName, IDatabaseTableColumn $column, bool $useNewName = false): void
{
$this->finalizeLog([
'sqlTable' => $tableName,
'sqlColumn' => $useNewName ? $column->getNewName() : $column->getName(),
]);
}
/**
* Finalizes the log entry for adding the given index.
*/
private function finalizeForeignKeyLog(string $tableName, DatabaseTableForeignKey $foreignKey): void
{
$this->finalizeLog(['sqlTable' => $tableName, 'sqlIndex' => $foreignKey->getName()]);
}
/**
* Finalizes the log entry for adding the given index.
*/
private function finalizeIndexLog(string $tableName, DatabaseTableIndex $index): void
{
$this->finalizeLog(['sqlTable' => $tableName, 'sqlIndex' => $index->getName()]);
}
/**
* Finalizes a log entry after the relevant change has been executed.
*
* @param array{sqlTable: string, sqlColumn?: string, sqlIndex?: string} $data
*/
private function finalizeLog(array $data): void
{
$sql = "UPDATE wcf1_package_installation_sql_log
SET isDone = ?
WHERE packageID = ?
AND sqlTable = ?
AND sqlColumn = ?
AND sqlIndex = ?";
$statement = WCF::getDB()->prepare($sql);
$statement->execute([
1,
$this->package->packageID,
$data['sqlTable'],
$data['sqlColumn'] ?? '',
$data['sqlIndex'] ?? '',
]);
}
/**
* Finalizes the log entry for the creation of the given table.
*/
private function finalizeTableLog(DatabaseTable $table): void
{
$this->finalizeLog(['sqlTable' => $table->getName()]);
}
/**
* Returns the log entry for the given column or `null` if there is no explicit entry for
* this column.
*
* @return ?array{
* packageID: int,
* sqlTable: string,
* sqlColumn: string,
* sqlIndex: string,
* isDone: 0|1
* }
* @since 5.4
*/
private function getColumnLog(string $tableName, IDatabaseTableColumn $column): ?array
{
$sql = "SELECT *
FROM wcf1_package_installation_sql_log
WHERE packageID = ?
AND sqlTable = ?
AND sqlColumn = ?";
$statement = WCF::getDB()->prepare($sql);
$statement->execute([
$this->package->packageID,
$tableName,
$column->getName(),
]);
$row = $statement->fetchSingleRow();
if ($row === false) {
return null;
}
return $row;
}
/**
* Returns the id of the package to with the given column belongs to. If there is no specific
* log entry for the given column, the table log is checked and the relevant package id of
* the whole table is returned. If the package of the table is also unknown, `null` is returned.
*/
private function getColumnPackageID(DatabaseTable $table, IDatabaseTableColumn $column): ?int
{
if (isset($this->columnPackageIDs[$table->getName()][$column->getName()])) {
return $this->columnPackageIDs[$table->getName()][$column->getName()];
} elseif (isset($this->tablePackageIDs[$table->getName()])) {
return $this->tablePackageIDs[$table->getName()];
}
return null;
}
/**
* Returns the `DatabaseTable` object for the table with the given name.
*/
private function getExistingTable(string $tableName): DatabaseTable
{
if (!isset($this->existingTables[$tableName])) {
$this->existingTables[$tableName] = DatabaseTable::createFromExistingTable($this->dbEditor, $tableName);
}