Failed Conditions
Pull Request — 3.0.x (#3980)
by Guilherme
124:28 queued 58:42
created

AbstractPlatform::getSequencePrefix()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 10
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 4
nc 5
nop 2
crap 4
1
<?php
2
3
namespace Doctrine\DBAL\Platforms;
4
5
use Doctrine\Common\EventManager;
6
use Doctrine\DBAL\DBALException;
7
use Doctrine\DBAL\Event\SchemaAlterTableAddColumnEventArgs;
8
use Doctrine\DBAL\Event\SchemaAlterTableChangeColumnEventArgs;
9
use Doctrine\DBAL\Event\SchemaAlterTableEventArgs;
10
use Doctrine\DBAL\Event\SchemaAlterTableRemoveColumnEventArgs;
11
use Doctrine\DBAL\Event\SchemaAlterTableRenameColumnEventArgs;
12
use Doctrine\DBAL\Event\SchemaCreateTableColumnEventArgs;
13
use Doctrine\DBAL\Event\SchemaCreateTableEventArgs;
14
use Doctrine\DBAL\Event\SchemaDropTableEventArgs;
15
use Doctrine\DBAL\Events;
16
use Doctrine\DBAL\Platforms\Keywords\KeywordList;
17
use Doctrine\DBAL\Schema\Column;
18
use Doctrine\DBAL\Schema\ColumnDiff;
19
use Doctrine\DBAL\Schema\Constraint;
20
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
21
use Doctrine\DBAL\Schema\Identifier;
22
use Doctrine\DBAL\Schema\Index;
23
use Doctrine\DBAL\Schema\Sequence;
24
use Doctrine\DBAL\Schema\Table;
25
use Doctrine\DBAL\Schema\TableDiff;
26
use Doctrine\DBAL\Schema\UniqueConstraint;
27
use Doctrine\DBAL\TransactionIsolationLevel;
28
use Doctrine\DBAL\Types;
29
use Doctrine\DBAL\Types\Type;
30
use InvalidArgumentException;
31
use UnexpectedValueException;
32
use const E_USER_DEPRECATED;
33
use function addcslashes;
34
use function array_map;
35
use function array_merge;
36
use function array_unique;
37
use function array_values;
38
use function assert;
39
use function count;
40
use function explode;
41
use function func_get_arg;
42
use function func_get_args;
43
use function func_num_args;
44
use function implode;
45
use function in_array;
46
use function is_array;
47
use function is_bool;
48
use function is_int;
49
use function is_string;
50
use function preg_quote;
51
use function preg_replace;
52
use function sprintf;
53
use function str_replace;
54
use function strlen;
55
use function strpos;
56
use function strtolower;
57
use function strtoupper;
58
use function trigger_error;
59
60
/**
61
 * Base class for all DatabasePlatforms. The DatabasePlatforms are the central
62
 * point of abstraction of platform-specific behaviors, features and SQL dialects.
63
 * They are a passive source of information.
64
 *
65
 * @todo Remove any unnecessary methods.
66
 */
67
abstract class AbstractPlatform
68
{
69
    public const CREATE_INDEXES = 1;
70
71
    public const CREATE_FOREIGNKEYS = 2;
72
73
    /**
74
     * @deprecated Use DateIntervalUnit::INTERVAL_UNIT_SECOND.
75
     */
76
    public const DATE_INTERVAL_UNIT_SECOND = DateIntervalUnit::SECOND;
77
78
    /**
79
     * @deprecated Use DateIntervalUnit::MINUTE.
80
     */
81
    public const DATE_INTERVAL_UNIT_MINUTE = DateIntervalUnit::MINUTE;
82
83
    /**
84
     * @deprecated Use DateIntervalUnit::HOUR.
85
     */
86
    public const DATE_INTERVAL_UNIT_HOUR = DateIntervalUnit::HOUR;
87
88
    /**
89
     * @deprecated Use DateIntervalUnit::DAY.
90
     */
91
    public const DATE_INTERVAL_UNIT_DAY = DateIntervalUnit::DAY;
92
93
    /**
94
     * @deprecated Use DateIntervalUnit::WEEK.
95
     */
96
    public const DATE_INTERVAL_UNIT_WEEK = DateIntervalUnit::WEEK;
97
98
    /**
99
     * @deprecated Use DateIntervalUnit::MONTH.
100
     */
101
    public const DATE_INTERVAL_UNIT_MONTH = DateIntervalUnit::MONTH;
102
103
    /**
104
     * @deprecated Use DateIntervalUnit::QUARTER.
105
     */
106
    public const DATE_INTERVAL_UNIT_QUARTER = DateIntervalUnit::QUARTER;
107
108
    /**
109
     * @deprecated Use DateIntervalUnit::QUARTER.
110
     */
111
    public const DATE_INTERVAL_UNIT_YEAR = DateIntervalUnit::YEAR;
112
113
    /**
114
     * @deprecated Use TrimMode::UNSPECIFIED.
115
     */
116
    public const TRIM_UNSPECIFIED = TrimMode::UNSPECIFIED;
117
118
    /**
119
     * @deprecated Use TrimMode::LEADING.
120
     */
121
    public const TRIM_LEADING = TrimMode::LEADING;
122
123
    /**
124
     * @deprecated Use TrimMode::TRAILING.
125
     */
126
    public const TRIM_TRAILING = TrimMode::TRAILING;
127
128
    /**
129
     * @deprecated Use TrimMode::BOTH.
130
     */
131
    public const TRIM_BOTH = TrimMode::BOTH;
132
133
    /** @var string[]|null */
134
    protected $doctrineTypeMapping = null;
135
136
    /**
137
     * Contains a list of all columns that should generate parseable column comments for type-detection
138
     * in reverse engineering scenarios.
139
     *
140
     * @var string[]|null
141
     */
142
    protected $doctrineTypeComments = null;
143
144
    /** @var EventManager|null */
145
    protected $_eventManager;
146
147
    /**
148
     * Holds the KeywordList instance for the current platform.
149
     *
150
     * @var KeywordList|null
151
     */
152
    protected $_keywords;
153 42562
154
    public function __construct()
155 42562
    {
156
    }
157
158
    /**
159
     * Sets the EventManager used by the Platform.
160
     *
161
     * @return void
162 1268
     */
163
    public function setEventManager(EventManager $eventManager)
164 1268
    {
165 1268
        $this->_eventManager = $eventManager;
166
    }
167
168
    /**
169
     * Gets the EventManager used by the Platform.
170
     *
171
     * @return EventManager|null
172 1688
     */
173
    public function getEventManager()
174 1688
    {
175
        return $this->_eventManager;
176
    }
177
178
    /**
179
     * Returns the SQL snippet that declares a boolean column.
180
     *
181
     * @param mixed[] $columnDef
182
     *
183
     * @return string
184
     */
185
    abstract public function getBooleanTypeDeclarationSQL(array $columnDef);
186
187
    /**
188
     * Returns the SQL snippet that declares a 4 byte integer column.
189
     *
190
     * @param mixed[] $columnDef
191
     *
192
     * @return string
193
     */
194
    abstract public function getIntegerTypeDeclarationSQL(array $columnDef);
195
196
    /**
197
     * Returns the SQL snippet that declares an 8 byte integer column.
198
     *
199
     * @param mixed[] $columnDef
200
     *
201
     * @return string
202
     */
203
    abstract public function getBigIntTypeDeclarationSQL(array $columnDef);
204
205
    /**
206
     * Returns the SQL snippet that declares a 2 byte integer column.
207
     *
208
     * @param mixed[] $columnDef
209
     *
210
     * @return string
211
     */
212
    abstract public function getSmallIntTypeDeclarationSQL(array $columnDef);
213
214
    /**
215
     * Returns the SQL snippet that declares common properties of an integer column.
216
     *
217
     * @param mixed[] $columnDef
218
     *
219
     * @return string
220
     */
221
    abstract protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef);
222
223
    /**
224
     * Lazy load Doctrine Type Mappings.
225
     *
226
     * @return void
227
     */
228
    abstract protected function initializeDoctrineTypeMappings();
229
230
    /**
231
     * Initializes Doctrine Type Mappings with the platform defaults
232
     * and with all additional type mappings.
233
     *
234
     * @return void
235 1266
     */
236
    private function initializeAllDoctrineTypeMappings()
237 1266
    {
238
        $this->initializeDoctrineTypeMappings();
239 1266
240 1266
        foreach (Type::getTypesMap() as $typeName => $className) {
241 684
            foreach (Type::getType($typeName)->getMappedDatabaseTypes($this) as $dbType) {
242
                $this->doctrineTypeMapping[$dbType] = $typeName;
243
            }
244 1266
        }
245
    }
246
247
    /**
248
     * Returns the SQL snippet used to declare a VARCHAR column type.
249
     *
250
     * @param mixed[] $field
251
     *
252
     * @return string
253 5140
     */
254
    public function getVarcharTypeDeclarationSQL(array $field)
255 5140
    {
256 985
        if (! isset($field['length'])) {
257
            $field['length'] = $this->getVarcharDefaultLength();
258
        }
259 5140
260
        $fixed = $field['fixed'] ?? false;
261 5140
262 760
        $maxLength = $fixed
263 5140
            ? $this->getCharMaxLength()
264
            : $this->getVarcharMaxLength();
265 5140
266
        if ($field['length'] > $maxLength) {
267
            return $this->getClobTypeDeclarationSQL($field);
268
        }
269 5140
270
        return $this->getVarcharTypeDeclarationSQLSnippet($field['length'], $fixed);
271
    }
272
273
    /**
274
     * Returns the SQL snippet used to declare a BINARY/VARBINARY column type.
275
     *
276
     * @param mixed[] $field The column definition.
277
     *
278
     * @return string
279 417
     */
280
    public function getBinaryTypeDeclarationSQL(array $field)
281 417
    {
282 241
        if (! isset($field['length'])) {
283
            $field['length'] = $this->getBinaryDefaultLength();
284
        }
285 417
286
        $fixed = $field['fixed'] ?? false;
287 417
288
        $maxLength = $this->getBinaryMaxLength();
289 417
290 226
        if ($field['length'] > $maxLength) {
291 154
            if ($maxLength > 0) {
292 7
                @trigger_error(sprintf(
293 154
                    'Binary field length %d is greater than supported by the platform (%d). Reduce the field length or use a BLOB field instead.',
294 154
                    $field['length'],
295 154
                    $maxLength
296
                ), E_USER_DEPRECATED);
297
            }
298 226
299
            return $this->getBlobTypeDeclarationSQL($field);
300
        }
301 257
302
        return $this->getBinaryTypeDeclarationSQLSnippet($field['length'], $fixed);
303
    }
304
305
    /**
306
     * Returns the SQL snippet to declare a GUID/UUID field.
307
     *
308
     * By default this maps directly to a CHAR(36) and only maps to more
309
     * special datatypes when the underlying databases support this datatype.
310
     *
311
     * @param mixed[] $field
312
     *
313
     * @return string
314 144
     */
315
    public function getGuidTypeDeclarationSQL(array $field)
316 144
    {
317 144
        $field['length'] = 36;
318
        $field['fixed']  = true;
319 144
320
        return $this->getVarcharTypeDeclarationSQL($field);
321
    }
322
323
    /**
324
     * Returns the SQL snippet to declare a JSON field.
325
     *
326
     * By default this maps directly to a CLOB and only maps to more
327
     * special datatypes when the underlying databases support this datatype.
328
     *
329
     * @param mixed[] $field
330
     *
331
     * @return string
332 289
     */
333
    public function getJsonTypeDeclarationSQL(array $field)
334 289
    {
335
        return $this->getClobTypeDeclarationSQL($field);
336
    }
337
338
    /**
339
     * @param int|false $length
340
     * @param bool      $fixed
341
     *
342
     * @return string
343
     *
344
     * @throws DBALException If not supported on this platform.
345
     */
346
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
0 ignored issues
show
Unused Code introduced by
The parameter $fixed is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

346
    protected function getVarcharTypeDeclarationSQLSnippet($length, /** @scrutinizer ignore-unused */ $fixed)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
347
    {
348
        throw DBALException::notSupported('VARCHARs not supported by Platform.');
349
    }
350
351
    /**
352
     * Returns the SQL snippet used to declare a BINARY/VARBINARY column type.
353
     *
354
     * @param int|false $length The length of the column.
355
     * @param bool      $fixed  Whether the column length is fixed.
356
     *
357
     * @return string
358
     *
359
     * @throws DBALException If not supported on this platform.
360
     */
361
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
0 ignored issues
show
Unused Code introduced by
The parameter $fixed is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

361
    protected function getBinaryTypeDeclarationSQLSnippet($length, /** @scrutinizer ignore-unused */ $fixed)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
362
    {
363
        throw DBALException::notSupported('BINARY/VARBINARY column types are not supported by this platform.');
364
    }
365
366
    /**
367
     * Returns the SQL snippet used to declare a CLOB column type.
368
     *
369
     * @param mixed[] $field
370
     *
371
     * @return string
372
     */
373
    abstract public function getClobTypeDeclarationSQL(array $field);
374
375
    /**
376
     * Returns the SQL Snippet used to declare a BLOB column type.
377
     *
378
     * @param mixed[] $field
379
     *
380
     * @return string
381
     */
382
    abstract public function getBlobTypeDeclarationSQL(array $field);
383
384
    /**
385
     * Gets the name of the platform.
386
     *
387
     * @return string
388
     */
389
    abstract public function getName();
390
391
    /**
392
     * Registers a doctrine type to be used in conjunction with a column type of this platform.
393
     *
394
     * @param string $dbType
395
     * @param string $doctrineType
396
     *
397
     * @return void
398
     *
399
     * @throws DBALException If the type is not found.
400 687
     */
401
    public function registerDoctrineTypeMapping($dbType, $doctrineType)
402 687
    {
403 682
        if ($this->doctrineTypeMapping === null) {
404
            $this->initializeAllDoctrineTypeMappings();
405
        }
406 687
407 220
        if (! Types\Type::hasType($doctrineType)) {
408
            throw DBALException::typeNotFound($doctrineType);
409
        }
410 467
411 467
        $dbType                             = strtolower($dbType);
412
        $this->doctrineTypeMapping[$dbType] = $doctrineType;
413 467
414
        $doctrineType = Type::getType($doctrineType);
415 467
416 247
        if (! $doctrineType->requiresSQLCommentHint($this)) {
417
            return;
418
        }
419 220
420 220
        $this->markDoctrineTypeCommented($doctrineType);
421
    }
422
423
    /**
424
     * Gets the Doctrine type that is mapped for the given database column type.
425
     *
426
     * @param string $dbType
427
     *
428
     * @return string
429
     *
430
     * @throws DBALException
431 2319
     */
432
    public function getDoctrineTypeMapping($dbType)
433 2319
    {
434 298
        if ($this->doctrineTypeMapping === null) {
435
            $this->initializeAllDoctrineTypeMappings();
436
        }
437 2319
438
        $dbType = strtolower($dbType);
439 2319
440 220
        if (! isset($this->doctrineTypeMapping[$dbType])) {
441
            throw new DBALException('Unknown database type ' . $dbType . ' requested, ' . static::class . ' may not support it.');
442
        }
443 2099
444
        return $this->doctrineTypeMapping[$dbType];
445
    }
446
447
    /**
448
     * Checks if a database type is currently supported by this platform.
449
     *
450
     * @param string $dbType
451
     *
452
     * @return bool
453 328
     */
454
    public function hasDoctrineTypeMappingFor($dbType)
455 328
    {
456 286
        if ($this->doctrineTypeMapping === null) {
457
            $this->initializeAllDoctrineTypeMappings();
458
        }
459 328
460
        $dbType = strtolower($dbType);
461 328
462
        return isset($this->doctrineTypeMapping[$dbType]);
463
    }
464
465
    /**
466
     * Initializes the Doctrine Type comments instance variable for in_array() checks.
467
     *
468
     * @return void
469 11149
     */
470
    protected function initializeCommentedDoctrineTypes()
471 11149
    {
472
        $this->doctrineTypeComments = [];
473 11149
474 11149
        foreach (Type::getTypesMap() as $typeName => $className) {
475
            $type = Type::getType($typeName);
476 11149
477 11149
            if (! $type->requiresSQLCommentHint($this)) {
478
                continue;
479
            }
480 11149
481
            $this->doctrineTypeComments[] = $typeName;
482 11149
        }
483
    }
484
485
    /**
486
     * Is it necessary for the platform to add a parsable type comment to allow reverse engineering the given type?
487
     *
488
     * @return bool
489 14529
     */
490
    public function isCommentedDoctrineType(Type $doctrineType)
491 14529
    {
492 10929
        if ($this->doctrineTypeComments === null) {
493
            $this->initializeCommentedDoctrineTypes();
494
        }
495 14529
496
        assert(is_array($this->doctrineTypeComments));
497 14529
498
        return in_array($doctrineType->getName(), $this->doctrineTypeComments, true);
499
    }
500
501
    /**
502
     * Marks this type as to be commented in ALTER TABLE and CREATE TABLE statements.
503
     *
504
     * @param string|Type $doctrineType
505
     *
506
     * @return void
507 220
     */
508
    public function markDoctrineTypeCommented($doctrineType)
509 220
    {
510 220
        if ($this->doctrineTypeComments === null) {
511
            $this->initializeCommentedDoctrineTypes();
512
        }
513 220
514
        assert(is_array($this->doctrineTypeComments));
515 220
516 220
        $this->doctrineTypeComments[] = $doctrineType instanceof Type ? $doctrineType->getName() : $doctrineType;
517
    }
518
519
    /**
520
     * Gets the comment to append to a column comment that helps parsing this type in reverse engineering.
521
     *
522
     * @return string
523 724
     */
524
    public function getDoctrineTypeComment(Type $doctrineType)
525 724
    {
526
        return '(DC2Type:' . $doctrineType->getName() . ')';
527
    }
528
529
    /**
530
     * Gets the comment of a passed column modified by potential doctrine type comment hints.
531
     *
532
     * @return string|null
533 8833
     */
534
    protected function getColumnComment(Column $column)
535 8833
    {
536
        $comment = $column->getComment();
537 8833
538 724
        if ($this->isCommentedDoctrineType($column->getType())) {
539
            $comment .= $this->getDoctrineTypeComment($column->getType());
540
        }
541 8833
542
        return $comment;
543
    }
544
545
    /**
546
     * Gets the character used for identifier quoting.
547
     *
548
     * @return string
549 3906
     */
550
    public function getIdentifierQuoteCharacter()
551 3906
    {
552
        return '"';
553
    }
554
555
    /**
556
     * Gets the string portion that starts an SQL comment.
557
     *
558
     * @return string
559
     */
560
    public function getSqlCommentStartString()
561
    {
562
        return '--';
563
    }
564
565
    /**
566
     * Gets the string portion that ends an SQL comment.
567
     *
568
     * @return string
569
     */
570
    public function getSqlCommentEndString()
571
    {
572
        return "\n";
573
    }
574
575
    /**
576
     * Gets the maximum length of a char field.
577 665
     */
578
    public function getCharMaxLength() : int
579 665
    {
580
        return $this->getVarcharMaxLength();
581
    }
582
583
    /**
584
     * Gets the maximum length of a varchar field.
585
     *
586
     * @return int
587 1828
     */
588
    public function getVarcharMaxLength()
589 1828
    {
590
        return 4000;
591
    }
592
593
    /**
594
     * Gets the default length of a varchar field.
595
     *
596
     * @return int
597 919
     */
598
    public function getVarcharDefaultLength()
599 919
    {
600
        return 255;
601
    }
602
603
    /**
604
     * Gets the maximum length of a binary field.
605
     *
606
     * @return int
607
     */
608
    public function getBinaryMaxLength()
609
    {
610
        return 4000;
611
    }
612
613
    /**
614
     * Gets the default length of a binary field.
615
     *
616
     * @return int
617 235
     */
618
    public function getBinaryDefaultLength()
619 235
    {
620
        return 255;
621
    }
622
623
    /**
624
     * Gets all SQL wildcard characters of the platform.
625
     *
626
     * @return string[]
627
     */
628
    public function getWildcards()
629
    {
630
        return ['%', '_'];
631
    }
632
633
    /**
634
     * Returns the regular expression operator.
635
     *
636
     * @return string
637
     *
638
     * @throws DBALException If not supported on this platform.
639 44
     */
640
    public function getRegexpExpression()
641 44
    {
642
        throw DBALException::notSupported(__METHOD__);
643
    }
644
645
    /**
646
     * Returns the global unique identifier expression.
647
     *
648
     * @deprecated Use application-generated UUIDs instead
649
     *
650
     * @return string
651
     *
652
     * @throws DBALException If not supported on this platform.
653
     */
654
    public function getGuidExpression()
655
    {
656
        throw DBALException::notSupported(__METHOD__);
657
    }
658
659
    /**
660
     * Returns the SQL snippet to get the average value of a column.
661
     *
662
     * @param string $column The column to use.
663
     *
664
     * @return string Generated SQL including an AVG aggregate function.
665
     */
666
    public function getAvgExpression($column)
667
    {
668
        return 'AVG(' . $column . ')';
669
    }
670
671
    /**
672
     * Returns the SQL snippet to get the number of rows (without a NULL value) of a column.
673
     *
674
     * If a '*' is used instead of a column the number of selected rows is returned.
675
     *
676
     * @param string|int $column The column to use.
677
     *
678
     * @return string Generated SQL including a COUNT aggregate function.
679
     */
680
    public function getCountExpression($column)
681
    {
682
        return 'COUNT(' . $column . ')';
683
    }
684
685
    /**
686
     * Returns the SQL snippet to get the highest value of a column.
687
     *
688
     * @param string $column The column to use.
689
     *
690
     * @return string Generated SQL including a MAX aggregate function.
691
     */
692
    public function getMaxExpression($column)
693
    {
694
        return 'MAX(' . $column . ')';
695
    }
696
697
    /**
698
     * Returns the SQL snippet to get the lowest value of a column.
699
     *
700
     * @param string $column The column to use.
701
     *
702
     * @return string Generated SQL including a MIN aggregate function.
703
     */
704
    public function getMinExpression($column)
705
    {
706
        return 'MIN(' . $column . ')';
707
    }
708
709
    /**
710
     * Returns the SQL snippet to get the total sum of a column.
711
     *
712
     * @param string $column The column to use.
713
     *
714
     * @return string Generated SQL including a SUM aggregate function.
715
     */
716
    public function getSumExpression($column)
717
    {
718
        return 'SUM(' . $column . ')';
719
    }
720
721
    // scalar functions
722
723
    /**
724
     * Returns the SQL snippet to get the md5 sum of a field.
725
     *
726
     * Note: Not SQL92, but common functionality.
727
     *
728
     * @param string $column
729
     *
730
     * @return string
731
     */
732
    public function getMd5Expression($column)
733
    {
734
        return 'MD5(' . $column . ')';
735
    }
736
737
    /**
738
     * Returns the SQL snippet to get the length of a text field.
739
     *
740
     * @param string $column
741
     *
742
     * @return string
743
     */
744
    public function getLengthExpression($column)
745
    {
746
        return 'LENGTH(' . $column . ')';
747
    }
748
749
    /**
750
     * Returns the SQL snippet to get the squared value of a column.
751
     *
752
     * @param string $column The column to use.
753
     *
754
     * @return string Generated SQL including an SQRT aggregate function.
755
     */
756
    public function getSqrtExpression($column)
757
    {
758
        return 'SQRT(' . $column . ')';
759
    }
760
761
    /**
762
     * Returns the SQL snippet to round a numeric field to the number of decimals specified.
763
     *
764
     * @param string $column
765
     * @param int    $decimals
766
     *
767
     * @return string
768
     */
769
    public function getRoundExpression($column, $decimals = 0)
770
    {
771
        return 'ROUND(' . $column . ', ' . $decimals . ')';
772
    }
773
774
    /**
775
     * Returns the SQL snippet to get the remainder of the division operation $expression1 / $expression2.
776
     *
777
     * @param string $expression1
778
     * @param string $expression2
779
     *
780
     * @return string
781
     */
782
    public function getModExpression($expression1, $expression2)
783
    {
784
        return 'MOD(' . $expression1 . ', ' . $expression2 . ')';
785
    }
786
787
    /**
788
     * Returns the SQL snippet to trim a string.
789
     *
790
     * @param string      $str  The expression to apply the trim to.
791
     * @param int         $mode The position of the trim (leading/trailing/both).
792
     * @param string|bool $char The char to trim, has to be quoted already. Defaults to space.
793
     *
794
     * @return string
795 684
     */
796
    public function getTrimExpression($str, $mode = TrimMode::UNSPECIFIED, $char = false)
797 684
    {
798
        $expression = '';
799 684
800
        switch ($mode) {
801 171
            case TrimMode::LEADING:
802 171
                $expression = 'LEADING ';
803
                break;
804
805 171
            case TrimMode::TRAILING:
806 171
                $expression = 'TRAILING ';
807
                break;
808
809 171
            case TrimMode::BOTH:
810 171
                $expression = 'BOTH ';
811
                break;
812
        }
813 684
814 532
        if ($char !== false) {
815
            $expression .= $char . ' ';
0 ignored issues
show
Bug introduced by
Are you sure $char of type string|true can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

815
            $expression .= /** @scrutinizer ignore-type */ $char . ' ';
Loading history...
816
        }
817 684
818 646
        if ($mode !== TrimMode::UNSPECIFIED || $char !== false) {
819
            $expression .= 'FROM ';
820
        }
821 684
822
        return 'TRIM(' . $expression . $str . ')';
823
    }
824
825
    /**
826
     * Returns the SQL snippet to trim trailing space characters from the expression.
827
     *
828
     * @param string $str Literal string or column name.
829
     *
830
     * @return string
831 22
     */
832
    public function getRtrimExpression($str)
833 22
    {
834
        return 'RTRIM(' . $str . ')';
835
    }
836
837
    /**
838
     * Returns the SQL snippet to trim leading space characters from the expression.
839
     *
840
     * @param string $str Literal string or column name.
841
     *
842
     * @return string
843 22
     */
844
    public function getLtrimExpression($str)
845 22
    {
846
        return 'LTRIM(' . $str . ')';
847
    }
848
849
    /**
850
     * Returns the SQL snippet to change all characters from the expression to uppercase,
851
     * according to the current character set mapping.
852
     *
853
     * @param string $str Literal string or column name.
854
     *
855
     * @return string
856
     */
857
    public function getUpperExpression($str)
858
    {
859
        return 'UPPER(' . $str . ')';
860
    }
861
862
    /**
863
     * Returns the SQL snippet to change all characters from the expression to lowercase,
864
     * according to the current character set mapping.
865
     *
866
     * @param string $str Literal string or column name.
867
     *
868
     * @return string
869
     */
870
    public function getLowerExpression($str)
871
    {
872
        return 'LOWER(' . $str . ')';
873
    }
874
875
    /**
876
     * Returns the SQL snippet to get the position of the first occurrence of substring $substr in string $str.
877
     *
878
     * @param string    $str      Literal string.
879
     * @param string    $substr   Literal string to find.
880
     * @param int|false $startPos Position to start at, beginning of string by default.
881
     *
882
     * @return string
883
     *
884
     * @throws DBALException If not supported on this platform.
885
     */
886
    public function getLocateExpression($str, $substr, $startPos = false)
0 ignored issues
show
Unused Code introduced by
The parameter $substr is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

886
    public function getLocateExpression($str, /** @scrutinizer ignore-unused */ $substr, $startPos = false)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $startPos is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

886
    public function getLocateExpression($str, $substr, /** @scrutinizer ignore-unused */ $startPos = false)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
887
    {
888
        throw DBALException::notSupported(__METHOD__);
889
    }
890
891
    /**
892
     * Returns the SQL snippet to get the current system date.
893
     *
894
     * @return string
895
     */
896
    public function getNowExpression()
897
    {
898
        return 'NOW()';
899
    }
900
901
    /**
902
     * Returns a SQL snippet to get a substring inside an SQL statement.
903
     *
904
     * Note: Not SQL92, but common functionality.
905
     *
906
     * SQLite only supports the 2 parameter variant of this function.
907
     *
908
     * @param string   $value  An sql string literal or column name/alias.
909
     * @param int      $from   Where to start the substring portion.
910
     * @param int|null $length The substring portion length.
911
     *
912
     * @return string
913
     */
914
    public function getSubstringExpression($value, $from, $length = null)
915
    {
916
        if ($length === null) {
917
            return 'SUBSTRING(' . $value . ' FROM ' . $from . ')';
918
        }
919
920
        return 'SUBSTRING(' . $value . ' FROM ' . $from . ' FOR ' . $length . ')';
921
    }
922
923
    /**
924
     * Returns a SQL snippet to concatenate the given expressions.
925
     *
926
     * Accepts an arbitrary number of string parameters. Each parameter must contain an expression.
927
     *
928
     * @return string
929 66
     */
930
    public function getConcatExpression()
931 66
    {
932
        return implode(' || ', func_get_args());
933
    }
934
935
    /**
936
     * Returns the SQL for a logical not.
937
     *
938
     * Example:
939
     * <code>
940
     * $q = new Doctrine_Query();
941
     * $e = $q->expr;
942
     * $q->select('*')->from('table')
943
     *   ->where($e->eq('id', $e->not('null'));
944
     * </code>
945
     *
946
     * @param string $expression
947
     *
948
     * @return string The logical expression.
949
     */
950
    public function getNotExpression($expression)
951
    {
952
        return 'NOT(' . $expression . ')';
953
    }
954
955
    /**
956
     * Returns the SQL that checks if an expression is null.
957
     *
958
     * @param string $expression The expression that should be compared to null.
959
     *
960
     * @return string The logical expression.
961 88
     */
962
    public function getIsNullExpression($expression)
963 88
    {
964
        return $expression . ' IS NULL';
965
    }
966
967
    /**
968
     * Returns the SQL that checks if an expression is not null.
969
     *
970
     * @param string $expression The expression that should be compared to null.
971
     *
972
     * @return string The logical expression.
973
     */
974
    public function getIsNotNullExpression($expression)
975
    {
976
        return $expression . ' IS NOT NULL';
977
    }
978
979
    /**
980
     * Returns the SQL that checks if an expression evaluates to a value between two values.
981
     *
982
     * The parameter $expression is checked if it is between $value1 and $value2.
983
     *
984
     * Note: There is a slight difference in the way BETWEEN works on some databases.
985
     * http://www.w3schools.com/sql/sql_between.asp. If you want complete database
986
     * independence you should avoid using between().
987
     *
988
     * @param string $expression The value to compare to.
989
     * @param string $value1     The lower value to compare with.
990
     * @param string $value2     The higher value to compare with.
991
     *
992
     * @return string The logical expression.
993
     */
994
    public function getBetweenExpression($expression, $value1, $value2)
995
    {
996
        return $expression . ' BETWEEN ' . $value1 . ' AND ' . $value2;
997
    }
998
999
    /**
1000
     * Returns the SQL to get the arccosine of a value.
1001
     *
1002
     * @param string $value
1003
     *
1004
     * @return string
1005
     */
1006
    public function getAcosExpression($value)
1007
    {
1008
        return 'ACOS(' . $value . ')';
1009
    }
1010
1011
    /**
1012
     * Returns the SQL to get the sine of a value.
1013
     *
1014
     * @param string $value
1015
     *
1016
     * @return string
1017
     */
1018
    public function getSinExpression($value)
1019
    {
1020
        return 'SIN(' . $value . ')';
1021
    }
1022
1023
    /**
1024
     * Returns the SQL to get the PI value.
1025
     *
1026
     * @return string
1027
     */
1028
    public function getPiExpression()
1029
    {
1030
        return 'PI()';
1031
    }
1032
1033
    /**
1034
     * Returns the SQL to get the cosine of a value.
1035
     *
1036
     * @param string $value
1037
     *
1038
     * @return string
1039
     */
1040
    public function getCosExpression($value)
1041
    {
1042
        return 'COS(' . $value . ')';
1043
    }
1044
1045
    /**
1046
     * Returns the SQL to calculate the difference in days between the two passed dates.
1047
     *
1048
     * Computes diff = date1 - date2.
1049
     *
1050
     * @param string $date1
1051
     * @param string $date2
1052
     *
1053
     * @return string
1054
     *
1055
     * @throws DBALException If not supported on this platform.
1056
     */
1057
    public function getDateDiffExpression($date1, $date2)
0 ignored issues
show
Unused Code introduced by
The parameter $date1 is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

1057
    public function getDateDiffExpression(/** @scrutinizer ignore-unused */ $date1, $date2)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $date2 is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

1057
    public function getDateDiffExpression($date1, /** @scrutinizer ignore-unused */ $date2)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1058
    {
1059
        throw DBALException::notSupported(__METHOD__);
1060
    }
1061
1062
    /**
1063
     * Returns the SQL to add the number of given seconds to a date.
1064
     *
1065
     * @param string $date
1066
     * @param int    $seconds
1067
     *
1068
     * @return string
1069
     *
1070
     * @throws DBALException If not supported on this platform.
1071 66
     */
1072
    public function getDateAddSecondsExpression($date, $seconds)
1073 66
    {
1074
        return $this->getDateArithmeticIntervalExpression($date, '+', $seconds, DateIntervalUnit::SECOND);
1075
    }
1076
1077
    /**
1078
     * Returns the SQL to subtract the number of given seconds from a date.
1079
     *
1080
     * @param string $date
1081
     * @param int    $seconds
1082
     *
1083
     * @return string
1084
     *
1085
     * @throws DBALException If not supported on this platform.
1086 66
     */
1087
    public function getDateSubSecondsExpression($date, $seconds)
1088 66
    {
1089
        return $this->getDateArithmeticIntervalExpression($date, '-', $seconds, DateIntervalUnit::SECOND);
1090
    }
1091
1092
    /**
1093
     * Returns the SQL to add the number of given minutes to a date.
1094
     *
1095
     * @param string $date
1096
     * @param int    $minutes
1097
     *
1098
     * @return string
1099
     *
1100
     * @throws DBALException If not supported on this platform.
1101 66
     */
1102
    public function getDateAddMinutesExpression($date, $minutes)
1103 66
    {
1104
        return $this->getDateArithmeticIntervalExpression($date, '+', $minutes, DateIntervalUnit::MINUTE);
1105
    }
1106
1107
    /**
1108
     * Returns the SQL to subtract the number of given minutes from a date.
1109
     *
1110
     * @param string $date
1111
     * @param int    $minutes
1112
     *
1113
     * @return string
1114
     *
1115
     * @throws DBALException If not supported on this platform.
1116 66
     */
1117
    public function getDateSubMinutesExpression($date, $minutes)
1118 66
    {
1119
        return $this->getDateArithmeticIntervalExpression($date, '-', $minutes, DateIntervalUnit::MINUTE);
1120
    }
1121
1122
    /**
1123
     * Returns the SQL to add the number of given hours to a date.
1124
     *
1125
     * @param string $date
1126
     * @param int    $hours
1127
     *
1128
     * @return string
1129
     *
1130
     * @throws DBALException If not supported on this platform.
1131 66
     */
1132
    public function getDateAddHourExpression($date, $hours)
1133 66
    {
1134
        return $this->getDateArithmeticIntervalExpression($date, '+', $hours, DateIntervalUnit::HOUR);
1135
    }
1136
1137
    /**
1138
     * Returns the SQL to subtract the number of given hours to a date.
1139
     *
1140
     * @param string $date
1141
     * @param int    $hours
1142
     *
1143
     * @return string
1144
     *
1145
     * @throws DBALException If not supported on this platform.
1146 66
     */
1147
    public function getDateSubHourExpression($date, $hours)
1148 66
    {
1149
        return $this->getDateArithmeticIntervalExpression($date, '-', $hours, DateIntervalUnit::HOUR);
1150
    }
1151
1152
    /**
1153
     * Returns the SQL to add the number of given days to a date.
1154
     *
1155
     * @param string $date
1156
     * @param int    $days
1157
     *
1158
     * @return string
1159
     *
1160
     * @throws DBALException If not supported on this platform.
1161 110
     */
1162
    public function getDateAddDaysExpression($date, $days)
1163 110
    {
1164
        return $this->getDateArithmeticIntervalExpression($date, '+', $days, DateIntervalUnit::DAY);
1165
    }
1166
1167
    /**
1168
     * Returns the SQL to subtract the number of given days to a date.
1169
     *
1170
     * @param string $date
1171
     * @param int    $days
1172
     *
1173
     * @return string
1174
     *
1175
     * @throws DBALException If not supported on this platform.
1176 67
     */
1177
    public function getDateSubDaysExpression($date, $days)
1178 67
    {
1179
        return $this->getDateArithmeticIntervalExpression($date, '-', $days, DateIntervalUnit::DAY);
1180
    }
1181
1182
    /**
1183
     * Returns the SQL to add the number of given weeks to a date.
1184
     *
1185
     * @param string $date
1186
     * @param int    $weeks
1187
     *
1188
     * @return string
1189
     *
1190
     * @throws DBALException If not supported on this platform.
1191 66
     */
1192
    public function getDateAddWeeksExpression($date, $weeks)
1193 66
    {
1194
        return $this->getDateArithmeticIntervalExpression($date, '+', $weeks, DateIntervalUnit::WEEK);
1195
    }
1196
1197
    /**
1198
     * Returns the SQL to subtract the number of given weeks from a date.
1199
     *
1200
     * @param string $date
1201
     * @param int    $weeks
1202
     *
1203
     * @return string
1204
     *
1205
     * @throws DBALException If not supported on this platform.
1206 66
     */
1207
    public function getDateSubWeeksExpression($date, $weeks)
1208 66
    {
1209
        return $this->getDateArithmeticIntervalExpression($date, '-', $weeks, DateIntervalUnit::WEEK);
1210
    }
1211
1212
    /**
1213
     * Returns the SQL to add the number of given months to a date.
1214
     *
1215
     * @param string $date
1216
     * @param int    $months
1217
     *
1218
     * @return string
1219
     *
1220
     * @throws DBALException If not supported on this platform.
1221 66
     */
1222
    public function getDateAddMonthExpression($date, $months)
1223 66
    {
1224
        return $this->getDateArithmeticIntervalExpression($date, '+', $months, DateIntervalUnit::MONTH);
1225
    }
1226
1227
    /**
1228
     * Returns the SQL to subtract the number of given months to a date.
1229
     *
1230
     * @param string $date
1231
     * @param int    $months
1232
     *
1233
     * @return string
1234
     *
1235
     * @throws DBALException If not supported on this platform.
1236 66
     */
1237
    public function getDateSubMonthExpression($date, $months)
1238 66
    {
1239
        return $this->getDateArithmeticIntervalExpression($date, '-', $months, DateIntervalUnit::MONTH);
1240
    }
1241
1242
    /**
1243
     * Returns the SQL to add the number of given quarters to a date.
1244
     *
1245
     * @param string $date
1246
     * @param int    $quarters
1247
     *
1248
     * @return string
1249
     *
1250
     * @throws DBALException If not supported on this platform.
1251 66
     */
1252
    public function getDateAddQuartersExpression($date, $quarters)
1253 66
    {
1254
        return $this->getDateArithmeticIntervalExpression($date, '+', $quarters, DateIntervalUnit::QUARTER);
1255
    }
1256
1257
    /**
1258
     * Returns the SQL to subtract the number of given quarters from a date.
1259
     *
1260
     * @param string $date
1261
     * @param int    $quarters
1262
     *
1263
     * @return string
1264
     *
1265
     * @throws DBALException If not supported on this platform.
1266 66
     */
1267
    public function getDateSubQuartersExpression($date, $quarters)
1268 66
    {
1269
        return $this->getDateArithmeticIntervalExpression($date, '-', $quarters, DateIntervalUnit::QUARTER);
1270
    }
1271
1272
    /**
1273
     * Returns the SQL to add the number of given years to a date.
1274
     *
1275
     * @param string $date
1276
     * @param int    $years
1277
     *
1278
     * @return string
1279
     *
1280
     * @throws DBALException If not supported on this platform.
1281 66
     */
1282
    public function getDateAddYearsExpression($date, $years)
1283 66
    {
1284
        return $this->getDateArithmeticIntervalExpression($date, '+', $years, DateIntervalUnit::YEAR);
1285
    }
1286
1287
    /**
1288
     * Returns the SQL to subtract the number of given years from a date.
1289
     *
1290
     * @param string $date
1291
     * @param int    $years
1292
     *
1293
     * @return string
1294
     *
1295
     * @throws DBALException If not supported on this platform.
1296 66
     */
1297
    public function getDateSubYearsExpression($date, $years)
1298 66
    {
1299
        return $this->getDateArithmeticIntervalExpression($date, '-', $years, DateIntervalUnit::YEAR);
1300
    }
1301
1302
    /**
1303
     * Returns the SQL for a date arithmetic expression.
1304
     *
1305
     * @param string $date     The column or literal representing a date to perform the arithmetic operation on.
1306
     * @param string $operator The arithmetic operator (+ or -).
1307
     * @param int    $interval The interval that shall be calculated into the date.
1308
     * @param string $unit     The unit of the interval that shall be calculated into the date.
1309
     *                         One of the DATE_INTERVAL_UNIT_* constants.
1310
     *
1311
     * @return string
1312
     *
1313
     * @throws DBALException If not supported on this platform.
1314
     */
1315
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
0 ignored issues
show
Unused Code introduced by
The parameter $unit is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

1315
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, /** @scrutinizer ignore-unused */ $unit)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $interval is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

