-
Notifications
You must be signed in to change notification settings - Fork 895
/
MysqlAdapter.php
1486 lines (1302 loc) · 46.3 KB
/
MysqlAdapter.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
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
/**
* MIT License
* For full license information, please view the LICENSE file that was distributed with this source code.
*/
namespace Phinx\Db\Adapter;
use Cake\Database\Connection;
use Cake\Database\Driver\Mysql as MysqlDriver;
use InvalidArgumentException;
use PDO;
use Phinx\Db\Table\Column;
use Phinx\Db\Table\ForeignKey;
use Phinx\Db\Table\Index;
use Phinx\Db\Table\Table;
use Phinx\Db\Util\AlterInstructions;
use Phinx\Util\Literal;
use RuntimeException;
/**
* Phinx MySQL Adapter.
*
* @author Rob Morgan <robbym@gmail.com>
*/
class MysqlAdapter extends PdoAdapter
{
/**
* @var string[]
*/
protected static $specificColumnTypes = [
self::PHINX_TYPE_ENUM,
self::PHINX_TYPE_SET,
self::PHINX_TYPE_YEAR,
self::PHINX_TYPE_JSON,
self::PHINX_TYPE_BINARYUUID,
self::PHINX_TYPE_TINYBLOB,
self::PHINX_TYPE_MEDIUMBLOB,
self::PHINX_TYPE_LONGBLOB,
];
/**
* @var bool[]
*/
protected $signedColumnTypes = [
self::PHINX_TYPE_INTEGER => true,
self::PHINX_TYPE_TINY_INTEGER => true,
self::PHINX_TYPE_SMALL_INTEGER => true,
self::PHINX_TYPE_BIG_INTEGER => true,
self::PHINX_TYPE_FLOAT => true,
self::PHINX_TYPE_DECIMAL => true,
self::PHINX_TYPE_DOUBLE => true,
self::PHINX_TYPE_BOOLEAN => true,
];
public const TEXT_TINY = 255;
public const TEXT_SMALL = 255; /* deprecated, alias of TEXT_TINY */
public const TEXT_REGULAR = 65535;
public const TEXT_MEDIUM = 16777215;
public const TEXT_LONG = 4294967295;
// According to https://dev.mysql.com/doc/refman/5.0/en/blob.html BLOB sizes are the same as TEXT
public const BLOB_TINY = 255;
public const BLOB_SMALL = 255; /* deprecated, alias of BLOB_TINY */
public const BLOB_REGULAR = 65535;
public const BLOB_MEDIUM = 16777215;
public const BLOB_LONG = 4294967295;
public const INT_TINY = 255;
public const INT_SMALL = 65535;
public const INT_MEDIUM = 16777215;
public const INT_REGULAR = 4294967295;
public const INT_BIG = 18446744073709551615;
public const BIT = 64;
public const TYPE_YEAR = 'year';
public const FIRST = 'FIRST';
/**
* {@inheritDoc}
*
* @throws \RuntimeException
* @throws \InvalidArgumentException
* @return void
*/
public function connect()
{
if ($this->connection === null) {
if (!class_exists('PDO') || !in_array('mysql', PDO::getAvailableDrivers(), true)) {
// @codeCoverageIgnoreStart
throw new RuntimeException('You need to enable the PDO_Mysql extension for Phinx to run properly.');
// @codeCoverageIgnoreEnd
}
$options = $this->getOptions();
$dsn = 'mysql:';
if (!empty($options['unix_socket'])) {
// use socket connection
$dsn .= 'unix_socket=' . $options['unix_socket'];
} else {
// use network connection
$dsn .= 'host=' . $options['host'];
if (!empty($options['port'])) {
$dsn .= ';port=' . $options['port'];
}
}
$dsn .= ';dbname=' . $options['name'];
// charset support
if (!empty($options['charset'])) {
$dsn .= ';charset=' . $options['charset'];
}
$driverOptions = [];
// use custom data fetch mode
if (!empty($options['fetch_mode'])) {
$driverOptions[PDO::ATTR_DEFAULT_FETCH_MODE] = constant('\PDO::FETCH_' . strtoupper($options['fetch_mode']));
}
// support arbitrary \PDO::MYSQL_ATTR_* driver options and pass them to PDO
// http://php.net/manual/en/ref.pdo-mysql.php#pdo-mysql.constants
foreach ($options as $key => $option) {
if (strpos($key, 'mysql_attr_') === 0) {
$pdoConstant = '\PDO::' . strtoupper($key);
if (!defined($pdoConstant)) {
throw new \UnexpectedValueException('Invalid PDO attribute: ' . $key . ' (' . $pdoConstant . ')');
}
$driverOptions[constant($pdoConstant)] = $option;
}
}
$db = $this->createPdoConnection($dsn, $options['user'] ?? null, $options['pass'] ?? null, $driverOptions);
$this->setConnection($db);
}
}
/**
* @inheritDoc
*/
public function disconnect()
{
$this->connection = null;
}
/**
* @inheritDoc
*/
public function hasTransactions()
{
return true;
}
/**
* @inheritDoc
*/
public function beginTransaction()
{
$this->execute('START TRANSACTION');
}
/**
* @inheritDoc
*/
public function commitTransaction()
{
$this->execute('COMMIT');
}
/**
* @inheritDoc
*/
public function rollbackTransaction()
{
$this->execute('ROLLBACK');
}
/**
* @inheritDoc
*/
public function quoteTableName($tableName)
{
return str_replace('.', '`.`', $this->quoteColumnName($tableName));
}
/**
* @inheritDoc
*/
public function quoteColumnName($columnName)
{
return '`' . str_replace('`', '``', $columnName) . '`';
}
/**
* @inheritDoc
*/
public function hasTable($tableName)
{
if ($this->hasCreatedTable($tableName)) {
return true;
}
if (strpos($tableName, '.') !== false) {
[$schema, $table] = explode('.', $tableName);
$exists = $this->hasTableWithSchema($schema, $table);
// Only break here on success, because it is possible for table names to contain a dot.
if ($exists) {
return true;
}
}
$options = $this->getOptions();
return $this->hasTableWithSchema($options['name'], $tableName);
}
/**
* @param string $schema The table schema
* @param string $tableName The table name
* @return bool
*/
protected function hasTableWithSchema($schema, $tableName)
{
$result = $this->fetchRow(sprintf(
"SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = '%s'",
$schema,
$tableName
));
return !empty($result);
}
/**
* @inheritDoc
*/
public function createTable(Table $table, array $columns = [], array $indexes = [])
{
// This method is based on the MySQL docs here: http://dev.mysql.com/doc/refman/5.1/en/create-index.html
$defaultOptions = [
'engine' => 'InnoDB',
'collation' => 'utf8_general_ci',
];
$options = array_merge(
$defaultOptions,
array_intersect_key($this->getOptions(), $defaultOptions),
$table->getOptions()
);
// Add the default primary key
if (!isset($options['id']) || (isset($options['id']) && $options['id'] === true)) {
$options['id'] = 'id';
}
if (isset($options['id']) && is_string($options['id'])) {
// Handle id => "field_name" to support AUTO_INCREMENT
$column = new Column();
$column->setName($options['id'])
->setType('integer')
->setSigned($options['signed'] ?? true)
->setIdentity(true);
if (isset($options['limit'])) {
$column->setLimit($options['limit']);
}
array_unshift($columns, $column);
if (isset($options['primary_key']) && (array)$options['id'] !== (array)$options['primary_key']) {
throw new InvalidArgumentException('You cannot enable an auto incrementing ID field and a primary key');
}
$options['primary_key'] = $options['id'];
}
// open: process table options like collation etc
// process table engine (default to InnoDB)
$optionsStr = 'ENGINE = InnoDB';
if (isset($options['engine'])) {
$optionsStr = sprintf('ENGINE = %s', $options['engine']);
}
// process table collation
if (isset($options['collation'])) {
$charset = explode('_', $options['collation']);
$optionsStr .= sprintf(' CHARACTER SET %s', $charset[0]);
$optionsStr .= sprintf(' COLLATE %s', $options['collation']);
}
// set the table comment
if (isset($options['comment'])) {
$optionsStr .= sprintf(' COMMENT=%s ', $this->getConnection()->quote($options['comment']));
}
// set the table row format
if (isset($options['row_format'])) {
$optionsStr .= sprintf(' ROW_FORMAT=%s ', $options['row_format']);
}
$sql = 'CREATE TABLE ';
$sql .= $this->quoteTableName($table->getName()) . ' (';
foreach ($columns as $column) {
$sql .= $this->quoteColumnName($column->getName()) . ' ' . $this->getColumnSqlDefinition($column) . ', ';
}
// set the primary key(s)
if (isset($options['primary_key'])) {
$sql = rtrim($sql);
$sql .= ' PRIMARY KEY (';
if (is_string($options['primary_key'])) { // handle primary_key => 'id'
$sql .= $this->quoteColumnName($options['primary_key']);
} elseif (is_array($options['primary_key'])) { // handle primary_key => array('tag_id', 'resource_id')
$sql .= implode(',', array_map([$this, 'quoteColumnName'], $options['primary_key']));
}
$sql .= ')';
} else {
$sql = substr(rtrim($sql), 0, -1); // no primary keys
}
// set the indexes
foreach ($indexes as $index) {
$sql .= ', ' . $this->getIndexSqlDefinition($index);
}
$sql .= ') ' . $optionsStr;
$sql = rtrim($sql);
// execute the sql
$this->execute($sql);
$this->addCreatedTable($table->getName());
}
/**
* {@inheritDoc}
*
* @throws \InvalidArgumentException
*/
protected function getChangePrimaryKeyInstructions(Table $table, $newColumns)
{
$instructions = new AlterInstructions();
// Drop the existing primary key
$primaryKey = $this->getPrimaryKey($table->getName());
if (!empty($primaryKey['columns'])) {
$instructions->addAlter('DROP PRIMARY KEY');
}
// Add the primary key(s)
if (!empty($newColumns)) {
$sql = 'ADD PRIMARY KEY (';
if (is_string($newColumns)) { // handle primary_key => 'id'
$sql .= $this->quoteColumnName($newColumns);
} elseif (is_array($newColumns)) { // handle primary_key => array('tag_id', 'resource_id')
$sql .= implode(',', array_map([$this, 'quoteColumnName'], $newColumns));
} else {
throw new InvalidArgumentException(sprintf(
'Invalid value for primary key: %s',
json_encode($newColumns)
));
}
$sql .= ')';
$instructions->addAlter($sql);
}
return $instructions;
}
/**
* @inheritDoc
*/
protected function getChangeCommentInstructions(Table $table, $newComment)
{
$instructions = new AlterInstructions();
// passing 'null' is to remove table comment
$newComment = $newComment ?? '';
$sql = sprintf(' COMMENT=%s ', $this->getConnection()->quote($newComment));
$instructions->addAlter($sql);
return $instructions;
}
/**
* @inheritDoc
*/
protected function getRenameTableInstructions($tableName, $newTableName)
{
$this->updateCreatedTableName($tableName, $newTableName);
$sql = sprintf(
'RENAME TABLE %s TO %s',
$this->quoteTableName($tableName),
$this->quoteTableName($newTableName)
);
return new AlterInstructions([], [$sql]);
}
/**
* @inheritDoc
*/
protected function getDropTableInstructions($tableName)
{
$this->removeCreatedTable($tableName);
$sql = sprintf('DROP TABLE %s', $this->quoteTableName($tableName));
return new AlterInstructions([], [$sql]);
}
/**
* @inheritDoc
*/
public function truncateTable($tableName)
{
$sql = sprintf(
'TRUNCATE TABLE %s',
$this->quoteTableName($tableName)
);
$this->execute($sql);
}
/**
* @inheritDoc
*/
public function getColumns($tableName)
{
$columns = [];
$rows = $this->fetchAll(sprintf('SHOW COLUMNS FROM %s', $this->quoteTableName($tableName)));
foreach ($rows as $columnInfo) {
$phinxType = $this->getPhinxType($columnInfo['Type']);
$column = new Column();
$column->setName($columnInfo['Field'])
->setNull($columnInfo['Null'] !== 'NO')
->setDefault($columnInfo['Default'])
->setType($phinxType['name'])
->setSigned(strpos($columnInfo['Type'], 'unsigned') === false)
->setLimit($phinxType['limit'])
->setScale($phinxType['scale']);
if ($columnInfo['Extra'] === 'auto_increment') {
$column->setIdentity(true);
}
if (isset($phinxType['values'])) {
$column->setValues($phinxType['values']);
}
$columns[] = $column;
}
return $columns;
}
/**
* @inheritDoc
*/
public function hasColumn($tableName, $columnName)
{
$rows = $this->fetchAll(sprintf('SHOW COLUMNS FROM %s', $this->quoteTableName($tableName)));
foreach ($rows as $column) {
if (strcasecmp($column['Field'], $columnName) === 0) {
return true;
}
}
return false;
}
/**
* @inheritDoc
*/
protected function getAddColumnInstructions(Table $table, Column $column)
{
$alter = sprintf(
'ADD %s %s',
$this->quoteColumnName($column->getName()),
$this->getColumnSqlDefinition($column)
);
$alter .= $this->afterClause($column);
return new AlterInstructions([$alter]);
}
/**
* Exposes the MySQL syntax to arrange a column `FIRST`.
*
* @param \Phinx\Db\Table\Column $column The column being altered.
* @return string The appropriate SQL fragment.
*/
protected function afterClause(Column $column)
{
$after = $column->getAfter();
if (empty($after)) {
return '';
}
if ($after === self::FIRST) {
return ' FIRST';
}
return ' AFTER ' . $this->quoteColumnName($after);
}
/**
* {@inheritDoc}
*
* @throws \InvalidArgumentException
*/
protected function getRenameColumnInstructions($tableName, $columnName, $newColumnName)
{
$rows = $this->fetchAll(sprintf('SHOW FULL COLUMNS FROM %s', $this->quoteTableName($tableName)));
foreach ($rows as $row) {
if (strcasecmp($row['Field'], $columnName) === 0) {
$null = $row['Null'] === 'NO' ? 'NOT NULL' : 'NULL';
$comment = isset($row['Comment']) ? ' COMMENT ' . '\'' . addslashes($row['Comment']) . '\'' : '';
$extra = ' ' . strtoupper($row['Extra']);
if (($row['Default'] !== null)) {
$extra .= $this->getDefaultValueDefinition($row['Default']);
}
$definition = $row['Type'] . ' ' . $null . $extra . $comment;
$alter = sprintf(
'CHANGE COLUMN %s %s %s',
$this->quoteColumnName($columnName),
$this->quoteColumnName($newColumnName),
$definition
);
return new AlterInstructions([$alter]);
}
}
throw new InvalidArgumentException(sprintf(
"The specified column doesn't exist: " .
$columnName
));
}
/**
* @inheritDoc
*/
protected function getChangeColumnInstructions($tableName, $columnName, Column $newColumn)
{
$alter = sprintf(
'CHANGE %s %s %s%s',
$this->quoteColumnName($columnName),
$this->quoteColumnName($newColumn->getName()),
$this->getColumnSqlDefinition($newColumn),
$this->afterClause($newColumn)
);
return new AlterInstructions([$alter]);
}
/**
* @inheritDoc
*/
protected function getDropColumnInstructions($tableName, $columnName)
{
$alter = sprintf('DROP COLUMN %s', $this->quoteColumnName($columnName));
return new AlterInstructions([$alter]);
}
/**
* Get an array of indexes from a particular table.
*
* @param string $tableName Table name
* @return array
*/
protected function getIndexes($tableName)
{
$indexes = [];
$rows = $this->fetchAll(sprintf('SHOW INDEXES FROM %s', $this->quoteTableName($tableName)));
foreach ($rows as $row) {
if (!isset($indexes[$row['Key_name']])) {
$indexes[$row['Key_name']] = ['columns' => []];
}
$indexes[$row['Key_name']]['columns'][] = strtolower($row['Column_name']);
}
return $indexes;
}
/**
* @inheritDoc
*/
public function hasIndex($tableName, $columns)
{
if (is_string($columns)) {
$columns = [$columns]; // str to array
}
$columns = array_map('strtolower', $columns);
$indexes = $this->getIndexes($tableName);
foreach ($indexes as $index) {
if ($columns == $index['columns']) {
return true;
}
}
return false;
}
/**
* @inheritDoc
*/
public function hasIndexByName($tableName, $indexName)
{
$indexes = $this->getIndexes($tableName);
foreach ($indexes as $name => $index) {
if ($name === $indexName) {
return true;
}
}
return false;
}
/**
* @inheritDoc
*/
protected function getAddIndexInstructions(Table $table, Index $index)
{
$instructions = new AlterInstructions();
if ($index->getType() === Index::FULLTEXT) {
// Must be executed separately
// SQLSTATE[HY000]: General error: 1795 InnoDB presently supports one FULLTEXT index creation at a time
$alter = sprintf(
'ALTER TABLE %s ADD %s',
$this->quoteTableName($table->getName()),
$this->getIndexSqlDefinition($index)
);
$instructions->addPostStep($alter);
} else {
$alter = sprintf(
'ADD %s',
$this->getIndexSqlDefinition($index)
);
$instructions->addAlter($alter);
}
return $instructions;
}
/**
* {@inheritDoc}
*
* @throws \InvalidArgumentException
*/
protected function getDropIndexByColumnsInstructions($tableName, $columns)
{
if (is_string($columns)) {
$columns = [$columns]; // str to array
}
$indexes = $this->getIndexes($tableName);
$columns = array_map('strtolower', $columns);
foreach ($indexes as $indexName => $index) {
if ($columns == $index['columns']) {
return new AlterInstructions([sprintf(
'DROP INDEX %s',
$this->quoteColumnName($indexName)
)]);
}
}
throw new InvalidArgumentException(sprintf(
"The specified index on columns '%s' does not exist",
implode(',', $columns)
));
}
/**
* {@inheritDoc}
*
* @throws \InvalidArgumentException
*/
protected function getDropIndexByNameInstructions($tableName, $indexName)
{
$indexes = $this->getIndexes($tableName);
foreach ($indexes as $name => $index) {
if ($name === $indexName) {
return new AlterInstructions([sprintf(
'DROP INDEX %s',
$this->quoteColumnName($indexName)
)]);
}
}
throw new InvalidArgumentException(sprintf(
"The specified index name '%s' does not exist",
$indexName
));
}
/**
* @inheritDoc
*/
public function hasPrimaryKey($tableName, $columns, $constraint = null)
{
$primaryKey = $this->getPrimaryKey($tableName);
if (empty($primaryKey['constraint'])) {
return false;
}
if ($constraint) {
return $primaryKey['constraint'] === $constraint;
} else {
if (is_string($columns)) {
$columns = [$columns]; // str to array
}
$missingColumns = array_diff($columns, $primaryKey['columns']);
return empty($missingColumns);
}
}
/**
* Get the primary key from a particular table.
*
* @param string $tableName Table name
* @return array
*/
public function getPrimaryKey($tableName)
{
$options = $this->getOptions();
$rows = $this->fetchAll(sprintf(
"SELECT
k.CONSTRAINT_NAME,
k.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS t
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE k
USING(CONSTRAINT_NAME,TABLE_NAME)
WHERE t.CONSTRAINT_TYPE='PRIMARY KEY'
AND t.TABLE_SCHEMA='%s'
AND t.TABLE_NAME='%s'",
$options['name'],
$tableName
));
$primaryKey = [
'columns' => [],
];
foreach ($rows as $row) {
$primaryKey['constraint'] = $row['CONSTRAINT_NAME'];
$primaryKey['columns'][] = $row['COLUMN_NAME'];
}
return $primaryKey;
}
/**
* @inheritDoc
*/
public function hasForeignKey($tableName, $columns, $constraint = null)
{
if (is_string($columns)) {
$columns = [$columns]; // str to array
}
$foreignKeys = $this->getForeignKeys($tableName);
if ($constraint) {
if (isset($foreignKeys[$constraint])) {
return !empty($foreignKeys[$constraint]);
}
return false;
}
foreach ($foreignKeys as $key) {
if ($columns == $key['columns']) {
return true;
}
}
return false;
}
/**
* Get an array of foreign keys from a particular table.
*
* @param string $tableName Table name
* @return array
*/
protected function getForeignKeys($tableName)
{
if (strpos($tableName, '.') !== false) {
[$schema, $tableName] = explode('.', $tableName);
}
$foreignKeys = [];
$rows = $this->fetchAll(sprintf(
"SELECT
CONSTRAINT_NAME,
CONCAT(TABLE_SCHEMA, '.', TABLE_NAME) AS TABLE_NAME,
COLUMN_NAME,
CONCAT(REFERENCED_TABLE_SCHEMA, '.', REFERENCED_TABLE_NAME) AS REFERENCED_TABLE_NAME,
REFERENCED_COLUMN_NAME
FROM information_schema.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_NAME IS NOT NULL
AND TABLE_SCHEMA = %s
AND TABLE_NAME = '%s'
ORDER BY POSITION_IN_UNIQUE_CONSTRAINT",
empty($schema) ? 'DATABASE()' : "'$schema'",
$tableName
));
foreach ($rows as $row) {
$foreignKeys[$row['CONSTRAINT_NAME']]['table'] = $row['TABLE_NAME'];
$foreignKeys[$row['CONSTRAINT_NAME']]['columns'][] = $row['COLUMN_NAME'];
$foreignKeys[$row['CONSTRAINT_NAME']]['referenced_table'] = $row['REFERENCED_TABLE_NAME'];
$foreignKeys[$row['CONSTRAINT_NAME']]['referenced_columns'][] = $row['REFERENCED_COLUMN_NAME'];
}
return $foreignKeys;
}
/**
* @inheritDoc
*/
protected function getAddForeignKeyInstructions(Table $table, ForeignKey $foreignKey)
{
$alter = sprintf(
'ADD %s',
$this->getForeignKeySqlDefinition($foreignKey)
);
return new AlterInstructions([$alter]);
}
/**
* @inheritDoc
*/
protected function getDropForeignKeyInstructions($tableName, $constraint)
{
$alter = sprintf(
'DROP FOREIGN KEY %s',
$constraint
);
return new AlterInstructions([$alter]);
}
/**
* {@inheritDoc}
*
* @throws \InvalidArgumentException
*/
protected function getDropForeignKeyByColumnsInstructions($tableName, $columns)
{
$instructions = new AlterInstructions();
foreach ($columns as $column) {
$rows = $this->fetchAll(sprintf(
"SELECT
CONSTRAINT_NAME
FROM information_schema.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_SCHEMA = DATABASE()
AND REFERENCED_TABLE_NAME IS NOT NULL
AND TABLE_NAME = '%s'
AND COLUMN_NAME = '%s'
ORDER BY POSITION_IN_UNIQUE_CONSTRAINT",
$tableName,
$column
));
foreach ($rows as $row) {
$instructions->merge($this->getDropForeignKeyInstructions($tableName, $row['CONSTRAINT_NAME']));
}
}
if (empty($instructions->getAlterParts())) {
throw new InvalidArgumentException(sprintf(
"Not foreign key on columns '%s' exist",
implode(',', $columns)
));
}
return $instructions;
}
/**
* {@inheritDoc}
*
* @throws \Phinx\Db\Adapter\UnsupportedColumnTypeException
*/
public function getSqlType($type, $limit = null)
{
switch ($type) {
case static::PHINX_TYPE_FLOAT:
case static::PHINX_TYPE_DOUBLE:
case static::PHINX_TYPE_DECIMAL:
case static::PHINX_TYPE_DATE:
case static::PHINX_TYPE_ENUM:
case static::PHINX_TYPE_SET:
case static::PHINX_TYPE_JSON:
// Geospatial database types
case static::PHINX_TYPE_GEOMETRY:
case static::PHINX_TYPE_POINT:
case static::PHINX_TYPE_LINESTRING:
case static::PHINX_TYPE_POLYGON:
return ['name' => $type];
case static::PHINX_TYPE_DATETIME:
case static::PHINX_TYPE_TIMESTAMP:
case static::PHINX_TYPE_TIME:
return ['name' => $type, 'limit' => $limit];
case static::PHINX_TYPE_STRING:
return ['name' => 'varchar', 'limit' => $limit ?: 255];
case static::PHINX_TYPE_CHAR:
return ['name' => 'char', 'limit' => $limit ?: 255];
case static::PHINX_TYPE_TEXT:
if ($limit) {
$sizes = [
// Order matters! Size must always be tested from longest to shortest!
'longtext' => static::TEXT_LONG,
'mediumtext' => static::TEXT_MEDIUM,
'text' => static::TEXT_REGULAR,
'tinytext' => static::TEXT_SMALL,
];
foreach ($sizes as $name => $length) {
if ($limit >= $length) {
return ['name' => $name];
}
}
}
return ['name' => 'text'];
case static::PHINX_TYPE_BINARY:
if ($limit === null) {
$limit = 255;
}
if ($limit > 255) {
return $this->getSqlType(static::PHINX_TYPE_BLOB, $limit);
}
return ['name' => 'binary', 'limit' => $limit];
case static::PHINX_TYPE_BINARYUUID:
return ['name' => 'binary', 'limit' => 16];
case static::PHINX_TYPE_VARBINARY:
if ($limit === null) {
$limit = 255;
}
if ($limit > 255) {
return $this->getSqlType(static::PHINX_TYPE_BLOB, $limit);
}
return ['name' => 'varbinary', 'limit' => $limit];
case static::PHINX_TYPE_BLOB:
if ($limit !== null) {
// Rework this part as the choosen types were always UNDER the required length
$sizes = [
'tinyblob' => static::BLOB_SMALL,
'blob' => static::BLOB_REGULAR,
'mediumblob' => static::BLOB_MEDIUM,
];
foreach ($sizes as $name => $length) {
if ($limit <= $length) {
return ['name' => $name];
}
}
// For more length requirement, the longblob is used
return ['name' => 'longblob'];
}
// If not limit is provided, fallback on blob
return ['name' => 'blob'];
case static::PHINX_TYPE_TINYBLOB:
// Automatically reprocess blob type to ensure that correct blob subtype is selected given provided limit
return $this->getSqlType(static::PHINX_TYPE_BLOB, $limit ?: static::BLOB_TINY);
case static::PHINX_TYPE_MEDIUMBLOB:
// Automatically reprocess blob type to ensure that correct blob subtype is selected given provided limit
return $this->getSqlType(static::PHINX_TYPE_BLOB, $limit ?: static::BLOB_MEDIUM);
case static::PHINX_TYPE_LONGBLOB:
// Automatically reprocess blob type to ensure that correct blob subtype is selected given provided limit
return $this->getSqlType(static::PHINX_TYPE_BLOB, $limit ?: static::BLOB_LONG);
case static::PHINX_TYPE_BIT:
return ['name' => 'bit', 'limit' => $limit ?: 64];