/
Mysql.php
3811 lines (3442 loc) · 121 KB
/
Mysql.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
/**
* Mysql PDO DB adapter
*
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
namespace Magento\Framework\DB\Adapter\Pdo;
use Magento\Framework\Cache\FrontendInterface;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\DB\ExpressionConverter;
use Magento\Framework\DB\LoggerInterface;
use Magento\Framework\DB\Profiler;
use Magento\Framework\DB\Select;
use Magento\Framework\DB\SelectFactory;
use Magento\Framework\DB\Statement\Parameter;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Phrase;
use Magento\Framework\Stdlib\DateTime;
use Magento\Framework\Stdlib\StringUtils;
/**
* @SuppressWarnings(PHPMD.ExcessivePublicCount)
* @SuppressWarnings(PHPMD.TooManyFields)
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Mysql extends \Zend_Db_Adapter_Pdo_Mysql implements AdapterInterface
{
const TIMESTAMP_FORMAT = 'Y-m-d H:i:s';
const DATETIME_FORMAT = 'Y-m-d H:i:s';
const DATE_FORMAT = 'Y-m-d';
const DDL_DESCRIBE = 1;
const DDL_CREATE = 2;
const DDL_INDEX = 3;
const DDL_FOREIGN_KEY = 4;
const DDL_CACHE_PREFIX = 'DB_PDO_MYSQL_DDL';
const DDL_CACHE_TAG = 'DB_PDO_MYSQL_DDL';
const LENGTH_TABLE_NAME = 64;
const LENGTH_INDEX_NAME = 64;
const LENGTH_FOREIGN_NAME = 64;
/**
* MEMORY engine type for MySQL tables
*/
const ENGINE_MEMORY = 'MEMORY';
/**
* Maximum number of connection retries
*/
const MAX_CONNECTION_RETRIES = 10;
/**
* Default class name for a DB statement.
*
* @var string
*/
protected $_defaultStmtClass = 'Magento\Framework\DB\Statement\Pdo\Mysql';
/**
* Current Transaction Level
*
* @var int
*/
protected $_transactionLevel = 0;
/**
* Whether transaction was rolled back or not
*
* @var bool
*/
protected $_isRolledBack = false;
/**
* Set attribute to connection flag
*
* @var bool
*/
protected $_connectionFlagsSet = false;
/**
* Tables DDL cache
*
* @var array
*/
protected $_ddlCache = [];
/**
* SQL bind params. Used temporarily by regexp callback.
*
* @var array
*/
protected $_bindParams = [];
/**
* Autoincrement for bind value. Used by regexp callback.
*
* @var int
*/
protected $_bindIncrement = 0;
/**
* Cache frontend adapter instance
*
* @var FrontendInterface
*/
protected $_cacheAdapter;
/**
* DDL cache allowing flag
* @var bool
*/
protected $_isDdlCacheAllowed = true;
/**
* MySQL column - Table DDL type pairs
*
* @var array
*/
protected $_ddlColumnTypes = [
Table::TYPE_BOOLEAN => 'bool',
Table::TYPE_SMALLINT => 'smallint',
Table::TYPE_INTEGER => 'int',
Table::TYPE_BIGINT => 'bigint',
Table::TYPE_FLOAT => 'float',
Table::TYPE_DECIMAL => 'decimal',
Table::TYPE_NUMERIC => 'decimal',
Table::TYPE_DATE => 'date',
Table::TYPE_TIMESTAMP => 'timestamp',
Table::TYPE_DATETIME => 'datetime',
Table::TYPE_TEXT => 'text',
Table::TYPE_BLOB => 'blob',
Table::TYPE_VARBINARY => 'blob',
];
/**
* All possible DDL statements
* First 3 symbols for each statement
*
* @var string[]
*/
protected $_ddlRoutines = ['alt', 'cre', 'ren', 'dro', 'tru'];
/**
* Allowed interval units array
*
* @var array
*/
protected $_intervalUnits = [
self::INTERVAL_YEAR => 'YEAR',
self::INTERVAL_MONTH => 'MONTH',
self::INTERVAL_DAY => 'DAY',
self::INTERVAL_HOUR => 'HOUR',
self::INTERVAL_MINUTE => 'MINUTE',
self::INTERVAL_SECOND => 'SECOND',
];
/**
* Hook callback to modify queries. Mysql specific property, designed only for backwards compatibility.
*
* @var array|null
*/
protected $_queryHook = null;
/**
* @var String
*/
protected $string;
/**
* @var DateTime
*/
protected $dateTime;
/**
* @var SelectFactory
*/
protected $selectFactory;
/**
* @var LoggerInterface
*/
protected $logger;
/**
* @param StringUtils $string
* @param DateTime $dateTime
* @param LoggerInterface $logger
* @param SelectFactory $selectFactory
* @param array $config
*/
public function __construct(
StringUtils $string,
DateTime $dateTime,
LoggerInterface $logger,
SelectFactory $selectFactory,
array $config = []
) {
$this->string = $string;
$this->dateTime = $dateTime;
$this->logger = $logger;
$this->selectFactory = $selectFactory;
try {
parent::__construct($config);
} catch (\Zend_Db_Adapter_Exception $e) {
throw new \InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Begin new DB transaction for connection
*
* @return $this
* @throws \Exception
*/
public function beginTransaction()
{
if ($this->_isRolledBack) {
throw new \Exception(AdapterInterface::ERROR_ROLLBACK_INCOMPLETE_MESSAGE);
}
if ($this->_transactionLevel === 0) {
$this->logger->startTimer();
parent::beginTransaction();
$this->logger->logStats(LoggerInterface::TYPE_TRANSACTION, 'BEGIN');
}
++$this->_transactionLevel;
return $this;
}
/**
* Commit DB transaction
*
* @return $this
* @throws \Exception
*/
public function commit()
{
if ($this->_transactionLevel === 1 && !$this->_isRolledBack) {
$this->logger->startTimer();
parent::commit();
$this->logger->logStats(LoggerInterface::TYPE_TRANSACTION, 'COMMIT');
} elseif ($this->_transactionLevel === 0) {
throw new \Exception(AdapterInterface::ERROR_ASYMMETRIC_COMMIT_MESSAGE);
} elseif ($this->_isRolledBack) {
throw new \Exception(AdapterInterface::ERROR_ROLLBACK_INCOMPLETE_MESSAGE);
}
--$this->_transactionLevel;
return $this;
}
/**
* Rollback DB transaction
*
* @return $this
* @throws \Exception
*/
public function rollBack()
{
if ($this->_transactionLevel === 1) {
$this->logger->startTimer();
parent::rollBack();
$this->_isRolledBack = false;
$this->logger->logStats(LoggerInterface::TYPE_TRANSACTION, 'ROLLBACK');
} elseif ($this->_transactionLevel === 0) {
throw new \Exception(AdapterInterface::ERROR_ASYMMETRIC_ROLLBACK_MESSAGE);
} else {
$this->_isRolledBack = true;
}
--$this->_transactionLevel;
return $this;
}
/**
* Get adapter transaction level state. Return 0 if all transactions are complete
*
* @return int
*/
public function getTransactionLevel()
{
return $this->_transactionLevel;
}
/**
* Convert date to DB format
*
* @param int|string|\DateTime $date
* @return \Zend_Db_Expr
*/
public function convertDate($date)
{
return $this->formatDate($date, false);
}
/**
* Convert date and time to DB format
*
* @param int|string|\DateTime $datetime
* @return \Zend_Db_Expr
*/
public function convertDateTime($datetime)
{
return $this->formatDate($datetime, true);
}
/**
* Creates a PDO object and connects to the database.
*
* @return void
* @throws \Zend_Db_Adapter_Exception
*/
protected function _connect()
{
if ($this->_connection) {
return;
}
if (!extension_loaded('pdo_mysql')) {
throw new \Zend_Db_Adapter_Exception('pdo_mysql extension is not installed');
}
if (!isset($this->_config['host'])) {
throw new \Zend_Db_Adapter_Exception('No host configured to connect');
}
if (strpos($this->_config['host'], '/') !== false) {
$this->_config['unix_socket'] = $this->_config['host'];
unset($this->_config['host']);
} elseif (strpos($this->_config['host'], ':') !== false) {
list($this->_config['host'], $this->_config['port']) = explode(':', $this->_config['host']);
}
$this->logger->startTimer();
parent::_connect();
$this->logger->logStats(LoggerInterface::TYPE_CONNECT, '');
/** @link http://bugs.mysql.com/bug.php?id=18551 */
$this->_connection->query("SET SQL_MODE=''");
// As we use default value CURRENT_TIMESTAMP for TIMESTAMP type columns we need to set GMT timezone
$this->_connection->query("SET time_zone = '+00:00'");
if (isset($this->_config['initStatements'])) {
$this->query($this->_config['initStatements']);
}
if (!$this->_connectionFlagsSet) {
$this->_connection->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
$this->_connection->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
$this->_connectionFlagsSet = true;
}
}
/**
* Run RAW Query
*
* @param string $sql
* @return \Zend_Db_Statement_Interface
* @throws \PDOException
*/
public function rawQuery($sql)
{
try {
$result = $this->query($sql);
} catch (\Zend_Db_Statement_Exception $e) {
// Convert to \PDOException to maintain backwards compatibility with usage of MySQL adapter
$e = $e->getPrevious();
if (!($e instanceof \PDOException)) {
$e = new \PDOException($e->getMessage(), $e->getCode());
}
throw $e;
}
return $result;
}
/**
* Run RAW query and Fetch First row
*
* @param string $sql
* @param string|int $field
* @return mixed|null
*/
public function rawFetchRow($sql, $field = null)
{
$result = $this->rawQuery($sql);
if (!$result) {
return false;
}
$row = $result->fetch(\PDO::FETCH_ASSOC);
if (!$row) {
return false;
}
if (empty($field)) {
return $row;
} else {
return isset($row[$field]) ? $row[$field] : false;
}
}
/**
* Check transaction level in case of DDL query
*
* @param string|\Magento\Framework\DB\Select $sql
* @return void
* @throws \Zend_Db_Adapter_Exception
*/
protected function _checkDdlTransaction($sql)
{
if ($this->getTransactionLevel() > 0) {
$sql = ltrim(preg_replace('/\s+/', ' ', $sql));
$sqlMessage = explode(' ', $sql, 3);
$startSql = strtolower(substr($sqlMessage[0], 0, 3));
if (in_array($startSql, $this->_ddlRoutines) && strcasecmp($sqlMessage[1], 'temporary') !== 0) {
trigger_error(AdapterInterface::ERROR_DDL_MESSAGE, E_USER_ERROR);
}
}
}
/**
* Special handling for PDO query().
* All bind parameter names must begin with ':'.
*
* @param string|\Magento\Framework\DB\Select $sql The SQL statement with placeholders.
* @param mixed $bind An array of data or data itself to bind to the placeholders.
* @return \Zend_Db_Statement_Pdo|void
* @throws \Zend_Db_Adapter_Exception To re-throw \PDOException.
* @throws LocalizedException In case multiple queries are attempted at once, to protect from SQL injection
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
protected function _query($sql, $bind = [])
{
$connectionErrors = [
2006, // SQLSTATE[HY000]: General error: 2006 MySQL server has gone away
2013, // SQLSTATE[HY000]: General error: 2013 Lost connection to MySQL server during query
];
$triesCount = 0;
do {
$retry = false;
$this->logger->startTimer();
try {
$this->_checkDdlTransaction($sql);
$this->_prepareQuery($sql, $bind);
$result = parent::query($sql, $bind);
$this->logger->logStats(LoggerInterface::TYPE_QUERY, $sql, $bind, $result);
return $result;
} catch (\Exception $e) {
// Finalize broken query
$profiler = $this->getProfiler();
if ($profiler instanceof Profiler) {
/** @var Profiler $profiler */
$profiler->queryEndLast();
}
/** @var $pdoException \PDOException */
$pdoException = null;
if ($e instanceof \PDOException) {
$pdoException = $e;
} elseif (($e instanceof \Zend_Db_Statement_Exception) && ($e->getPrevious() instanceof \PDOException)) {
$pdoException = $e->getPrevious();
}
// Check to reconnect
if ($pdoException && $triesCount < self::MAX_CONNECTION_RETRIES
&& in_array($pdoException->errorInfo[1], $connectionErrors)
) {
$retry = true;
$triesCount++;
$this->closeConnection();
$this->_connect();
}
if (!$retry) {
$this->logger->logStats(LoggerInterface::TYPE_QUERY, $sql, $bind);
$this->logger->critical($e);
throw $e;
}
}
} while ($retry);
}
/**
* Special handling for PDO query().
* All bind parameter names must begin with ':'.
*
* @param string|\Magento\Framework\DB\Select $sql The SQL statement with placeholders.
* @param mixed $bind An array of data or data itself to bind to the placeholders.
* @return \Zend_Db_Statement_Pdo|void
* @throws \Zend_Db_Adapter_Exception To re-throw \PDOException.
* @throws LocalizedException In case multiple queries are attempted at once, to protect from SQL injection
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function query($sql, $bind = [])
{
if (strpos(rtrim($sql, " \t\n\r\0;"), ';') !== false && count($this->_splitMultiQuery($sql)) > 1) {
throw new \Magento\Framework\Exception\LocalizedException(new Phrase('Cannot execute multiple queries'));
}
return $this->_query($sql, $bind);
}
/**
* Allows multiple queries -- to safeguard against SQL injection, USE CAUTION and verify that input
* cannot be tampered with.
*
* Special handling for PDO query().
* All bind parameter names must begin with ':'.
*
* @param string|\Magento\Framework\DB\Select $sql The SQL statement with placeholders.
* @param mixed $bind An array of data or data itself to bind to the placeholders.
* @return \Zend_Db_Statement_Pdo|void
* @throws \Zend_Db_Adapter_Exception To re-throw \PDOException.
* @throws LocalizedException In case multiple queries are attempted at once, to protect from SQL injection
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function multiQuery($sql, $bind = [])
{
return $this->_query($sql, $bind);
}
/**
* Prepares SQL query by moving to bind all special parameters that can be confused with bind placeholders
* (e.g. "foo:bar"). And also changes named bind to positional one, because underlying library has problems
* with named binds.
*
* @param \Magento\Framework\DB\Select|string $sql
* @param mixed $bind
* @return $this
*/
protected function _prepareQuery(&$sql, &$bind = [])
{
$sql = (string) $sql;
if (!is_array($bind)) {
$bind = [$bind];
}
// Mixed bind is not supported - so remember whether it is named bind, to normalize later if required
$isNamedBind = false;
if ($bind) {
foreach ($bind as $k => $v) {
if (!is_int($k)) {
$isNamedBind = true;
if ($k[0] != ':') {
$bind[":{$k}"] = $v;
unset($bind[$k]);
}
}
}
}
// Special query hook
if ($this->_queryHook) {
$object = $this->_queryHook['object'];
$method = $this->_queryHook['method'];
$object->$method($sql, $bind);
}
return $this;
}
/**
* Callback function for preparation of query and bind by regexp.
* Checks query parameters for special symbols and moves such parameters to bind array as named ones.
* This method writes to $_bindParams, where query bind parameters are kept.
* This method requires further normalizing, if bind array is positional.
*
* @param string[] $matches
* @return string
*/
public function proccessBindCallback($matches)
{
if (isset($matches[6]) && (
strpos($matches[6], "'") !== false ||
strpos($matches[6], ':') !== false ||
strpos($matches[6], '?') !== false)
) {
$bindName = ':_mage_bind_var_' . (++$this->_bindIncrement);
$this->_bindParams[$bindName] = $this->_unQuote($matches[6]);
return ' ' . $bindName;
}
return $matches[0];
}
/**
* Unquote raw string (use for auto-bind)
*
* @param string $string
* @return string
*/
protected function _unQuote($string)
{
$translate = [
"\\000" => "\000",
"\\n" => "\n",
"\\r" => "\r",
"\\\\" => "\\",
"\'" => "'",
"\\\"" => "\"",
"\\032" => "\032",
];
return strtr($string, $translate);
}
/**
* Normalizes mixed positional-named bind to positional bind, and replaces named placeholders in query to
* '?' placeholders.
*
* @param string $sql
* @param array $bind
* @return $this
*/
protected function _convertMixedBind(&$sql, &$bind)
{
$positions = [];
$offset = 0;
// get positions
while (true) {
$pos = strpos($sql, '?', $offset);
if ($pos !== false) {
$positions[] = $pos;
$offset = ++$pos;
} else {
break;
}
}
$bindResult = [];
$map = [];
foreach ($bind as $k => $v) {
// positional
if (is_int($k)) {
if (!isset($positions[$k])) {
continue;
}
$bindResult[$positions[$k]] = $v;
} else {
$offset = 0;
while (true) {
$pos = strpos($sql, $k, $offset);
if ($pos === false) {
break;
} else {
$offset = $pos + strlen($k);
$bindResult[$pos] = $v;
}
}
$map[$k] = '?';
}
}
ksort($bindResult);
$bind = array_values($bindResult);
$sql = strtr($sql, $map);
return $this;
}
/**
* Sets (removes) query hook.
*
* $hook must be either array with 'object' and 'method' entries, or null to remove hook.
* Previous hook is returned.
*
* @param array $hook
* @return array|null
*/
public function setQueryHook($hook)
{
$prev = $this->_queryHook;
$this->_queryHook = $hook;
return $prev;
}
/**
* Split multi statement query
*
* @param string $sql
* @return array
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
protected function _splitMultiQuery($sql)
{
$parts = preg_split(
'#(;|\'|"|\\\\|//|--|\n|/\*|\*/)#',
$sql,
null,
PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
);
$q = false;
$c = false;
$stmts = [];
$s = '';
foreach ($parts as $i => $part) {
// strings
if (($part === "'" || $part === '"') && ($i === 0 || $parts[$i-1] !== '\\')) {
if ($q === false) {
$q = $part;
} elseif ($q === $part) {
$q = false;
}
}
// single line comments
if (($part === '//' || $part === '--') && ($i === 0 || $parts[$i-1] === "\n")) {
$c = $part;
} elseif ($part === "\n" && ($c === '//' || $c === '--')) {
$c = false;
}
// multi line comments
if ($part === '/*' && $c === false) {
$c = '/*';
} elseif ($part === '*/' && $c === '/*') {
$c = false;
}
// statements
if ($part === ';' && $q === false && $c === false) {
if (trim($s) !== '') {
$stmts[] = trim($s);
$s = '';
}
} else {
$s .= $part;
}
}
if (trim($s) !== '') {
$stmts[] = trim($s);
}
return $stmts;
}
/**
* Drop the Foreign Key from table
*
* @param string $tableName
* @param string $fkName
* @param string $schemaName
* @return $this
*/
public function dropForeignKey($tableName, $fkName, $schemaName = null)
{
$foreignKeys = $this->getForeignKeys($tableName, $schemaName);
$fkName = strtoupper($fkName);
if (substr($fkName, 0, 3) == 'FK_') {
$fkName = substr($fkName, 3);
}
foreach ([$fkName, 'FK_' . $fkName] as $key) {
if (isset($foreignKeys[$key])) {
$sql = sprintf(
'ALTER TABLE %s DROP FOREIGN KEY %s',
$this->quoteIdentifier($this->_getTableName($tableName, $schemaName)),
$this->quoteIdentifier($foreignKeys[$key]['FK_NAME'])
);
$this->resetDdlCache($tableName, $schemaName);
$this->rawQuery($sql);
}
}
return $this;
}
/**
* Prepare table before add constraint foreign key
*
* @param string $tableName
* @param string $columnName
* @param string $refTableName
* @param string $refColumnName
* @param string $onDelete
* @return $this
*/
public function purgeOrphanRecords(
$tableName,
$columnName,
$refTableName,
$refColumnName,
$onDelete = AdapterInterface::FK_ACTION_CASCADE
) {
$onDelete = strtoupper($onDelete);
if ($onDelete == AdapterInterface::FK_ACTION_CASCADE
|| $onDelete == AdapterInterface::FK_ACTION_RESTRICT
) {
$sql = sprintf(
"DELETE p.* FROM %s AS p LEFT JOIN %s AS r ON p.%s = r.%s WHERE r.%s IS NULL",
$this->quoteIdentifier($tableName),
$this->quoteIdentifier($refTableName),
$this->quoteIdentifier($columnName),
$this->quoteIdentifier($refColumnName),
$this->quoteIdentifier($refColumnName)
);
$this->rawQuery($sql);
} elseif ($onDelete == AdapterInterface::FK_ACTION_SET_NULL) {
$sql = sprintf(
"UPDATE %s AS p LEFT JOIN %s AS r ON p.%s = r.%s SET p.%s = NULL WHERE r.%s IS NULL",
$this->quoteIdentifier($tableName),
$this->quoteIdentifier($refTableName),
$this->quoteIdentifier($columnName),
$this->quoteIdentifier($refColumnName),
$this->quoteIdentifier($columnName),
$this->quoteIdentifier($refColumnName)
);
$this->rawQuery($sql);
}
return $this;
}
/**
* Check does table column exist
*
* @param string $tableName
* @param string $columnName
* @param string $schemaName
* @return bool
*/
public function tableColumnExists($tableName, $columnName, $schemaName = null)
{
$describe = $this->describeTable($tableName, $schemaName);
foreach ($describe as $column) {
if ($column['COLUMN_NAME'] == $columnName) {
return true;
}
}
return false;
}
/**
* Adds new column to table.
*
* Generally $defintion must be array with column data to keep this call cross-DB compatible.
* Using string as $definition is allowed only for concrete DB adapter.
* Adds primary key if needed
*
* @param string $tableName
* @param string $columnName
* @param array|string $definition string specific or universal array DB Server definition
* @param string $schemaName
* @return true|\Zend_Db_Statement_Pdo
* @throws \Zend_Db_Exception
*/
public function addColumn($tableName, $columnName, $definition, $schemaName = null)
{
if ($this->tableColumnExists($tableName, $columnName, $schemaName)) {
return true;
}
$primaryKey = '';
if (is_array($definition)) {
$definition = array_change_key_case($definition, CASE_UPPER);
if (empty($definition['COMMENT'])) {
throw new \Zend_Db_Exception("Impossible to create a column without comment.");
}
if (!empty($definition['PRIMARY'])) {
$primaryKey = sprintf(', ADD PRIMARY KEY (%s)', $this->quoteIdentifier($columnName));
}
$definition = $this->_getColumnDefinition($definition);
}
$sql = sprintf(
'ALTER TABLE %s ADD COLUMN %s %s %s',
$this->quoteIdentifier($this->_getTableName($tableName, $schemaName)),
$this->quoteIdentifier($columnName),
$definition,
$primaryKey
);
$result = $this->rawQuery($sql);
$this->resetDdlCache($tableName, $schemaName);
return $result;
}
/**
* Delete table column
*
* @param string $tableName
* @param string $columnName
* @param string $schemaName
* @return true|\Zend_Db_Statement_Pdo
*/
public function dropColumn($tableName, $columnName, $schemaName = null)
{
if (!$this->tableColumnExists($tableName, $columnName, $schemaName)) {
return true;
}
$alterDrop = [];
$foreignKeys = $this->getForeignKeys($tableName, $schemaName);
foreach ($foreignKeys as $fkProp) {
if ($fkProp['COLUMN_NAME'] == $columnName) {
$alterDrop[] = 'DROP FOREIGN KEY ' . $this->quoteIdentifier($fkProp['FK_NAME']);
}
}
/* drop index that after column removal would coincide with the existing index by indexed columns */
foreach ($this->getIndexList($tableName, $schemaName) as $idxData) {
$idxColumns = $idxData['COLUMNS_LIST'];
$idxColumnKey = array_search($columnName, $idxColumns);
if ($idxColumnKey !== false) {
unset($idxColumns[$idxColumnKey]);
if ($idxColumns && $this->_getIndexByColumns($tableName, $idxColumns, $schemaName)) {
$this->dropIndex($tableName, $idxData['KEY_NAME'], $schemaName);
}
}
}
$alterDrop[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
$sql = sprintf(
'ALTER TABLE %s %s',
$this->quoteIdentifier($this->_getTableName($tableName, $schemaName)),
implode(', ', $alterDrop)
);
$result = $this->rawQuery($sql);
$this->resetDdlCache($tableName, $schemaName);
return $result;
}
/**
* Retrieve index information by indexed columns or return NULL, if there is no index for a column list
*
* @param string $tableName
* @param array $columns
* @param string|null $schemaName
* @return array|null
*/
protected function _getIndexByColumns($tableName, array $columns, $schemaName)
{
foreach ($this->getIndexList($tableName, $schemaName) as $idxData) {
if ($idxData['COLUMNS_LIST'] === $columns) {
return $idxData;
}
}
return null;
}
/**
* Change the column name and definition
*
* For change definition of column - use modifyColumn
*
* @param string $tableName
* @param string $oldColumnName
* @param string $newColumnName
* @param array $definition
* @param boolean $flushData flush table statistic
* @param string $schemaName
* @return \Zend_Db_Statement_Pdo
* @throws \Zend_Db_Exception
*/
public function changeColumn(
$tableName,
$oldColumnName,
$newColumnName,
$definition,
$flushData = false,
$schemaName = null
) {
if (!$this->tableColumnExists($tableName, $oldColumnName, $schemaName)) {
throw new \Zend_Db_Exception(
sprintf(
'Column "%s" does not exist in table "%s".',
$oldColumnName,
$tableName
)
);
}
if (is_array($definition)) {
$definition = $this->_getColumnDefinition($definition);
}
$sql = sprintf(
'ALTER TABLE %s CHANGE COLUMN %s %s %s',
$this->quoteIdentifier($tableName),
$this->quoteIdentifier($oldColumnName),
$this->quoteIdentifier($newColumnName),
$definition
);
$result = $this->rawQuery($sql);
if ($flushData) {
$this->showTableStatus($tableName, $schemaName);
}