1315
    protected function getDateArithmeticIntervalExpression($date, $operator, /** @scrutinizer ignore-unused */ $interval, $unit)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $operator is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

1315
    protected function getDateArithmeticIntervalExpression($date, /** @scrutinizer ignore-unused */ $operator, $interval, $unit)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1316
    {
1317
        throw DBALException::notSupported(__METHOD__);
1318
    }
1319
1320
    /**
1321
     * Returns the SQL bit AND comparison expression.
1322
     *
1323
     * @param string $value1
1324
     * @param string $value2
1325
     *
1326
     * @return string
1327 196
     */
1328
    public function getBitAndComparisonExpression($value1, $value2)
1329 196
    {
1330
        return '(' . $value1 . ' & ' . $value2 . ')';
1331
    }
1332
1333
    /**
1334
     * Returns the SQL bit OR comparison expression.
1335
     *
1336
     * @param string $value1
1337
     * @param string $value2
1338
     *
1339
     * @return string
1340 196
     */
1341
    public function getBitOrComparisonExpression($value1, $value2)
1342 196
    {
1343
        return '(' . $value1 . ' | ' . $value2 . ')';
1344
    }
1345
1346
    /**
1347
     * Returns the FOR UPDATE expression.
1348
     *
1349
     * @return string
1350 36
     */
