-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathMigrationHelper.php
More file actions
735 lines (651 loc) · 23.2 KB
/
MigrationHelper.php
File metadata and controls
735 lines (651 loc) · 23.2 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
<?php
declare(strict_types=1);
/**
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @license https://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Migrations\View\Helper;
use ArrayAccess;
use Cake\Core\Configure;
use Cake\Database\Connection;
use Cake\Database\Driver\Mysql;
use Cake\Database\Schema\CollectionInterface;
use Cake\Database\Schema\TableSchemaInterface;
use Cake\Utility\Hash;
use Cake\Utility\Inflector;
use Cake\View\Helper;
use Cake\View\View;
use Migrations\Db\Table\ForeignKey;
/**
* Migration Helper class for output of field data in migration files.
*
* MigrationHelper encloses all methods needed while working with HTML pages.
*/
class MigrationHelper extends Helper
{
/**
* Schemas list for tables analyzed during migration baking
*
* @var array<string, \Cake\Database\Schema\TableSchemaInterface>
*/
protected array $schemas = [];
/**
* Stores the status of the ``$this->table()`` statements issued while baking.
* It helps prevent duplicate calls in case of complex conditions
*
* @var array<bool>
*/
protected array $tableStatementStatus = [];
/**
* @var array<string, array<string, array<string>>>
*/
protected array $returnedData = [];
/**
* Store a table's column listing.
*
* @param string $table The table name
* @param string $columnsList The column list to store.
* @return void
*/
public function storeReturnedData(string $table, string $columnsList): void
{
$this->returnedData['dropForeignKeys'][$table][] = $columnsList;
}
/**
* Get all stored data.
*
* @return array An array of stored data.
*/
public function getReturnedData(): array
{
return $this->returnedData;
}
/**
* Constructor
*
* ### Settings
*
* - `collection` \Cake\Database\Schema\Collection
* - `connection` \Cake\Database\Connection
*
* @param \Cake\View\View $View The View this helper is being attached to.
* @param array $config Configuration settings for the helper.
*/
public function __construct(View $View, array $config = [])
{
parent::__construct($View, $config);
}
/**
* Returns the method to be used for the Table::save()
*
* @param string|null $action Name of action to take against the table
* @return string
*/
public function tableMethod(?string $action = null): string
{
if ($action === 'drop_table') {
return 'drop';
}
if ($action === 'create_table') {
return 'create';
}
return 'update';
}
/**
* Returns the method to be used for the index manipulation
*
* @param string|null $action Name of action to take against the table
* @return string
*/
public function indexMethod(?string $action = null): string
{
if ($action === 'drop_field') {
return 'removeIndex';
}
return 'addIndex';
}
/**
* Returns the method to be used for the column manipulation
*
* @param string|null $action Name of action to take against the table
* @return string
*/
public function columnMethod(?string $action = null): string
{
if ($action === 'drop_field') {
return 'removeColumn';
}
if ($action === 'alter_field') {
return 'changeColumn';
}
return 'addColumn';
}
/**
* Returns the Cake\Database\Schema\TableSchemaInterface for $table
*
* @param string $table Name of the table to retrieve constraints for.
* @return \Cake\Database\Schema\TableSchemaInterface
*/
protected function schema(string $table): TableSchemaInterface
{
if (isset($this->schemas[$table])) {
return $this->schemas[$table];
}
$collection = $this->getConfig('collection');
assert($collection instanceof CollectionInterface);
$schema = $collection->describe($table);
$this->schemas[$table] = $schema;
return $schema;
}
/**
* Returns an array of column data for a given table
*
* @param \Cake\Database\Schema\TableSchemaInterface|string $table Name of the table to retrieve constraints for
* or a table schema object.
* @return array<string, array>
*/
public function columns(TableSchemaInterface|string $table): array
{
$tableSchema = $table;
if (!($tableSchema instanceof TableSchemaInterface)) {
$tableSchema = $this->schema($tableSchema);
}
$columns = [];
$tablePrimaryKeys = $tableSchema->getPrimaryKey();
foreach ($tableSchema->columns() as $column) {
if (in_array($column, $tablePrimaryKeys, true)) {
continue;
}
$columns[$column] = $this->column($tableSchema, $column);
}
return $columns;
}
/**
* Returns an array of indexes for a given table
*
* @param \Cake\Database\Schema\TableSchemaInterface|string $table Name of the table to retrieve constraints for
* or a table schema object.
* @return array<string, array<string, mixed>|null>
*/
public function indexes(TableSchemaInterface|string $table): array
{
$tableSchema = $table;
if (!($tableSchema instanceof TableSchemaInterface)) {
$tableSchema = $this->schema($tableSchema);
}
$tableIndexes = $tableSchema->indexes();
$indexes = [];
if ($tableIndexes) {
foreach ($tableIndexes as $name) {
$indexes[$name] = $tableSchema->getIndex($name);
}
}
return $indexes;
}
/**
* Returns an array of constraints for a given table
*
* @param \Cake\Database\Schema\TableSchemaInterface|string $table Name of the table to retrieve constraints for
* or a table schema object.
* @return array<string, array<string, mixed>|null>
*/
public function constraints(TableSchemaInterface|string $table): array
{
$tableSchema = $table;
if (!($tableSchema instanceof TableSchemaInterface)) {
$tableSchema = $this->schema($tableSchema);
}
$constraints = [];
$tableConstraints = $tableSchema->constraints();
if (!$tableConstraints) {
return $constraints;
}
if ($tableConstraints[0] === 'primary') {
unset($tableConstraints[0]);
}
foreach ($tableConstraints as $name) {
$constraint = $tableSchema->getConstraint($name);
if (!$constraint) {
continue;
}
if ($constraint['type'] === 'primary') {
continue;
}
if (isset($constraint['update'])) {
$constraint['update'] = $this->formatConstraintAction($constraint['update']);
}
if (isset($constraint['delete'])) {
$constraint['delete'] = $this->formatConstraintAction($constraint['delete']);
}
$constraints[$name] = $constraint;
}
return $constraints;
}
/**
* Format a constraint action if it is not already in the format expected by migrations
*
* @param string $constraint Constraint action name
* @return string Constraint action name altered if needed.
*/
public function formatConstraintAction(string $constraint): string
{
if (defined(ForeignKey::class . '::' . $constraint)) {
return $constraint;
}
return strtoupper(Inflector::underscore($constraint));
}
/**
* Returns the primary key data for a given table
*
* @param \Cake\Database\Schema\TableSchemaInterface|string $table Name of the table ot retrieve primary key for
* @return array<array>
*/
public function primaryKeys(TableSchemaInterface|string $table): array
{
$tableSchema = $table;
if (!($tableSchema instanceof TableSchemaInterface)) {
$tableSchema = $this->schema($tableSchema);
}
$primaryKeys = [];
$tablePrimaryKeys = $tableSchema->getPrimaryKey();
foreach ($tableSchema->columns() as $column) {
if (in_array($column, $tablePrimaryKeys, true)) {
$primaryKeys[] = ['name' => $column, 'info' => $this->column($tableSchema, $column)];
}
}
return $primaryKeys;
}
/**
* Returns whether any of the given tables/schemas contains a primary key
* that is incompatible with automatically generated primary keys for the
* current driver.
*
* @param array<\Cake\Database\Schema\TableSchemaInterface|string> $tables List of schemas/tables to check
* @return bool
*/
public function hasAutoIdIncompatiblePrimaryKey(array $tables): bool
{
$connection = $this->getConfig('connection');
assert($connection instanceof Connection);
// currently only MySQL supports unsigned primary keys
if (!($connection->getDriver() instanceof Mysql)) {
return false;
}
$useUnsignedPrimaryKes = (bool)Configure::read('Migrations.unsigned_primary_keys');
foreach ($tables as $table) {
$schema = $table;
if (!($schema instanceof TableSchemaInterface)) {
$schema = $this->schema($schema);
}
foreach ($schema->getPrimaryKey() as $column) {
$data = $schema->getColumn($column);
if (isset($data['unsigned']) && $data['unsigned'] === !$useUnsignedPrimaryKes) {
return true;
}
}
}
return false;
}
/**
* Returns the primary key columns name for a given table
*
* @param \Cake\Database\Schema\TableSchemaInterface|string $table Name of the table ot retrieve primary key for
* @return array<string>
*/
public function primaryKeysColumnsList(TableSchemaInterface|string $table): array
{
$primaryKeys = $this->primaryKeys($table);
/** @var array $primaryKeysColumns */
$primaryKeysColumns = Hash::extract($primaryKeys, '{n}.name');
sort($primaryKeysColumns);
return $primaryKeysColumns;
}
/**
* Returns an array of column data for a single column
*
* @param \Cake\Database\Schema\TableSchemaInterface $tableSchema Name of the table to retrieve columns for
* @param string $column A column to retrieve data for
* @return array<string, string|array<string, mixed>|null>
*/
public function column(TableSchemaInterface $tableSchema, string $column): array
{
$columnType = $tableSchema->getColumnType($column);
return [
'columnType' => $columnType,
'options' => $this->attributes($tableSchema, $column),
];
}
/**
* Compute the final array of options to display in a `addColumn` or `changeColumn` instruction.
* The method also takes care of translating properties names between CakePHP database layer and phinx database
* layer.
*
* @param array<string, mixed> $options Array of options to compute the final list from.
* @return array<string, mixed>
*/
public function getColumnOption(array $options): array
{
$connection = $this->getConfig('connection');
assert($connection instanceof Connection);
$wantedOptions = array_flip([
'length',
'limit',
'default',
'signed',
'null',
'comment',
'autoIncrement',
'precision',
'scale',
'after',
'collate',
]);
$columnOptions = array_intersect_key($options, $wantedOptions);
if (empty($columnOptions['comment'])) {
unset($columnOptions['comment']);
}
if (empty($columnOptions['autoIncrement'])) {
unset($columnOptions['autoIncrement']);
}
if (empty($columnOptions['collate'])) {
unset($columnOptions['collate']);
}
// currently only MySQL supports the signed option
$driver = $connection->getDriver();
$isMysql = $driver instanceof Mysql;
if (!$isMysql) {
unset($columnOptions['signed']);
} elseif (isset($columnOptions['signed']) && $columnOptions['signed'] === true) {
// Remove 'signed' => true since signed is the default for integer columns
// Only output explicit 'signed' => false for unsigned columns
unset($columnOptions['signed']);
}
if (!empty($columnOptions['collate'])) {
// Phinx uses 'collation' not 'collate'
$columnOptions['collation'] = $columnOptions['collate'];
unset($columnOptions['collate']);
}
// Handle precision/scale conversion between CakePHP's TableSchema format and SQL standard format.
// TableSchema uses: length=total digits, precision=decimal places
// Migrations uses SQL standard: precision=total digits, scale=decimal places
if (!isset($columnOptions['precision']) || $columnOptions['precision'] == null) {
unset($columnOptions['precision']);
} else {
// Convert CakePHP's precision (decimal places) to Migrations' scale
// Only convert if scale is not already set (for decimal columns from diff)
if (!isset($columnOptions['scale'])) {
$columnOptions['scale'] = $columnOptions['precision'];
}
if (isset($columnOptions['limit'])) {
$columnOptions['precision'] = $columnOptions['limit'];
unset($columnOptions['limit']);
}
if (isset($columnOptions['length'])) {
$columnOptions['precision'] = $columnOptions['length'];
unset($columnOptions['length']);
}
}
return $columnOptions;
}
/**
* Returns a string-like representation of a value
*
* @param string|float|int|bool|null $value A value to represent as a string
* @param bool $numbersAsString Set tu true to return as string.
* @return string|float
*/
public function value(string|float|int|bool|null $value, bool $numbersAsString = false): string|float
{
if ($value === null || $value === 'null' || $value === 'NULL') {
return 'null';
}
if ($value === 'true' || $value === 'false') {
return $value;
}
if (is_bool($value)) {
return $value ? 'true' : 'false';
}
if (!$numbersAsString && (is_numeric($value) || ctype_digit($value))) {
return (float)$value;
}
return sprintf("'%s'", addslashes((string)$value));
}
/**
* Returns an array of attributes for a given table column
*
* @param \Cake\Database\Schema\TableSchemaInterface|string $table Name of the table to retrieve columns for
* @param string $column A column to retrieve attributes for
* @return array<string, mixed>
*/
public function attributes(TableSchemaInterface|string $table, string $column): array
{
$connection = $this->getConfig('connection');
assert($connection instanceof Connection);
$tableSchema = $table;
if (!($tableSchema instanceof TableSchemaInterface)) {
$tableSchema = $this->schema($tableSchema);
}
$validOptions = [
'length', 'limit',
'default', 'null',
'precision', 'scale',
'after', 'update',
'comment', 'unsigned',
'signed', 'properties',
'autoIncrement', 'unique',
'collate',
];
$attributes = [];
$options = $tableSchema->getColumn($column);
if ($options === null) {
return [];
}
foreach ($options as $_option => $value) {
$option = $_option;
switch ($_option) {
case 'length':
$option = 'limit';
break;
case 'unsigned':
$option = 'signed';
$value = !$value;
break;
case 'unique':
$value = (bool)$value;
break;
}
if (!in_array($option, $validOptions, true)) {
continue;
}
if ($option === 'default' && is_string($value)) {
$value = trim($value, "'");
}
$attributes[$option] = $value;
}
// currently only MySQL supports the signed option
$isMysql = $connection->getDriver() instanceof Mysql;
if (!$isMysql) {
unset($attributes['signed']);
} elseif (isset($attributes['signed']) && $attributes['signed'] === true) {
// Remove 'signed' => true since signed is now the default for integer columns
// Only output explicit 'signed' => false for unsigned columns
unset($attributes['signed']);
}
$defaultCollation = $tableSchema->getOptions()['collation'] ?? null;
if (empty($attributes['collate']) || $attributes['collate'] == $defaultCollation) {
unset($attributes['collate']);
}
ksort($attributes);
return $attributes;
}
/**
* Returns an array converted into a formatted multiline string
*
* @param array $list array of items to be stringified
* @param array<string, mixed> $options options to use
* @param array<string, mixed> $wantedOptions The options you want to include in the output. If undefined all keys are included.
* @return string
*/
public function stringifyList(array $list, array $options = [], array $wantedOptions = []): string
{
if ($wantedOptions) {
$list = array_intersect_key($list, $wantedOptions);
if (empty($list['comment'])) {
unset($list['comment']);
}
}
$options += [
'indent' => 2,
];
if (!empty($options['remove'])) {
foreach ($options['remove'] as $option) {
unset($list[$option]);
}
unset($options['remove']);
}
if (!$list) {
return '';
}
ksort($list);
foreach ($list as $k => &$v) {
if (is_array($v)) {
$v = $this->stringifyList($v, [
'indent' => $options['indent'] + 1,
]);
$v = sprintf('[%s]', $v);
} else {
$v = $this->value($v, $k === 'default');
}
if (!is_numeric($k)) {
$v = "'$k' => $v";
}
}
$start = $end = '';
$join = ', ';
if ($options['indent']) {
$join = ',';
$start = "\n" . str_repeat(' ', $options['indent']);
$join .= $start;
$end = "\n" . str_repeat(' ', $options['indent'] - 1);
}
return $start . implode($join, $list) . ',' . $end;
}
/**
* Returns a $this->table() statement only if it was not issued already
*
* @param string $table Table for which the statement is needed
* @param bool $reset Reset previously set statement.
* @return string
*/
public function tableStatement(string $table, bool $reset = false): string
{
if ($reset === true) {
unset($this->tableStatementStatus[$table]);
}
if (!isset($this->tableStatementStatus[$table])) {
$this->tableStatementStatus[$table] = true;
return '$this->table(\'' . addslashes($table) . '\')';
}
return '';
}
/**
* Checks whether a table statement was generated for the given table name.
*
* @param string $table The table's name for which to check the status for.
* @return bool
* @see tableStatement()
*/
public function wasTableStatementGeneratedFor(string $table): bool
{
return isset($this->tableStatementStatus[$table]);
}
/**
* Resets the table statement generation status for the given table name.
*
* @param string $table The table's name for which to reset the status.
* @return void
* @see tableStatement()
*/
public function resetTableStatementGenerationFor(string $table): void
{
unset($this->tableStatementStatus[$table]);
}
/**
* Render an element.
*
* @param string $name The name of the element to render.
* @param array<string, mixed> $data Additional data for the element.
* @return ?string
*/
public function element(string $name, array $data): ?string
{
return $this->getView()->element($name, $data);
}
/**
* Wrapper around Hash::extract()
*
* @param \ArrayAccess|array $list The data to extract from.
* @param string $path The path to extract.
* @return \ArrayAccess|array
*/
public function extract(ArrayAccess|array $list, string $path = '{n}.name'): ArrayAccess|array
{
return Hash::extract($list, $path);
}
/**
* Get data to use in create tables element
*
* @param \Cake\Database\Schema\TableSchemaInterface|string $table Name of the table to retrieve constraints for
* or a table schema object.
* @return array<string, mixed>
*/
public function getCreateTableData(TableSchemaInterface|string $table): array
{
$constraints = $this->constraints($table);
$indexes = $this->indexes($table);
$foreignKeys = [];
foreach ($constraints as $constraint) {
if ($constraint['type'] === 'foreign') {
$foreignKeys[] = $constraint['columns'];
}
}
return compact('constraints', 'indexes', 'foreignKeys');
}
/**
* Get data to use inside the create-tables element
*
* @param array<\Cake\Database\Schema\TableSchemaInterface|string> $tables The tables to create element data for.
* @return array<string, mixed>
*/
public function getCreateTablesElementData(array $tables): array
{
$result = [
'constraints' => [],
'tables' => [],
];
foreach ($tables as $table) {
$tableName = $table;
if ($table instanceof TableSchemaInterface) {
$tableName = $table->name();
}
$data = $this->getCreateTableData($table);
$tableConstraintsNoUnique = array_filter(
$data['constraints'],
function ($constraint) {
return $constraint['type'] !== 'unique';
},
);
if ($tableConstraintsNoUnique) {
$result['constraints'][$tableName] = $data['constraints'];
}
$result['tables'][$tableName] = $data;
}
return $result;
}
}