1351
    public function getForUpdateSQL()
1352 36
    {
1353
        return 'FOR UPDATE';
1354
    }
1355
1356
    /**
1357
     * Honors that some SQL vendors such as MsSql use table hints for locking instead of the ANSI SQL FOR UPDATE specification.
1358
     *
1359
     * @param string   $fromClause The FROM clause to append the hint for the given lock mode to.
1360
     * @param int|null $lockMode   One of the Doctrine\DBAL\LockMode::* constants. If null is given, nothing will
1361
     *                             be appended to the FROM clause.
1362
     *
1363
     * @return string
1364 38
     */
1365
    public function appendLockHint($fromClause, $lockMode)
0 ignored issues
show
Unused Code introduced by
The parameter $lockMode is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

1365
    public function appendLockHint($fromClause, /** @scrutinizer ignore-unused */ $lockMode)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1366 38
    {
1367
        return $fromClause;
1368
    }
1369
1370
    /**
1371
     * Returns the SQL snippet to append to any SELECT statement which locks rows in shared read lock.
1372
     *
1373
     * This defaults to the ANSI SQL "FOR UPDATE", which is an exclusive lock (Write). Some database
1374
     * vendors allow to lighten this constraint up to be a real read lock.
1375
     *
1376
     * @return string
1377
     */
1378
    public function getReadLockSQL()
1379
    {
1380
        return $this->getForUpdateSQL();
1381
    }
1382
1383
    /**
1384
     * Returns the SQL snippet to append to any SELECT statement which obtains an exclusive lock on the rows.
1385
     *
1386
     * The semantics of this lock mode should equal the SELECT .. FOR UPDATE of the ANSI SQL standard.
1387
     *
1388
     * @return string
1389 42
     */
1390
    public function getWriteLockSQL()
1391 42
    {
1392
        return $this->getForUpdateSQL();
1393
    }
1394
1395
    /**
1396
     * Returns the SQL snippet to drop an existing database.
1397
     *
1398
     * @param string $database The name of the database that should be dropped.
1399
     *
1400
     * @return string
1401 54
     */
1402
    public function getDropDatabaseSQL($database)
1403 54
    {
1404
        return 'DROP DATABASE ' . $database;
1405
    }
1406
1407
    /**
1408
     * Returns the SQL snippet to drop an existing table.
1409
     *
1410
     * @param Table|string $table
1411
     *
1412
     * @return string
1413
     *
1414
     * @throws InvalidArgumentException
1415 3752
     */
1416
    public function getDropTableSQL($table)
1417 3752
    {
1418
        $tableArg = $table;
1419 3752
1420 321
        if ($table instanceof Table) {
1421
            $table = $table->getQuotedName($this);
1422
        }
1423 3752
1424
        if (! is_string($table)) {
0 ignored issues
show
introduced by
The condition is_string($table) is always true.
Loading history...
1425
            throw new InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
1426
        }
1427 3752
1428 220
        if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaDropTable)) {
1429 220
            $eventArgs = new SchemaDropTableEventArgs($tableArg, $this);
1430
            $this->_eventManager->dispatchEvent(Events::onSchemaDropTable, $eventArgs);
1431 220
1432
            if ($eventArgs->isDefaultPrevented()) {
1433
                $sql = $eventArgs->getSql();
1434
1435
                if ($sql === null) {
1436
                    throw new UnexpectedValueException('Default implementation of DROP TABLE was overridden with NULL');
1437
                }
1438
1439
                return $sql;
1440
            }
1441
        }
1442 3752
1443
        return 'DROP TABLE ' . $table;
1444
    }
1445
1446
    /**
1447
     * Returns the SQL to safely drop a temporary table WITHOUT implicitly committing an open transaction.
1448
     *
1449
     * @param Table|string $table
1450
     *
1451
     * @return string
1452 18
     */
1453
    public function getDropTemporaryTableSQL($table)
1454 18
    {
1455
        return $this->getDropTableSQL($table);
1456
    }
1457
1458
    /**
1459
     * Returns the SQL to drop an index from a table.
1460
     *
1461
     * @param Index|string $index
1462
     * @param Table|string $table
1463
     *
1464
     * @return string
1465
     *
1466
     * @throws InvalidArgumentException
1467 133
     */
1468
    public function getDropIndexSQL($index, $table = null)
1469 133
    {
1470 125
        if ($index instanceof Index) {
1471 8
            $index = $index->getQuotedName($this);
1472
        } elseif (! is_string($index)) {
0 ignored issues
show
introduced by
The condition is_string($index) is always true.
Loading history...
1473
            throw new InvalidArgumentException('AbstractPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
1474
        }
1475 133
1476
        return 'DROP INDEX ' . $index;
1477
    }
1478
1479
    /**
1480
     * Returns the SQL to drop a constraint.
1481
     *
1482
     * @param Constraint|string $constraint
1483
     * @param Table|string      $table
1484
     *
1485
     * @return string
1486 542
     */
1487
    public function getDropConstraintSQL($constraint, $table)
1488 542
    {
1489 449
        if (! $constraint instanceof Constraint) {
1490
            $constraint = new Identifier($constraint);
1491
        }
1492 542
1493 542
        if (! $table instanceof Table) {
1494
            $table = new Identifier($table);
1495
        }
1496 542
1497 542
        $constraint = $constraint->getQuotedName($this);
1498
        $table      = $table->getQuotedName($this);
1499 542
1500
        return 'ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $constraint;
1501
    }
1502
1503
    /**
1504
     * Returns the SQL to drop a foreign key.
1505
     *
1506
     * @param ForeignKeyConstraint|string $foreignKey
1507
     * @param Table|string                $table
1508
     *
1509
     * @return string
1510 351
     */
1511
    public function getDropForeignKeySQL($foreignKey, $table)
1512 351
    {
1513 110
        if (! $foreignKey instanceof ForeignKeyConstraint) {
1514
            $foreignKey = new Identifier($foreignKey);
1515
        }
1516 351
1517 351
        if (! $table instanceof Table) {
1518
            $table = new Identifier($table);
1519
        }
1520 351
1521 351
        $foreignKey = $foreignKey->getQuotedName($this);
1522
        $table      = $table->getQuotedName($this);
1523 351
1524
        return 'ALTER TABLE ' . $table . ' DROP FOREIGN KEY ' . $foreignKey;
1525
    }
1526
1527
    /**
1528
     * Returns the SQL statement(s) to create a table with the specified name, columns and constraints
1529
     * on this platform.
1530
     *
1531
     * @param int $createFlags
1532
     *
1533
     * @return string[] The sequence of SQL statements.
1534
     *
1535
     * @throws DBALException
1536
     * @throws InvalidArgumentException
1537 7215
     */
1538
    public function getCreateTableSQL(Table $table, $createFlags = self::CREATE_INDEXES)
1539 7215
    {
1540
        if (! is_int($createFlags)) {
0 ignored issues
show
introduced by
The condition is_int($createFlags) is always true.
Loading history...
1541
            throw new InvalidArgumentException('Second argument of AbstractPlatform::getCreateTableSQL() has to be integer.');
1542
        }
1543 7215
1544 220
        if (count($table->getColumns()) === 0) {
1545
            throw DBALException::noColumnsSpecifiedForTable($table->getName());
1546
        }
1547 6995
1548 6995
        $tableName                    = $table->getQuotedName($this);
1549 6995
        $options                      = $table->getOptions();
1550 6995
        $options['uniqueConstraints'] = [];
1551 6995
        $options['indexes']           = [];
1552
        $options['primary']           = [];
1553 6995
1554 6731
        if (($createFlags & self::CREATE_INDEXES) > 0) {
1555
            foreach ($table->getIndexes() as $index) {
1556 4507
                /** @var $index Index */
1557 3542
                if (! $index->isPrimary()) {
1558 3542
                    $options['indexes'][$index->getQuotedName($this)] = $index;
1559
1560 1382
                    continue;
1561
                }
1562
1563
                $options['primary']       = $index->getQuotedColumns($this);
1564
                $options['primary_index'] = $index;
1565 6995
            }
1566 6995
1567
            foreach ($table->getUniqueConstraints() as $uniqueConstraint) {
1568 6995
                /** @var UniqueConstraint $uniqueConstraint */
1569 6995
                $options['uniqueConstraints'][$uniqueConstraint->getQuotedName($this)] = $uniqueConstraint;
1570 220
            }
1571 220
        }
1572
1573 220
        if (($createFlags & self::CREATE_FOREIGNKEYS) > 0) {
1574
            $options['foreignKeys'] = array();
1575 220
1576
            foreach ($table->getForeignKeys() as $fkConstraint) {
1577
                $options['foreignKeys'][] = $fkConstraint;
1578
            }
1579
        }
1580 6995
1581 6995
        $columnSql = [];
1582 6995
        $columns   = [];
1583 6995
1584
        foreach ($table->getColumns() as $column) {
1585 6995
            if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaCreateTableColumn)) {
1586 2561
                $eventArgs = new SchemaCreateTableColumnEventArgs($column, $table, $this);
1587
1588
                $this->_eventManager->dispatchEvent(Events::onSchemaCreateTableColumn, $eventArgs);
1589 6995
1590 3278
                $columnSql = array_merge($columnSql, $eventArgs->getSql());
1591
1592
                if ($eventArgs->isDefaultPrevented()) {
1593 6995
                    continue;
1594
                }
1595
            }
1596 6995
1597 4309
            $columnData            = $column->toArray();
1598 4309
            $columnData['name']    = $column->getQuotedName($this);
1599 603
            $columnData['version'] = $column->hasPlatformOption('version') ? $column->getPlatformOption('version') : false;
1600
            $columnData['comment'] = $this->getColumnComment($column);
1601
1602
            if ($columnData['type'] instanceof Types\StringType && $columnData['length'] === null) {
1603 6995
                $columnData['length'] = 255;
1604 220
            }
1605 220
1606
            if (in_array($column->getName(), $options['primary'], true)) {
1607 220
                $columnData['primary'] = true;
1608
            }
1609
1610
            $columns[$columnData['name']] = $columnData;
1611
        }
1612 6995
1613 6995
        if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaCreateTable)) {
1614 2543
            $eventArgs = new SchemaCreateTableEventArgs($table, $columns, $options, $this);
1615 51
1616
            $this->_eventManager->dispatchEvent(Events::onSchemaCreateTable, $eventArgs);
1617 2543
1618 2543
            if ($eventArgs->isDefaultPrevented()) {
1619
                return array_merge($eventArgs->getSql(), $columnSql);
1620 2543
            }
1621 2389
        }
1622
1623
        $sql = $this->_getCreateTableSQL($tableName, $columns, $options);
1624 440
        if ($this->supportsCommentOnStatement()) {
1625
            if ($table->hasOption('comment')) {
1626
                $sql[] = $this->getCommentOnTableSQL($tableName, $table->getOption('comment'));
1627
            }
1628 6995
1629
            foreach ($table->getColumns() as $column) {
1630
                $comment = $this->getColumnComment($column);
1631 51
1632
                if ($comment === null || $comment === '') {
1633 51
                    continue;
1634
                }
1635 51
1636 3
                $sql[] = $this->getCommentOnColumnSQL($tableName, $column->getQuotedName($this), $comment);
1637 51
            }
1638 51
        }
1639
1640
        return array_merge($sql, $columnSql);
1641
    }
1642
1643
    protected function getCommentOnTableSQL(string $tableName, ?string $comment) : string
1644
    {
1645
        $tableName = new Identifier($tableName);
1646
1647
        return sprintf(
1648
            'COMMENT ON TABLE %s IS %s',
1649 681
            $tableName->getQuotedName($this),
1650
            $this->quoteStringLiteral((string) $comment)
1651 681
        );
1652 681
    }
1653
1654 681
    /**
1655 60
     * @param string      $tableName
1656 681
     * @param string      $columnName
1657 681
     * @param string|null $comment
1658 681
     *
1659
     * @return string
1660
     */
1661
    public function getCommentOnColumnSQL($tableName, $columnName, $comment)
1662
    {
1663
        $tableName  = new Identifier($tableName);
1664
        $columnName = new Identifier($columnName);
1665
1666
        return sprintf(
1667
            'COMMENT ON COLUMN %s.%s IS %s',
1668
            $tableName->getQuotedName($this),
1669
            $columnName->getQuotedName($this),
1670
            $this->quoteStringLiteral((string) $comment)
1671 1126
        );
1672
    }
1673 1126
1674 132
    /**
1675
     * Returns the SQL to create inline comment on a column.
1676
     *
1677 994
     * @param string $comment
1678
     *
1679
     * @return string
1680
     *
1681
     * @throws DBALException If not supported on this platform.
1682
     */
1683
    public function getInlineColumnCommentSQL($comment)
1684
    {
1685
        if (! $this->supportsInlineColumnComments()) {
1686
            throw DBALException::notSupported(__METHOD__);
1687
        }
1688
1689 784
        return 'COMMENT ' . $this->quoteStringLiteral($comment);
1690
    }
1691 784
1692
    /**
1693 784
     * Returns the SQL used to create a table.
1694
     *
1695
     * @param string    $tableName
1696
     * @param mixed[][] $columns
1697
     * @param mixed[]   $options
1698
     *
1699 784
     * @return string[]
1700 399
     */
1701
    protected function _getCreateTableSQL($tableName, array $columns, array $options = [])
1702
    {
1703 784
        $columnListSql = $this->getColumnDeclarationListSQL($columns);
1704
1705
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
1706
            foreach ($options['uniqueConstraints'] as $name => $definition) {
1707
                $columnListSql .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
1708
            }
1709 784
        }
1710
1711 784
        if (isset($options['primary']) && ! empty($options['primary'])) {
1712 784
            $columnListSql .= ', PRIMARY KEY(' . implode(', ', array_unique(array_values($options['primary']))) . ')';
1713 22
        }
1714
1715 784
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
1716
            foreach ($options['indexes'] as $index => $definition) {
1717 784
                $columnListSql .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
1718
            }
1719 784
        }
1720 333
1721 79
        $query = 'CREATE TABLE ' . $tableName . ' (' . $columnListSql;
1722
1723
        $check = $this->getCheckDeclarationSQL($columns);
1724
        if (! empty($check)) {
1725 784
            $query .= ', ' . $check;
1726
        }
1727
        $query .= ')';
1728
1729
        $sql = [$query];
1730
1731 36
        if (isset($options['foreignKeys'])) {
1732
            foreach ((array) $options['foreignKeys'] as $definition) {
1733 36
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
1734
            }
1735
        }
1736
1737
        return $sql;
1738
    }
1739
1740
    /**
1741
     * @return string
1742
     */
1743
    public function getCreateTemporaryTableSnippetSQL()
1744
    {
1745
        return 'CREATE TEMPORARY TABLE';
1746
    }
1747
1748
    /**
1749
     * Returns the SQL to create a sequence on this platform.
1750
     *
1751
     * @return string
1752
     *
1753
     * @throws DBALException If not supported on this platform.
1754
     */
1755
    public function getCreateSequenceSQL(Sequence $sequence)
0 ignored issues
show
Unused Code introduced by
The parameter $sequence is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

1755
    public function getCreateSequenceSQL(/** @scrutinizer ignore-unused */ Sequence $sequence)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1756
    {
1757
        throw DBALException::notSupported(__METHOD__);
1758
    }
1759
1760
    /**
1761
     * Returns the SQL to change a sequence on this platform.
1762
     *
1763
     * @return string
1764
     *
1765
     * @throws DBALException If not supported on this platform.
1766
     */
1767
    public function getAlterSequenceSQL(Sequence $sequence)
0 ignored issues
show
Unused Code introduced by
The parameter $sequence is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

1767
    public function getAlterSequenceSQL(/** @scrutinizer ignore-unused */ Sequence $sequence)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1768
    {
1769 266
        throw DBALException::notSupported(__METHOD__);
1770
    }
1771 266
1772
    /**
1773
     * Returns the SQL to create a constraint on a table on this platform.
1774
     *
1775 266
     * @param Table|string $table
1776
     *
1777 266
     * @return string
1778
     *
1779 266
     * @throws InvalidArgumentException
1780 266
     */
1781 266
    public function getCreateConstraintSQL(Constraint $constraint, $table)
1782 266
    {
1783 176
        if ($table instanceof Table) {
1784 176
            $table = $table->getQuotedName($this);
1785
        }
1786
1787 266
        $query = 'ALTER TABLE ' . $table . ' ADD CONSTRAINT ' . $constraint->getQuotedName($this);
1788
1789
        $columnList = '(' . implode(', ', $constraint->getQuotedColumns($this)) . ')';
1790 176
1791 176
        $referencesClause = '';
1792
        if ($constraint instanceof Index) {
1793 176
            if ($constraint->isPrimary()) {
1794 176
                $query .= ' PRIMARY KEY';
1795
            } elseif ($constraint->isUnique()) {
1796 266
                $query .= ' UNIQUE';
1797
            } else {
1798 266
                throw new InvalidArgumentException(
1799
                    'Can only create primary or unique constraints, no common indexes with getCreateConstraintSQL().'
1800
                );
1801
            }
1802
        } elseif ($constraint instanceof ForeignKeyConstraint) {
1803
            $query .= ' FOREIGN KEY';
1804
1805
            $referencesClause = ' REFERENCES ' . $constraint->getQuotedForeignTableName($this) .
1806
                ' (' . implode(', ', $constraint->getQuotedForeignColumns($this)) . ')';
1807
        }
1808
        $query .= ' ' . $columnList . $referencesClause;
1809
1810 2209
        return $query;
1811
    }
1812 2209
1813 22
    /**
1814
     * Returns the SQL to create an index on a table on this platform.
1815 2209
     *
1816 2209
     * @param Table|string $table The name of the table on which the index is to be created.
1817
     *
1818 2209
     * @return string
1819
     *
1820
     * @throws InvalidArgumentException
1821
     */
1822 2209
    public function getCreateIndexSQL(Index $index, $table)
1823 396
    {
1824
        if ($table instanceof Table) {
1825
            $table = $table->getQuotedName($this);
1826 1835
        }
1827 1835
        $name    = $index->getQuotedName($this);
1828
        $columns = $index->getColumns();
1829 1835
1830
        if (count($columns) === 0) {
1831
            throw new InvalidArgumentException("Incomplete definition. 'columns' required.");
1832
        }
1833
1834
        if ($index->isPrimary()) {
1835
            return $this->getCreatePrimaryKeySQL($index, $table);
1836
        }
1837 2833
1838
        $query  = 'CREATE ' . $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name . ' ON ' . $table;
1839 2833
        $query .= ' (' . $this->getIndexFieldDeclarationListSQL($index) . ')' . $this->getPartialIndexSQL($index);
1840 49
1841
        return $query;
1842
    }
1843 2784
1844
    /**
1845
     * Adds condition for partial index.
1846
     *
1847
     * @return string
1848
     */
1849
    protected function getPartialIndexSQL(Index $index)
1850
    {
1851 1025
        if ($this->supportsPartialIndexes() && $index->hasOption('where')) {
1852
            return ' WHERE ' . $index->getOption('where');
1853 1025
        }
1854
1855
        return '';
1856
    }
1857
1858
    /**
1859
     * Adds additional flags for index generation.
1860
     *
1861
     * @return string
1862
     */
1863 374
    protected function getCreateIndexSQLFlags(Index $index)
1864
    {
1865 374
        return $index->isUnique() ? 'UNIQUE ' : '';
1866
    }
1867
1868
    /**
1869 374
     * Returns the SQL to create an unnamed primary key constraint.
1870
     *
1871
     * @param Table|string $table
1872
     *
1873
     * @return string
1874
     */
1875
    public function getCreatePrimaryKeySQL(Index $index, $table)
1876
    {
1877
        if ($table instanceof Table) {
1878
            $table = $table->getQuotedName($this);
1879
        }
1880
1881 154
        return 'ALTER TABLE ' . $table . ' ADD PRIMARY KEY (' . $this->getIndexFieldDeclarationListSQL($index) . ')';
1882
    }
1883 154
1884
    /**
1885
     * Returns the SQL to create a named schema.
1886
     *
1887
     * @param string $schemaName
1888
     *
1889
     * @return string
1890
     *
1891
     * @throws DBALException If not supported on this platform.
1892
     */
1893
    public function getCreateSchemaSQL($schemaName)
1894
    {
1895
        throw DBALException::notSupported(__METHOD__);
1896
    }
1897
1898
    /**
1899 5001
     * Quotes a string so that it can be safely used as a table or column name,
1900
     * even if it is a reserved word of the platform. This also detects identifier
1901 5001
     * chains separated by dot and quotes them independently.
1902 238
     *
1903
     * NOTE: Just because you CAN use quoted identifiers doesn't mean
1904 238
     * you SHOULD use them. In general, they end up causing way more
1905
     * problems than they solve.
1906
     *
1907 5001
     * @param string $str The identifier name to be quoted.
1908
     *
1909
     * @return string The quoted identifier string.
1910
     */
1911
    public function quoteIdentifier($str)
1912
    {
1913
        if (strpos($str, '.') !== false) {
1914
            $parts = array_map([$this, 'quoteSingleIdentifier'], explode('.', $str));
1915
1916
            return implode('.', $parts);
1917 8408
        }
1918
1919 8408
        return $this->quoteSingleIdentifier($str);
1920
    }
1921 8408
1922
    /**
1923
     * Quotes a single identifier (no dot chain separation).
1924
     *
1925
     * @param string $str The identifier name to be quoted.
1926
     *
1927
     * @return string The quoted identifier string.
1928
     */
1929
    public function quoteSingleIdentifier($str)
1930
    {
1931
        $c = $this->getIdentifierQuoteCharacter();
1932 1259
1933
        return $c . str_replace($c, $c . $c, $str) . $c;
1934 1259
    }
1935 22
1936
    /**
1937
     * Returns the SQL to create a new foreign key.
1938 1259
     *
1939
     * @param ForeignKeyConstraint $foreignKey The foreign key constraint.
1940
     * @param Table|string         $table      The name of the table on which the foreign key is to be created.
1941
     *
1942
     * @return string
1943
     */
1944
    public function getCreateForeignKeySQL(ForeignKeyConstraint $foreignKey, $table)
1945
    {
1946
        if ($table instanceof Table) {
1947
            $table = $table->getQuotedName($this);
1948
        }
1949
1950
        return 'ALTER TABLE ' . $table . ' ADD ' . $this->getForeignKeyDeclarationSQL($foreignKey);
1951
    }
1952
1953
    /**
1954
     * Gets the SQL statements for altering an existing table.
1955
     *
1956
     * This method returns an array of SQL statements, since some platforms need several statements.
1957
     *
1958
     * @return string[]
1959
     *
1960 1224
     * @throws DBALException If not supported on this platform.
1961
     */
1962 1224
    public function getAlterTableSQL(TableDiff $diff)
1963 968
    {
1964
        throw DBALException::notSupported(__METHOD__);
1965
    }
1966 256
1967 36
    /**
1968
     * @param mixed[] $columnSql
1969
     *
1970 220
     * @return bool
1971 220
     */
1972
    protected function onSchemaAlterTableAddColumn(Column $column, TableDiff $diff, &$columnSql)
1973 220
    {
1974
        if ($this->_eventManager === null) {
1975 220
            return false;
1976
        }
1977
1978
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableAddColumn)) {
1979
            return false;
1980
        }
1981
1982
        $eventArgs = new SchemaAlterTableAddColumnEventArgs($column, $diff, $this);
1983 864
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableAddColumn, $eventArgs);
1984
1985 864
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
1986 616
1987
        return $eventArgs->isDefaultPrevented();
1988
    }
1989 248
1990 28
    /**
1991
     * @param string[] $columnSql
1992
     *
1993 220
     * @return bool
1994 220
     */
1995
    protected function onSchemaAlterTableRemoveColumn(Column $column, TableDiff $diff, &$columnSql)
1996 220
    {
1997
        if ($this->_eventManager === null) {
1998 220
            return false;
1999
        }
2000
2001
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableRemoveColumn)) {
2002
            return false;
2003
        }
2004
2005
        $eventArgs = new SchemaAlterTableRemoveColumnEventArgs($column, $diff, $this);
2006 2499
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableRemoveColumn, $eventArgs);
2007
2008 2499
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
2009 1958
2010
        return $eventArgs->isDefaultPrevented();
2011
    }
2012 541
2013 321
    /**
2014
     * @param string[] $columnSql
2015
     *
2016 220
     * @return bool
2017 220
     */
2018
    protected function onSchemaAlterTableChangeColumn(ColumnDiff $columnDiff, TableDiff $diff, &$columnSql)
2019 220
    {
2020
        if ($this->_eventManager === null) {
2021 220
            return false;
2022
        }
2023
2024
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableChangeColumn)) {
2025
            return false;
2026
        }
2027
2028
        $eventArgs = new SchemaAlterTableChangeColumnEventArgs($columnDiff, $diff, $this);
2029
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableChangeColumn, $eventArgs);
2030 949
2031
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
2032 949
2033 704
        return $eventArgs->isDefaultPrevented();
2034
    }
2035
2036 245
    /**
2037 25
     * @param string   $oldColumnName
2038
     * @param string[] $columnSql
2039
     *
2040 220
     * @return bool
2041 220
     */
2042
    protected function onSchemaAlterTableRenameColumn($oldColumnName, Column $column, TableDiff $diff, &$columnSql)
2043 220
    {
2044
        if ($this->_eventManager === null) {
2045 220
            return false;
2046
        }
2047
2048
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableRenameColumn)) {
2049
            return false;
2050
        }
2051
2052
        $eventArgs = new SchemaAlterTableRenameColumnEventArgs($oldColumnName, $column, $diff, $this);
2053 4996
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableRenameColumn, $eventArgs);
2054
2055 4996
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
2056 4334
2057
        return $eventArgs->isDefaultPrevented();
2058
    }
2059 662
2060 442
    /**
2061
     * @param string[] $sql
2062
     *
2063 220
     * @return bool
2064 220
     */
2065
    protected function onSchemaAlterTable(TableDiff $diff, &$sql)
2066 220
    {
2067
        if ($this->_eventManager === null) {
2068 220
            return false;
2069
        }
2070
2071
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTable)) {
2072
            return false;
2073
        }
2074 4691
2075
        $eventArgs = new SchemaAlterTableEventArgs($diff, $this);
2076 4691
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTable, $eventArgs);
2077
2078 4691
        $sql = array_merge($sql, $eventArgs->getSql());
2079 4691
2080 4691
        return $eventArgs->isDefaultPrevented();
2081 329
    }
2082
2083 4691
    /**
2084 264
     * @return string[]
2085
     */
2086
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
2087
    {
2088 4691
        $tableName = $diff->getName($this)->getQuotedName($this);
2089 221
2090
        $sql = [];
2091 4691
        if ($this->supportsForeignKeyConstraints()) {
2092 394
            foreach ($diff->removedForeignKeys as $foreignKey) {
2093
                $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
2094
            }
2095 4691
            foreach ($diff->changedForeignKeys as $foreignKey) {
2096
                $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
2097
            }
2098
        }
2099
2100
        foreach ($diff->removedIndexes as $index) {
2101 4691
            $sql[] = $this->getDropIndexSQL($index, $tableName);
2102
        }
2103 4691
        foreach ($diff->changedIndexes as $index) {
2104 4691
            $sql[] = $this->getDropIndexSQL($index, $tableName);
2105
        }
2106 4691
2107 399
        return $sql;
2108
    }
2109 4294
2110
    /**
2111
     * @return string[]
2112 4691
     */
2113 4691
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff)
2114 306
    {
2115
        $sql     = [];
2116
        $newName = $diff->getNewName();
2117 4691
2118 264
        if ($newName !== false) {
2119
            $tableName = $newName->getQuotedName($this);
2120
        } else {
2121
            $tableName = $diff->getName($this)->getQuotedName($this);
2122 4691
        }
2123 87
2124
        if ($this->supportsForeignKeyConstraints()) {
2125
            foreach ($diff->addedForeignKeys as $foreignKey) {
2126 4691
                $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
2127 394
            }
2128
2129
            foreach ($diff->changedForeignKeys as $foreignKey) {
2130 4691
                $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
2131 1032
            }
2132 1032
        }
2133 1032
2134 1032
        foreach ($diff->addedIndexes as $index) {
2135
            $sql[] = $this->getCreateIndexSQL($index, $tableName);
2136
        }
2137
2138 4691
        foreach ($diff->changedIndexes as $index) {
2139
            $sql[] = $this->getCreateIndexSQL($index, $tableName);
2140
        }
2141
2142
        foreach ($diff->renamedIndexes as $oldIndexName => $index) {
2143
            $oldIndexName = new Identifier($oldIndexName);
2144
            $sql          = array_merge(
2145
                $sql,
2146
                $this->getRenameIndexSQL($oldIndexName->getQuotedName($this), $index, $tableName)
2147
            );
2148
        }
2149
2150 236
        return $sql;
2151
    }
2152
2153 236
    /**
2154 236
     * Returns the SQL for renaming an index on a table.
2155
     *
2156
     * @param string $oldIndexName The name of the index to rename from.
2157
     * @param Index  $index        The definition of the index to rename to.
2158
     * @param string $tableName    The table to rename the given index on.
2159
     *
2160
     * @return string[] The sequence of SQL statements for renaming the given index.
2161
     */
2162
    protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
2163
    {
2164
        return [
2165
            $this->getDropIndexSQL($oldIndexName, $tableName),
2166
            $this->getCreateIndexSQL($index, $tableName),
2167
        ];
2168
    }
2169
2170
    /**
2171
     * Common code for alter table statement generation that updates the changed Index and Foreign Key definitions.
2172
     *
2173
     * @deprecated
2174
     *
2175
     * @return string[]
2176
     */
2177
    protected function _getAlterTableIndexForeignKeySQL(TableDiff $diff)
2178
    {
2179
        return array_merge($this->getPreAlterTableIndexForeignKeySQL($diff), $this->getPostAlterTableIndexForeignKeySQL($diff));
2180
    }
2181
2182
    /**
2183
     * Gets declaration of a number of fields in bulk.
2184
     *
2185
     * @param mixed[][] $fields A multidimensional associative array.
2186
     *                          The first dimension determines the field name, while the second
2187
     *                          dimension is keyed with the name of the properties
2188
     *                          of the field being declared as array indexes. Currently, the types
2189
     *                          of supported field properties are as follows:
2190
     *
2191
     *      length
2192
     *          Integer value that determines the maximum length of the text
2193
     *          field. If this argument is missing the field should be
2194
     *          declared to have the longest length allowed by the DBMS.
2195
     *
2196
     *      default
2197
     *          Text value to be used as default for this field.
2198
     *
2199 6995
     *      notnull
2200
     *          Boolean flag that indicates whether this field is constrained
2201 6995
     *          to not be set to null.
2202
     *      charset
2203 6995
     *          Text value with the default CHARACTER SET for this field.
2204 6995
     *      collation
2205
     *          Text value with the default COLLATION for this field.
2206
     *      unique
2207 6995
     *          unique constraint
2208
     *
2209
     * @return string
2210
     */
2211
    public function getColumnDeclarationListSQL(array $fields)
2212
    {
2213
        $queryFields = [];
2214
2215
        foreach ($fields as $fieldName => $field) {
2216
            $queryFields[] = $this->getColumnDeclarationSQL($fieldName, $field);
2217
        }
2218
2219
        return implode(', ', $queryFields);
2220
    }
2221
2222
    /**
2223
     * Obtains DBMS specific SQL code portion needed to declare a generic type
2224
     * field to be used in statements like CREATE TABLE.
2225
     *
2226
     * @param string  $name  The name the field to be declared.
2227
     * @param mixed[] $field An associative array with the name of the properties
2228
     *                       of the field being declared as array indexes. Currently, the types
2229
     *                       of supported field properties are as follows:
2230
     *
2231
     *      length
2232
     *          Integer value that determines the maximum length of the text
2233
     *          field. If this argument is missing the field should be
2234
     *          declared to have the longest length allowed by the DBMS.
2235
     *
2236
     *      default
2237
     *          Text value to be used as default for this field.
2238
     *
2239
     *      notnull
2240
     *          Boolean flag that indicates whether this field is constrained
2241
     *          to not be set to null.
2242
     *      charset
2243 7549
     *          Text value with the default CHARACTER SET for this field.
2244
     *      collation
2245 7549
     *          Text value with the default COLLATION for this field.
2246 189
     *      unique
2247
     *          unique constraint
2248 7373
     *      check
2249
     *          column check constraint
2250 7373
     *      columnDefinition
2251 7373
     *          a string that defines the complete column
2252
     *
2253 7373
     * @return string DBMS specific SQL code portion that should be used to declare the column.
2254 7373
     */
2255
    public function getColumnDeclarationSQL($name, array $field)
2256 7373
    {
2257
        if (isset($field['columnDefinition'])) {
2258 7373
            $columnDef = $this->getCustomTypeDeclarationSQL($field);
2259 7373
        } else {
2260
            $default = $this->getDefaultValueDeclarationSQL($field);
2261 7373
2262
            $charset = ! empty($field['charset']) ?
2263 7373
                ' ' . $this->getColumnCharsetDeclarationSQL($field['charset']) : '';
2264 7373
2265
            $collation = ! empty($field['collation']) ?
2266 7373
                ' ' . $this->getColumnCollationDeclarationSQL($field['collation']) : '';
2267 895
2268
            $notnull = ! empty($field['notnull']) ? ' NOT NULL' : '';
2269
2270
            $unique = ! empty($field['unique']) ?
2271 7549
                ' ' . $this->getUniqueFieldDeclarationSQL() : '';
2272
2273
            $check = ! empty($field['check']) ? ' ' . $field['check'] : '';
2274
2275
            $typeDecl  = $field['type']->getSQLDeclaration($field, $this);
2276
            $columnDef = $typeDecl . $charset . $default . $notnull . $unique . $check . $collation;
2277
2278
            if ($this->supportsInlineColumnComments() && isset($field['comment']) && $field['comment'] !== '') {
2279
                $columnDef .= ' ' . $this->getInlineColumnCommentSQL($field['comment']);
2280
            }
2281 1835
        }
2282
2283 1835
        return $name . ' ' . $columnDef;
2284 1835
    }
2285 1835
2286 1835
    /**
2287
     * Returns the SQL snippet that declares a floating point column of arbitrary precision.
2288 1835
     *
2289
     * @param mixed[] $columnDef
2290
     *
2291
     * @return string
2292
     */
2293
    public function getDecimalTypeDeclarationSQL(array $columnDef)
2294
    {
2295
        $columnDef['precision'] = ! isset($columnDef['precision']) || empty($columnDef['precision'])
2296
            ? 10 : $columnDef['precision'];
2297
        $columnDef['scale']     = ! isset($columnDef['scale']) || empty($columnDef['scale'])
2298
            ? 0 : $columnDef['scale'];
2299 8906
2300
        return 'NUMERIC(' . $columnDef['precision'] . ', ' . $columnDef['scale'] . ')';
2301 8906
    }
2302 7462
2303
    /**
2304
     * Obtains DBMS specific SQL code portion needed to set a default value
2305 1881
     * declaration to be used in statements like CREATE TABLE.
2306
     *
2307 1881
     * @param mixed[] $field The field definition array.
2308 88
     *
2309
     * @return string DBMS specific SQL code portion needed to set a default value.
2310
     */
2311 1793
    public function getDefaultValueDeclarationSQL($field)
2312
    {
2313 1793
        if (! isset($field['default'])) {
2314 514
            return empty($field['notnull']) ? ' DEFAULT NULL' : '';
2315
        }
2316
2317 1364
        $default = $field['default'];
2318 270
2319
        if (! isset($field['type'])) {
2320
            return " DEFAULT '" . $default . "'";
2321 1110
        }
2322 13
2323
        $type = $field['type'];
2324
2325 1101
        if ($type instanceof Types\PhpIntegerMappingType) {
2326 234
            return ' DEFAULT ' . $default;
2327
        }
2328
2329 867
        if ($type instanceof Types\PhpDateTimeMappingType && $default === $this->getCurrentTimestampSQL()) {
2330 249
            return ' DEFAULT ' . $this->getCurrentTimestampSQL();
2331
        }
2332
2333 840
        if ($type instanceof Types\TimeType && $default === $this->getCurrentTimeSQL()) {
2334
            return ' DEFAULT ' . $this->getCurrentTimeSQL();
2335
        }
2336
2337
        if ($type instanceof Types\DateType && $default === $this->getCurrentDateSQL()) {
2338
            return ' DEFAULT ' . $this->getCurrentDateSQL();
2339
        }
2340
2341
        if ($type instanceof Types\BooleanType) {
2342
            return " DEFAULT '" . $this->convertBooleans($default) . "'";
0 ignored issues
show
Bug introduced by
Are you sure $this->convertBooleans($default) of type array|integer|mixed can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2342
            return " DEFAULT '" . /** @scrutinizer ignore-type */ $this->convertBooleans($default) . "'";
Loading history...
2343
        }
2344 1702
2345
        return ' DEFAULT ' . $this->quoteStringLiteral($default);
2346 1702
    }
2347 1702
2348 1702
    /**
2349
     * Obtains DBMS specific SQL code portion needed to set a CHECK constraint
2350
     * declaration to be used in statements like CREATE TABLE.
2351 1702
     *
2352 44
     * @param string[]|mixed[][] $definition The check definition.
2353
     *
2354
     * @return string DBMS specific SQL code portion needed to set a CHECK constraint.
2355 1702
     */
2356 44
    public function getCheckDeclarationSQL(array $definition)
2357
    {
2358
        $constraints = [];
2359
        foreach ($definition as $field => $def) {
2360
            if (is_string($def)) {
2361 1702
                $constraints[] = 'CHECK (' . $def . ')';
2362
            } else {
2363
                if (isset($def['min'])) {
2364
                    $constraints[] = 'CHECK (' . $field . ' >= ' . $def['min'] . ')';
2365
                }
2366
2367
                if (isset($def['max'])) {
2368
                    $constraints[] = 'CHECK (' . $field . ' <= ' . $def['max'] . ')';
2369
                }
2370
            }
2371
        }
2372
2373
        return implode(', ', $constraints);
2374
    }
2375 396
2376
    /**
2377 396
     * Obtains DBMS specific SQL code portion needed to set a unique
2378 396
     * constraint declaration to be used in statements like CREATE TABLE.
2379
     *
2380 396
     * @param string            $name       The name of the unique constraint.
2381
     * @param UniqueConstraint  $constraint The unique constraint definition.
2382
     *
2383
     * @return string DBMS specific SQL code portion needed to set a constraint.
2384 396
     *
2385 396
     * @throws InvalidArgumentException
2386 396
     */
2387
    public function getUniqueConstraintDeclarationSQL($name, UniqueConstraint $constraint)
2388
    {
2389
        $columns = $constraint->getQuotedColumns($this);
2390
        $name    = new Identifier($name);
2391
2392
        if (count($columns) === 0) {
2393
            throw new InvalidArgumentException("Incomplete definition. 'columns' required.");
2394
        }
2395
2396
        $flags = ['UNIQUE'];
2397
2398
        if ($constraint->hasFlag('clustered')) {
2399
            $flags[] = 'CLUSTERED';
2400 1008
        }
2401
2402 1008
        $constraintName  = $name->getQuotedName($this);
2403 1008
        $constraintName  = ! empty($constraintName) ? $constraintName . ' ' : '';
2404
        $columnListNames = $this->getIndexFieldDeclarationListSQL($columns);
2405 1008
2406
        return sprintf('CONSTRAINT %s%s (%s)', $constraintName, implode(' ', $flags), $columnListNames);
2407
    }
2408
2409 1008
    /**
2410 1008
     * Obtains DBMS specific SQL code portion needed to set an index
2411 1008
     * declaration to be used in statements like CREATE TABLE.
2412
     *
2413
     * @param string $name  The name of the index.
2414
     * @param Index  $index The index definition.
2415
     *
2416
     * @return string DBMS specific SQL code portion needed to set an index.
2417
     *
2418
     * @throws InvalidArgumentException
2419
     */
2420
    public function getIndexDeclarationSQL($name, Index $index)
2421
    {
2422
        $columns = $index->getColumns();
2423 233
        $name    = new Identifier($name);
2424
2425 233
        if (count($columns) === 0) {
2426
            throw new InvalidArgumentException("Incomplete definition. 'columns' required.");
2427
        }
2428
2429
        return $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name->getQuotedName($this)
2430
            . ' (' . $this->getIndexFieldDeclarationListSQL($index) . ')' . $this->getPartialIndexSQL($index);
2431
    }
2432
2433
    /**
2434 3559
     * Obtains SQL code portion needed to create a custom column,
2435
     * e.g. when a field has the "columnDefinition" keyword.
2436 3559
     * Only "AUTOINCREMENT" and "PRIMARY KEY" are added if appropriate.
2437 3317
     *
2438
     * @param mixed[] $columnDef
2439
     *
2440 286
     * @return string
2441
     */
2442
    public function getCustomTypeDeclarationSQL(array $columnDef)
2443
    {
2444 286
        return $columnDef['columnDefinition'];
2445
    }
2446 286
2447 286
    /**
2448
     * Obtains DBMS specific SQL code portion needed to set an index
2449
     * declaration to be used in statements like CREATE TABLE.
2450 286
     *
2451
     * @param mixed[]|Index $columnsOrIndex array declaration is deprecated, prefer passing Index to this method
2452
     */
2453
    public function getIndexFieldDeclarationListSQL($columnsOrIndex) : string
2454 286
    {
2455
        if ($columnsOrIndex instanceof Index) {
2456
            return implode(', ', $columnsOrIndex->getQuotedColumns($this));
2457
        }
2458
2459
        if (! is_array($columnsOrIndex)) {
0 ignored issues
show
introduced by
The condition is_array($columnsOrIndex) is always true.
Loading history...
2460
            throw new InvalidArgumentException('Fields argument should be an Index or array.');
2461
        }
2462
2463
        $ret = [];
2464
2465
        foreach ($columnsOrIndex as $column => $definition) {
2466
            if (is_array($definition)) {
2467
                $ret[] = $column;
2468
            } else {
2469
                $ret[] = $definition;
2470
            }
2471
        }
2472
2473
        return implode(', ', $ret);
2474
    }
2475
2476
    /**
2477
     * Returns the required SQL string that fits between CREATE ... TABLE
2478
     * to create the table as a temporary table.
2479
     *
2480
     * Should be overridden in driver classes to return the correct string for the
2481
     * specific database type.
2482
     *
2483 34
     * The default is to return the string "TEMPORARY" - this will result in a
2484
     * SQL error for any database that does not support temporary tables, or that
2485 34
     * requires a different SQL command from "CREATE TEMPORARY TABLE".
2486
     *
2487
     * @return string The string required to be placed between "CREATE" and "TABLE"
2488
     *                to generate a temporary table, if possible.
2489
     */
2490
    public function getTemporaryTableSQL()
2491
    {
2492
        return 'TEMPORARY';
2493
    }
2494
2495 1546
    /**
2496
     * Some vendors require temporary table names to be qualified specially.
2497 1546
     *
2498 1480
     * @param string $tableName
2499
     *
2500 1480
     * @return string
2501
     */
2502
    public function getTemporaryTableName($tableName)
2503
    {
2504
        return $tableName;
2505
    }
2506
2507
    /**
2508
     * Obtain DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
2509
     * of a field declaration to be used in statements like CREATE TABLE.
2510
     *
2511 1380
     * @return string DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
2512
     *                of a field declaration.
2513 1380
     */
2514 1380
    public function getForeignKeyDeclarationSQL(ForeignKeyConstraint $foreignKey)
2515 22
    {
2516
        $sql  = $this->getForeignKeyBaseDeclarationSQL($foreignKey);
2517 1380
        $sql .= $this->getAdvancedForeignKeyOptionsSQL($foreignKey);
2518 86
2519
        return $sql;
2520
    }
2521 1380
2522
    /**
2523
     * Returns the FOREIGN KEY query section dealing with non-standard options
2524
     * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
2525
     *
2526
     * @param ForeignKeyConstraint $foreignKey The foreign key definition.
2527
     *
2528
     * @return string
2529
     */
2530
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey)
2531
    {
2532
        $query = '';
2533 1428
        if ($this->supportsForeignKeyOnUpdate() && $foreignKey->hasOption('onUpdate')) {
2534
            $query .= ' ON UPDATE ' . $this->getForeignKeyReferentialActionSQL($foreignKey->getOption('onUpdate'));
2535 1428
        }
2536 64
        if ($foreignKey->hasOption('onDelete')) {
2537 1428
            $query .= ' ON DELETE ' . $this->getForeignKeyReferentialActionSQL($foreignKey->getOption('onDelete'));
2538 973
        }
2539 753
2540 577
        return $query;
2541 401
    }
2542 1230
2543
    /**
2544 198
     * Returns the given referential action in uppercase if valid, otherwise throws an exception.
2545
     *
2546
     * @param string $action The foreign key referential action.
2547
     *
2548
     * @return string
2549
     *
2550
     * @throws InvalidArgumentException If unknown referential action given.
2551
     */
2552
    public function getForeignKeyReferentialActionSQL($action)
2553
    {
2554
        $upper = strtoupper($action);
2555
        switch ($upper) {
2556 1326
            case 'CASCADE':
2557
            case 'SET NULL':
2558 1326
            case 'NO ACTION':
2559 1326
            case 'RESTRICT':
2560 1128
            case 'SET DEFAULT':
2561
                return $upper;
2562 1326
            default:
2563
                throw new InvalidArgumentException('Invalid foreign key action: ' . $upper);
2564 1326
        }
2565
    }
2566
2567 1326
    /**
2568
     * Obtains DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
2569
     * of a field declaration to be used in statements like CREATE TABLE.
2570 1326
     *
2571
     * @return string
2572
     *
2573
     * @throws InvalidArgumentException
2574 1326
     */
2575 1326
    public function getForeignKeyBaseDeclarationSQL(ForeignKeyConstraint $foreignKey)
2576 1326
    {
2577 1326
        $sql = '';
2578
        if (strlen($foreignKey->getName()) > 0) {
2579
            $sql .= 'CONSTRAINT ' . $foreignKey->getQuotedName($this) . ' ';
2580
        }
2581
        $sql .= 'FOREIGN KEY (';
2582
2583
        if (count($foreignKey->getLocalColumns()) === 0) {
2584
            throw new InvalidArgumentException("Incomplete definition. 'local' required.");
2585
        }
2586
        if (count($foreignKey->getForeignColumns()) === 0) {
2587
            throw new InvalidArgumentException("Incomplete definition. 'foreign' required.");
2588
        }
2589
        if (strlen($foreignKey->getForeignTableName()) === 0) {
2590
            throw new InvalidArgumentException("Incomplete definition. 'foreignTable' required.");
2591
        }
2592
2593
        return $sql . implode(', ', $foreignKey->getQuotedLocalColumns($this))
2594
            . ') REFERENCES '
2595
            . $foreignKey->getQuotedForeignTableName($this) . ' ('
2596
            . implode(', ', $foreignKey->getQuotedForeignColumns($this)) . ')';
2597
    }
2598
2599
    /**
2600
     * Obtains DBMS specific SQL code portion needed to set the UNIQUE constraint
2601
     * of a field declaration to be used in statements like CREATE TABLE.
2602
     *
2603
     * @return string DBMS specific SQL code portion needed to set the UNIQUE constraint
2604
     *                of a field declaration.
2605
     */
2606
    public function getUniqueFieldDeclarationSQL()
2607
    {
2608
        return 'UNIQUE';
2609
    }
2610
2611
    /**
2612
     * Obtains DBMS specific SQL code portion needed to set the CHARACTER SET
2613
     * of a field declaration to be used in statements like CREATE TABLE.
2614
     *
2615 91
     * @param string $charset The name of the charset.
2616
     *
2617 91
     * @return string DBMS specific SQL code portion needed to set the CHARACTER SET
2618
     *                of a field declaration.
2619
     */
2620
    public function getColumnCharsetDeclarationSQL($charset)
0 ignored issues
show
Unused Code introduced by
The parameter $charset is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

2620
    public function getColumnCharsetDeclarationSQL(/** @scrutinizer ignore-unused */ $charset)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
2621
    {
2622
        return '';
2623
    }
2624
2625
    /**
2626 44
     * Obtains DBMS specific SQL code portion needed to set the COLLATION
2627
     * of a field declaration to be used in statements like CREATE TABLE.
2628 44
     *
2629
     * @param string $collation The name of the collation.
2630
     *
2631
     * @return string DBMS specific SQL code portion needed to set the COLLATION
2632
     *                of a field declaration.
2633
     */
2634
    public function getColumnCollationDeclarationSQL($collation)
2635
    {
2636
        return $this->supportsColumnCollation() ? 'COLLATE ' . $collation : '';
2637 66
    }
2638
2639 66
    /**
2640
     * Whether the platform prefers sequences for ID generation.
2641
     * Subclasses should override this method to return TRUE if they prefer sequences.
2642
     *
2643
     * @return bool
2644
     */
2645
    public function prefersSequences()
2646
    {
2647
        return false;
2648
    }
2649
2650
    /**
2651
     * Whether the platform prefers identity columns (eg. autoincrement) for ID generation.
2652
     * Subclasses should override this method to return TRUE if they prefer identity columns.
2653
     *
2654
     * @return bool
2655
     */
2656 309
    public function prefersIdentityColumns()
2657
    {
2658 309
        return false;
2659
    }
2660
2661
    /**
2662
     * Some platforms need the boolean values to be converted.
2663
     *
2664
     * The default conversion in this implementation converts to integers (false => 0, true => 1).
2665
     *
2666 309
     * Note: if the input is not a boolean the original input might be returned.
2667 287
     *
2668
     * There are two contexts when converting booleans: Literals and Prepared Statements.
2669
     * This method should handle the literal case
2670 309
     *
2671
     * @param mixed $item A boolean or an array of them.
2672
     *
2673
     * @return mixed A boolean database value or an array of them.
2674
     */
2675
    public function convertBooleans($item)
2676
    {
2677
        if (is_array($item)) {
2678
            foreach ($item as $k => $value) {
2679
                if (! is_bool($value)) {
2680
                    continue;
2681
                }
2682 484
2683
                $item[$k] = (int) $value;
2684 484
            }
2685
        } elseif (is_bool($item)) {
2686
            $item = (int) $item;
2687
        }
2688
2689
        return $item;
2690
    }
2691
2692
    /**
2693
     * Some platforms have boolean literals that needs to be correctly converted
2694
     *
2695
     * The default conversion tries to convert value into bool "(bool)$item"
2696
     *
2697 100
     * @param mixed $item
2698
     *
2699 100
     * @return bool|null
2700
     */
2701
    public function convertFromBoolean($item)
2702
    {
2703
        return $item === null ? null: (bool) $item;
2704
    }
2705
2706
    /**
2707 207
     * This method should handle the prepared statements case. When there is no
2708
     * distinction, it's OK to use the same method.
2709 207
     *
2710
     * Note: if the input is not a boolean the original input might be returned.
2711
     *
2712
     * @param mixed $item A boolean or an array of them.
2713
     *
2714
     * @return mixed A boolean database value or an array of them.
2715
     */
2716
    public function convertBooleansToDatabaseValue($item)
2717 18
    {
2718
        return $this->convertBooleans($item);
2719 18
    }
2720
2721
    /**
2722
     * Returns the SQL specific for the platform to get the current date.
2723
     *
2724
     * @return string
2725
     */
2726
    public function getCurrentDateSQL()
2727 263
    {
2728
        return 'CURRENT_DATE';
2729 263
    }
2730
2731
    /**
2732
     * Returns the SQL specific for the platform to get the current time.
2733
     *
2734
     * @return string
2735
     */
2736
    public function getCurrentTimeSQL()
2737
    {
2738
        return 'CURRENT_TIME';
2739
    }
2740
2741 132
    /**
2742
     * Returns the SQL specific for the platform to get the current timestamp
2743 6
     *
2744 126
     * @return string
2745 132
     */
2746 126
    public function getCurrentTimestampSQL()
2747 132
    {
2748 126
        return 'CURRENT_TIMESTAMP';
2749 132
    }
2750 126
2751 132
    /**
2752
     * Returns the SQL for a given transaction isolation level Connection constant.
2753
     *
2754
     * @param int $level
2755
     *
2756
     * @return string
2757
     *
2758
     * @throws InvalidArgumentException
2759
     */
2760
    protected function _getTransactionIsolationLevelSQL($level)
2761
    {
2762 1
        switch ($level) {
2763
            case TransactionIsolationLevel::READ_UNCOMMITTED:
2764 1
                return 'READ UNCOMMITTED';
2765
            case TransactionIsolationLevel::READ_COMMITTED:
2766
                return 'READ COMMITTED';
2767
            case TransactionIsolationLevel::REPEATABLE_READ:
2768
                return 'REPEATABLE READ';
2769
            case TransactionIsolationLevel::SERIALIZABLE:
2770
                return 'SERIALIZABLE';
2771
            default:
2772
                throw new InvalidArgumentException('Invalid isolation level:' . $level);
2773
        }
2774
    }
2775
2776
    /**
2777
     * @return string
2778
     *
2779
     * @throws DBALException If not supported on this platform.
2780
     */
2781
    public function getListDatabasesSQL()
2782
    {
2783
        throw DBALException::notSupported(__METHOD__);
2784
    }
2785
2786
    /**
2787
     * Returns the SQL statement for retrieving the namespaces defined in the database.
2788
     *
2789
     * @return string
2790
     *
2791
     * @throws DBALException If not supported on this platform.
2792
     */
2793
    public function getListNamespacesSQL()
2794
    {
2795
        throw DBALException::notSupported(__METHOD__);
2796
    }
2797
2798
    /**
2799
     * @param string $database
2800
     *
2801
     * @return string
2802
     *
2803
     * @throws DBALException If not supported on this platform.
2804
     */
2805
    public function getListSequencesSQL($database)
2806
    {
2807
        throw DBALException::notSupported(__METHOD__);
2808
    }
2809
2810
    /**
2811
     * @param string $table
2812
     *
2813
     * @return string
2814
     *
2815
     * @throws DBALException If not supported on this platform.
2816
     */
2817
    public function getListTableConstraintsSQL($table)
2818
    {
2819
        throw DBALException::notSupported(__METHOD__);
2820
    }
2821
2822
    /**
2823
     * @param string      $table
2824
     * @param string|null $database
2825
     *
2826
     * @return string
2827
     *
2828
     * @throws DBALException If not supported on this platform.
2829
     */
2830
    public function getListTableColumnsSQL($table, $database = null)
2831
    {
2832
        throw DBALException::notSupported(__METHOD__);
2833
    }
2834
2835
    /**
2836
     * @return string
2837
     *
2838
     * @throws DBALException If not supported on this platform.
2839
     */
2840
    public function getListTablesSQL()
2841
    {
2842
        throw DBALException::notSupported(__METHOD__);
2843
    }
2844
2845
    /**
2846
     * @return string
2847
     *
2848
     * @throws DBALException If not supported on this platform.
2849
     */
2850
    public function getListUsersSQL()
2851
    {
2852
        throw DBALException::notSupported(__METHOD__);
2853
    }
2854
2855
    /**
2856
     * Returns the SQL to list all views of a database or user.
2857
     *
2858
     * @param string $database
2859
     *
2860
     * @return string
2861
     *
2862
     * @throws DBALException If not supported on this platform.
2863
     */
2864
    public function getListViewsSQL($database)
2865
    {
2866
        throw DBALException::notSupported(__METHOD__);
2867
    }
2868
2869
    /**
2870
     * Returns the list of indexes for the current database.
2871
     *
2872
     * The current database parameter is optional but will always be passed
2873
     * when using the SchemaManager API and is the database the given table is in.
2874
     *
2875
     * Attention: Some platforms only support currentDatabase when they
2876
     * are connected with that database. Cross-database information schema
2877
     * requests may be impossible.
2878
     *
2879
     * @param string $table
2880
     * @param string $currentDatabase
2881
     *
2882
     * @return string
2883
     *
2884
     * @throws DBALException If not supported on this platform.
2885
     */
2886
    public function getListTableIndexesSQL($table, $currentDatabase = null)
0 ignored issues
show
Unused Code introduced by
The parameter $currentDatabase is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

2886
    public function getListTableIndexesSQL($table, /** @scrutinizer ignore-unused */ $currentDatabase = null)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
2887
    {
2888
        throw DBALException::notSupported(__METHOD__);
2889
    }
2890
2891
    /**
2892
     * @param string $table
2893
     *
2894
     * @return string
2895
     *
2896
     * @throws DBALException If not supported on this platform.
2897
     */
2898
    public function getListTableForeignKeysSQL($table)
2899
    {
2900
        throw DBALException::notSupported(__METHOD__);
2901
    }
2902
2903
    /**
2904
     * @param string $name
2905
     * @param string $sql
2906
     *
2907
     * @return string
2908
     *
2909
     * @throws DBALException If not supported on this platform.
2910
     */
2911
    public function getCreateViewSQL($name, $sql)
2912
    {
2913
        throw DBALException::notSupported(__METHOD__);
2914
    }
2915
2916
    /**
2917
     * @param string $name
2918
     *
2919
     * @return string
2920
     *
2921
     * @throws DBALException If not supported on this platform.
2922
     */
2923
    public function getDropViewSQL($name)
2924
    {
2925
        throw DBALException::notSupported(__METHOD__);
2926
    }
2927
2928
    /**
2929
     * Returns the SQL snippet to drop an existing sequence.
2930
     *
2931
     * @param Sequence|string $sequence
2932
     *
2933
     * @return string
2934
     *
2935
     * @throws DBALException If not supported on this platform.
2936
     */
2937
    public function getDropSequenceSQL($sequence)
0 ignored issues
show
Unused Code introduced by
The parameter $sequence is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

2937
    public function getDropSequenceSQL(/** @scrutinizer ignore-unused */ $sequence)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
2938
    {
2939
        throw DBALException::notSupported(__METHOD__);
2940
    }
2941
2942
    /**
2943
     * @param string $sequenceName
2944 22
     *
2945
     * @return string
2946 22
     *
2947
     * @throws DBALException If not supported on this platform.
2948
     */
2949
    public function getSequenceNextValSQL($sequenceName)
0 ignored issues
show
Unused Code introduced by
The parameter $sequenceName is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

2949
    public function getSequenceNextValSQL(/** @scrutinizer ignore-unused */ $sequenceName)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
2950
    {
2951
        throw DBALException::notSupported(__METHOD__);
2952
    }
2953
2954
    /**
2955
     * Returns the SQL to create a new database.
2956
     *
2957
     * @param string $database The name of the database that should be created.
2958
     *
2959
     * @return string
2960
     *
2961
     * @throws DBALException If not supported on this platform.
2962
     */
2963
    public function getCreateDatabaseSQL($database)
2964
    {
2965
        throw DBALException::notSupported(__METHOD__);
2966
    }
2967
2968
    /**
2969
     * Returns the SQL to set the transaction isolation level.
2970
     *
2971
     * @param int $level
2972
     *
2973
     * @return string
2974
     *
2975
     * @throws DBALException If not supported on this platform.
2976
     */
2977
    public function getSetTransactionIsolationSQL($level)
2978
    {
2979
        throw DBALException::notSupported(__METHOD__);
2980
    }
2981
2982
    /**
2983
     * Obtains DBMS specific SQL to be used to create datetime fields in
2984
     * statements like CREATE TABLE.
2985 210
     *
2986
     * @param mixed[] $fieldDeclaration
2987 210
     *
2988
     * @return string
2989
     *
2990
     * @throws DBALException If not supported on this platform.
2991
     */
2992
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
2993
    {
2994
        throw DBALException::notSupported(__METHOD__);
2995
    }
2996
2997
    /**
2998
     * Obtains DBMS specific SQL to be used to create datetime with timezone offset fields.
2999
     *
3000
     * @param mixed[] $fieldDeclaration
3001
     *
3002
     * @return string
3003
     */
3004
    public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration)
3005
    {
3006
        return $this->getDateTimeTypeDeclarationSQL($fieldDeclaration);
3007
    }
3008
3009
    /**
3010
     * Obtains DBMS specific SQL to be used to create date fields in statements
3011
     * like CREATE TABLE.
3012
     *
3013
     * @param mixed[] $fieldDeclaration
3014
     *
3015
     * @return string
3016
     *
3017
     * @throws DBALException If not supported on this platform.
3018
     */
3019
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
3020
    {
3021
        throw DBALException::notSupported(__METHOD__);
3022
    }
3023
3024
    /**
3025 1079
     * Obtains DBMS specific SQL to be used to create time fields in statements
3026
     * like CREATE TABLE.
3027 1079
     *
3028
     * @param mixed[] $fieldDeclaration
3029
     *
3030
     * @return string
3031
     *
3032
     * @throws DBALException If not supported on this platform.
3033
     */
3034
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
3035
    {
3036
        throw DBALException::notSupported(__METHOD__);
3037
    }
3038
3039
    /**
3040
     * @param mixed[] $fieldDeclaration
3041
     *
3042
     * @return string
3043
     */
3044
    public function getFloatDeclarationSQL(array $fieldDeclaration)
3045
    {
3046
        return 'DOUBLE PRECISION';
3047
    }
3048
3049 104
    /**
3050
     * Gets the default transaction isolation level of the platform.
3051 104
     *
3052
     * @see TransactionIsolationLevel
3053
     *
3054
     * @return int The default isolation level.
3055
     */
3056
    public function getDefaultTransactionIsolationLevel()
3057
    {
3058
        return TransactionIsolationLevel::READ_COMMITTED;
3059
    }
3060
3061
    /* supports*() methods */
3062 24
3063
    /**
3064 24
     * Whether the platform supports sequences.
3065
     *
3066
     * @return bool
3067
     */
3068
    public function supportsSequences()
3069
    {
3070
        return false;
3071
    }
3072
3073
    /**
3074
     * Whether the platform supports identity columns.
3075
     *
3076 170
     * Identity columns are columns that receive an auto-generated value from the
3077
     * database on insert of a row.
3078 170
     *
3079
     * @return bool
3080
     */
3081
    public function supportsIdentityColumns()
3082
    {
3083
        return false;
3084
    }
3085
3086
    /**
3087
     * Whether the platform emulates identity columns through sequences.
3088
     *
3089
     * Some platforms that do not support identity columns natively
3090
     * but support sequences can emulate identity columns by using
3091
     * sequences.
3092
     *
3093 154
     * @return bool
3094
     */
3095 154
    public function usesSequenceEmulatedIdentityColumns()
3096
    {
3097
        return false;
3098
    }
3099
3100
    /**
3101
     * Gets the sequence name prefix based on table information.
3102
     *
3103 22
     * @param string      $tableName
3104
     * @param string|null $schemaName
3105 22
     *
3106
     * @return string
3107
     */
3108
    public function getSequencePrefix($tableName, $schemaName = null)
3109
    {
3110
        if ($schemaName === null) {
3111
            return $tableName;
3112
        }
3113 2386
3114
        // Prepend the schema name to the table name if there is one
3115 2386
        return (! $this->supportsSchemas() && $this->canEmulateSchemas())
3116
            ? $schemaName . '__' . $tableName
3117
            : $schemaName . '.' . $tableName;
3118
    }
3119
3120
    /**
3121 3592
     * Returns the name of the sequence for a particular identity column in a particular table.
3122
     *
3123 3592
     * @see usesSequenceEmulatedIdentityColumns
3124
     *
3125
     * @param string $tableName  The name of the table to return the sequence name for.
3126
     * @param string $columnName The name of the identity column in the table to return the sequence name for.
3127
     *
3128
     * @return string
3129
     *
3130
     * @throws DBALException If not supported on this platform.
3131 44
     */
3132
    public function getIdentitySequenceName($tableName, $columnName)
3133 44
    {
3134
        throw DBALException::notSupported(__METHOD__);
3135
    }
3136
3137
    /**
3138
     * Whether the platform supports indexes.
3139
     *
3140
     * @return bool
3141 22
     */
3142
    public function supportsIndexes()
3143 22
    {
3144
        return true;
3145
    }
3146
3147
    /**
3148
     * Whether the platform supports partial indexes.
3149
     *
3150
     * @return bool
3151 240
     */
3152
    public function supportsPartialIndexes()
3153 240
    {
3154
        return false;
3155
    }
3156
3157
    /**
3158
     * Whether the platform supports indexes with column length definitions.
3159
     */
3160
    public function supportsColumnLengthIndexes() : bool
3161 40
    {
3162
        return false;
3163 40
    }
3164
3165
    /**
3166
     * Whether the platform supports altering tables.
3167
     *
3168
     * @return bool
3169
     */
3170
    public function supportsAlterTable()
3171 22
    {
3172
        return true;
3173 22
    }
3174
3175
    /**
3176
     * Whether the platform supports transactions.
3177
     *
3178
     * @return bool
3179
     */
3180
    public function supportsTransactions()
3181 6676
    {
3182
        return true;
3183 6676
    }
3184
3185
    /**
3186
     * Whether the platform supports savepoints.
3187
     *
3188
     * @return bool
3189
     */
3190
    public function supportsSavepoints()
3191 1402
    {
3192
        return true;
3193 1402
    }
3194
3195
    /**
3196
     * Whether the platform supports releasing savepoints.
3197
     *
3198
     * @return bool
3199
     */
3200
    public function supportsReleaseSavepoints()
3201 171
    {
3202
        return $this->supportsSavepoints();
3203 171
    }
3204
3205
    /**
3206
     * Whether the platform supports primary key constraints.
3207
     *
3208
     * @return bool
3209
     */
3210
    public function supportsPrimaryConstraints()
3211
    {
3212
        return true;
3213
    }
3214
3215 22
    /**
3216
     * Whether the platform supports foreign key constraints.
3217 22
     *
3218
     * @return bool
3219
     */
3220
    public function supportsForeignKeyConstraints()
3221
    {
3222
        return true;
3223
    }
3224
3225
    /**
3226
     * Whether this platform supports onUpdate in foreign key constraints.
3227
     *
3228
     * @return bool
3229
     */
3230
    public function supportsForeignKeyOnUpdate()
3231
    {
3232
        return $this->supportsForeignKeyConstraints();
3233
    }
3234
3235
    /**
3236
     * Whether the platform supports database schemas.
3237
     *
3238
     * @return bool
3239 69
     */
3240
    public function supportsSchemas()
3241 69
    {
3242
        return false;
3243
    }
3244
3245
    /**
3246
     * Whether this platform can emulate schemas.
3247
     *
3248
     * Platforms that either support or emulate schemas don't automatically
3249 22
     * filter a schema for the namespaced elements in {@link
3250
     * AbstractManager#createSchema}.
3251 22
     *
3252
     * @return bool
3253
     */
3254
    public function canEmulateSchemas()
3255
    {
3256
        return false;
3257
    }
3258
3259 2744
    /**
3260
     * Returns the default schema name.
3261 2744
     *
3262
     * @return string
3263
     *
3264
     * @throws DBALException If not supported on this platform.
3265
     */
3266
    public function getDefaultSchemaName()
3267
    {
3268
        throw DBALException::notSupported(__METHOD__);
3269 4562
    }
3270
3271 4562
    /**
3272
     * Whether this platform supports create database.
3273
     *
3274
     * Some databases don't allow to create and drop databases at all or only with certain tools.
3275
     *
3276
     * @return bool
3277
     */
3278
    public function supportsCreateDropDatabase()
3279 6598
    {
3280
        return true;
3281 6598
    }
3282
3283
    /**
3284
     * Whether the platform supports getting the affected rows of a recent update/delete type query.
3285
     *
3286
     * @return bool
3287
     */
3288
    public function supportsGettingAffectedRows()
3289 7711
    {
3290
        return true;
3291 7711
    }
3292
3293
    /**
3294
     * Whether this platform support to add inline column comments as postfix.
3295
     *
3296
     * @return bool
3297
     */
3298
    public function supportsInlineColumnComments()
3299
    {
3300
        return false;
3301
    }
3302
3303
    /**
3304
     * Whether this platform support the proprietary syntax "COMMENT ON asset".
3305
     *
3306
     * @return bool
3307
     */
3308
    public function supportsCommentOnStatement()
3309
    {
3310
        return false;
3311 22
    }
3312
3313 22
    /**
3314
     * Does this platform have native guid type.
3315
     *
3316
     * @return bool
3317
     */
3318
    public function hasNativeGuidType()
3319
    {
3320
        return false;
3321
    }
3322
3323
    /**
3324
     * Does this platform have native JSON type.
3325
     *
3326
     * @return bool
3327
     */
3328
    public function hasNativeJsonType()
3329
    {
3330
        return false;
3331
    }
3332 374
3333
    /**
3334 374
     * @deprecated
3335
     *
3336
     * @return string
3337
     *
3338
     * @todo Remove in 3.0
3339
     */
3340
    public function getIdentityColumnNullInsertSQL()
3341
    {
3342
        return '';
3343 146
    }
3344
3345 146
    /**
3346
     * Whether this platform supports views.
3347
     *
3348
     * @return bool
3349
     */
3350
    public function supportsViews()
3351
    {
3352
        return true;
3353
    }
3354 151
3355
    /**
3356 151
     * Does this platform support column collation?
3357
     *
3358
     * @return bool
3359
     */
3360
    public function supportsColumnCollation()
3361
    {
3362
        return false;
3363
    }
3364
3365 129
    /**
3366
     * Gets the format string, as accepted by the date() function, that describes
3367 129
     * the format of a stored datetime value of this platform.
3368
     *
3369
     * @return string The format string.
3370
     */
3371
    public function getDateTimeFormatString()
3372
    {
3373
        return 'Y-m-d H:i:s';
3374
    }
3375
3376
    /**
3377
     * Gets the format string, as accepted by the date() function, that describes
3378
     * the format of a stored datetime with timezone value of this platform.
3379
     *
3380
     * @return string The format string.
3381 1562
     */
3382
    public function getDateTimeTzFormatString()
3383 1562
    {
3384 1188
        return 'Y-m-d H:i:s';
3385
    }
3386
3387 1562
    /**
3388
     * Gets the format string, as accepted by the date() function, that describes
3389 1562
     * the format of a stored date value of this platform.
3390
     *
3391
     * @return string The format string.
3392
     */
3393
    public function getDateFormatString()
3394
    {
3395
        return 'Y-m-d';
3396 1562
    }
3397
3398
    /**
3399
     * Gets the format string, as accepted by the date() function, that describes
3400
     * the format of a stored time value of this platform.
3401
     *
3402
     * @return string The format string.
3403 1562
     */
3404
    public function getTimeFormatString()
3405
    {
3406
        return 'H:i:s';
3407
    }
3408
3409
    /**
3410
     * Adds an driver-specific LIMIT clause to the query.
3411
     *
3412
     * @param string   $query
3413
     * @param int|null $limit
3414
     * @param int|null $offset
3415 246
     *
3416
     * @return string
3417 246
     *
3418 174
     * @throws DBALException
3419
     */
3420
    final public function modifyLimitQuery($query, $limit, $offset = null)
3421 246
    {
3422 42
        if ($limit !== null) {
3423
            $limit = (int) $limit;
3424
        }
3425 246
3426
        $offset = (int) $offset;
3427
3428
        if ($offset < 0) {
3429
            throw new DBALException(sprintf(
3430
                'Offset must be a positive integer or zero, %d given',
3431
                $offset
3432
            ));
3433 338
        }
3434
3435 338
        if ($offset > 0 && ! $this->supportsLimitOffset()) {
3436
            throw new DBALException(sprintf(
3437
                'Platform %s does not support offset values in limit queries.',
3438
                $this->getName()
3439
            ));
3440
        }
3441
3442
        return $this->doModifyLimitQuery($query, $limit, $offset);
3443
    }
3444
3445
    /**
3446
     * Adds an platform-specific LIMIT clause to the query.
3447
     *
3448
     * @param string   $query
3449
     * @param int|null $limit
3450
     * @param int|null $offset
3451
     *
3452
     * @return string
3453
     */
3454
    protected function doModifyLimitQuery($query, $limit, $offset)
3455
    {
3456
        if ($limit !== null) {
3457
            $query .= ' LIMIT ' . $limit;
3458
        }
3459
3460
        if ($offset > 0) {
3461
            $query .= ' OFFSET ' . $offset;
3462
        }
3463
3464
        return $query;
3465
    }
3466
3467
    /**
3468 382
     * Whether the database platform support offsets in modify limit clauses.
3469
     *
3470 382
     * @return bool
3471
     */
3472
    public function supportsLimitOffset()
3473
    {
3474
        return true;
3475
    }
3476
3477
    /**
3478
     * Gets the character casing of a column in an SQL result set of this platform.
3479
     *
3480
     * @param string $column The column name for which to get the correct character casing.
3481 14
     *
3482
     * @return string The column name in the character casing used in SQL result sets.
3483 14
     */
3484
    public function getSQLResultCasing($column)
3485
    {
3486
        return $column;
3487
    }
3488
3489
    /**
3490
     * Makes any fixes to a name of a schema element (table, sequence, ...) that are required
3491
     * by restrictions of the platform, like a maximum length.
3492
     *
3493
     * @param string $schemaElementName
3494
     *
3495
     * @return string
3496
     */
3497 174
    public function fixSchemaElementName($schemaElementName)
3498
    {
3499 174
        return $schemaElementName;
3500
    }
3501 174
3502
    /**
3503
     * Maximum length of any given database identifier, like tables or column names.
3504
     *
3505
     * @return int
3506
     */
3507
    public function getMaxIdentifierLength()
3508
    {
3509 174
        return 63;
3510
    }
3511 174
3512
    /**
3513 174
     * Returns the insert SQL for an empty insert statement.
3514
     *
3515
     * @param string $tableName
3516
     * @param string $identifierColumnName
3517
     *
3518
     * @return string
3519
     */
3520
    public function getEmptyIdentityInsertSQL($tableName, $identifierColumnName)
3521
    {
3522
        return 'INSERT INTO ' . $tableName . ' (' . $identifierColumnName . ') VALUES (null)';
3523 19
    }
3524
3525 19
    /**
3526
     * Generates a Truncate Table SQL statement for a given table.
3527
     *
3528
     * Cascade is not supported on many platforms but would optionally cascade the truncate by
3529
     * following the foreign keys.
3530
     *
3531
     * @param string $tableName
3532
     * @param bool   $cascade
3533
     *
3534
     * @return string
3535 18
     */
3536
    public function getTruncateTableSQL($tableName, $cascade = false)
0 ignored issues
show
Unused Code introduced by
The parameter $cascade is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

3536
    public function getTruncateTableSQL($tableName, /** @scrutinizer ignore-unused */ $cascade = false)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
3537 18
    {
3538
        $tableIdentifier = new Identifier($tableName);
3539
3540
        return 'TRUNCATE ' . $tableIdentifier->getQuotedName($this);
3541
    }
3542
3543
    /**
3544
     * This is for test reasons, many vendors have special requirements for dummy statements.
3545
     *
3546
     * @return string
3547 19
     */
3548
    public function getDummySelectSQL()
3549 19
    {
3550
        $expression = func_num_args() > 0 ? func_get_arg(0) : '1';
3551
3552
        return sprintf('SELECT %s', $expression);
3553
    }
3554
3555
    /**
3556
     * Returns the SQL to create a new savepoint.
3557
     *
3558
     * @param string $savepoint
3559 15959
     *
3560
     * @return string
3561
     */
3562 15959
    public function createSavePoint($savepoint)
3563 15189
    {
3564
        return 'SAVEPOINT ' . $savepoint;
3565
    }
3566 11963
3567 11963
    /**
3568 11963
     * Returns the SQL to release a savepoint.
3569
     *
3570
     * @param string $savepoint
3571
     *
3572
     * @return string
3573 11963
     */
3574
    public function releaseSavePoint($savepoint)
3575 11963
    {
3576
        return 'RELEASE SAVEPOINT ' . $savepoint;
3577
    }
3578
3579
    /**
3580
     * Returns the SQL to rollback a savepoint.
3581
     *
3582
     * @param string $savepoint
3583
     *
3584
     * @return string
3585
     */
3586
    public function rollbackSavePoint($savepoint)
3587
    {
3588
        return 'ROLLBACK TO SAVEPOINT ' . $savepoint;
3589
    }
3590
3591
    /**
3592
     * Returns the keyword list instance of this platform.
3593
     *
3594
     * @return KeywordList
3595
     *
3596
     * @throws DBALException If no keyword list is specified.
3597
     */
3598
    final public function getReservedKeywordsList()
3599
    {
3600 6633
        // Check for an existing instantiation of the keywords class.
3601
        if ($this->_keywords !== null) {
3602 6633
            return $this->_keywords;
3603
        }
3604 6633
3605
        $class    = $this->getReservedKeywordsClass();
3606
        $keywords = new $class();
3607
        if (! $keywords instanceof KeywordList) {
3608
            throw DBALException::notSupported(__METHOD__);
3609
        }
3610
3611
        // Store the instance so it doesn't need to be generated on every request.
3612 6853
        $this->_keywords = $keywords;
3613
3614 6853
        return $keywords;
3615
    }
3616
3617
    /**
3618
     * Returns the class name of the reserved keywords list.
3619
     *
3620
     * @return string
3621
     *
3622
     * @throws DBALException If not supported on this platform.
3623
     */
3624
    protected function getReservedKeywordsClass()
3625 242
    {
3626
        throw DBALException::notSupported(__METHOD__);
3627 242
    }
3628 242
3629 242
    /**
3630 242
     * Quotes a literal string.
3631
     * This method is NOT meant to fix SQL injections!
3632
     * It is only meant to escape this platform's string literal
3633
     * quote character inside the given literal string.
3634 242
     *
3635
     * @param string $str The literal string to be quoted.
3636 242
     *
3637
     * @return string The quoted literal string.
3638
     */
3639
    public function quoteStringLiteral($str)
3640
    {
3641
        $c = $this->getStringLiteralQuoteCharacter();
3642
3643
        return $c . str_replace($c, $c . $c, $str) . $c;
3644
    }
3645
3646
    /**
3647
     * Gets the character used for string literal quoting.
3648
     *
3649
     * @return string
3650
     */
3651
    public function getStringLiteralQuoteCharacter()
3652
    {
3653
        return "'";
3654
    }
3655
3656
    /**
3657
     * Escapes metacharacters in a string intended to be used with a LIKE
3658
     * operator.
3659
     *
3660
     * @param string $inputString a literal, unquoted string
3661
     * @param string $escapeChar  should be reused by the caller in the LIKE
3662
     *                            expression.
3663
     */
3664
    final public function escapeStringForLike(string $inputString, string $escapeChar) : string
3665
    {
3666
        return preg_replace(
3667
            '~([' . preg_quote($this->getLikeWildcardCharacters() . $escapeChar, '~') . '])~u',
3668
            addcslashes($escapeChar, '\\') . '$1',
3669
            $inputString
3670
        );
3671
    }
3672
3673
    protected function getLikeWildcardCharacters() : string
3674
    {
3675
        return '%_';
3676
    }
3677
}
3678