Failed Conditions
Pull Request — develop (#3348)
by Sergei
62:41
created

AbstractPlatform::convertBooleans()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 5

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 15
ccs 5
cts 5
cp 1
rs 9.6111
c 0
b 0
f 0
cc 5
nc 3
nop 1
crap 5
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 function addcslashes;
32
use function array_map;
33
use function array_merge;
34
use function array_unique;
35
use function array_values;
36
use function count;
37
use function explode;
38
use function implode;
39
use function in_array;
40
use function is_array;
41
use function is_bool;
42
use function is_numeric;
43
use function is_string;
44
use function preg_quote;
45
use function preg_replace;
46
use function sprintf;
47
use function str_replace;
48
use function strlen;
49
use function strpos;
50
use function strtolower;
51
use function strtoupper;
52
53
/**
54
 * Base class for all DatabasePlatforms. The DatabasePlatforms are the central
55
 * point of abstraction of platform-specific behaviors, features and SQL dialects.
56
 * They are a passive source of information.
57
 *
58
 * @todo Remove any unnecessary methods.
59
 */
60
abstract class AbstractPlatform
61
{
62
    public const CREATE_INDEXES = 1;
63
64
    public const CREATE_FOREIGNKEYS = 2;
65
66
    /**
67
     * @deprecated Use DateIntervalUnit::INTERVAL_UNIT_SECOND.
68
     */
69
    public const DATE_INTERVAL_UNIT_SECOND = DateIntervalUnit::SECOND;
70
71
    /**
72
     * @deprecated Use DateIntervalUnit::MINUTE.
73
     */
74
    public const DATE_INTERVAL_UNIT_MINUTE = DateIntervalUnit::MINUTE;
75
76
    /**
77
     * @deprecated Use DateIntervalUnit::HOUR.
78
     */
79
    public const DATE_INTERVAL_UNIT_HOUR = DateIntervalUnit::HOUR;
80
81
    /**
82
     * @deprecated Use DateIntervalUnit::DAY.
83
     */
84
    public const DATE_INTERVAL_UNIT_DAY = DateIntervalUnit::DAY;
85
86
    /**
87
     * @deprecated Use DateIntervalUnit::WEEK.
88
     */
89
    public const DATE_INTERVAL_UNIT_WEEK = DateIntervalUnit::WEEK;
90
91
    /**
92
     * @deprecated Use DateIntervalUnit::MONTH.
93
     */
94
    public const DATE_INTERVAL_UNIT_MONTH = DateIntervalUnit::MONTH;
95
96
    /**
97
     * @deprecated Use DateIntervalUnit::QUARTER.
98
     */
99
    public const DATE_INTERVAL_UNIT_QUARTER = DateIntervalUnit::QUARTER;
100
101
    /**
102
     * @deprecated Use DateIntervalUnit::QUARTER.
103
     */
104
    public const DATE_INTERVAL_UNIT_YEAR = DateIntervalUnit::YEAR;
105
106
    /**
107
     * @deprecated Use TrimMode::UNSPECIFIED.
108
     */
109
    public const TRIM_UNSPECIFIED = TrimMode::UNSPECIFIED;
110
111
    /**
112
     * @deprecated Use TrimMode::LEADING.
113
     */
114
    public const TRIM_LEADING = TrimMode::LEADING;
115
116
    /**
117
     * @deprecated Use TrimMode::TRAILING.
118
     */
119
    public const TRIM_TRAILING = TrimMode::TRAILING;
120
121
    /**
122
     * @deprecated Use TrimMode::BOTH.
123
     */
124
    public const TRIM_BOTH = TrimMode::BOTH;
125
126
    /** @var string[]|null */
127
    protected $doctrineTypeMapping = null;
128
129
    /**
130
     * Contains a list of all columns that should generate parseable column comments for type-detection
131
     * in reverse engineering scenarios.
132
     *
133
     * @var string[]|null
134
     */
135
    protected $doctrineTypeComments = null;
136
137
    /** @var EventManager */
138
    protected $_eventManager;
139
140
    /**
141
     * Holds the KeywordList instance for the current platform.
142
     *
143
     * @var KeywordList
144
     */
145
    protected $_keywords;
146
147
    public function __construct()
148
    {
149
    }
150 45479
151
    /**
152 45479
     * Sets the EventManager used by the Platform.
153
     */
154
    public function setEventManager(?EventManager $eventManager) : void
155
    {
156
        $this->_eventManager = $eventManager;
157 1361
    }
158
159 1361
    /**
160 1361
     * Gets the EventManager used by the Platform.
161
     */
162
    public function getEventManager() : ?EventManager
163
    {
164
        return $this->_eventManager;
165
    }
166
167 1008
    /**
168
     * Returns the SQL snippet that declares a boolean column.
169 1008
     *
170
     * @param mixed[] $columnDef
171
     */
172
    abstract public function getBooleanTypeDeclarationSQL(array $columnDef) : string;
173
174
    /**
175
     * Returns the SQL snippet that declares a 4 byte integer column.
176
     *
177
     * @param mixed[] $columnDef
178
     */
179
    abstract public function getIntegerTypeDeclarationSQL(array $columnDef) : string;
180
181
    /**
182
     * Returns the SQL snippet that declares an 8 byte integer column.
183
     *
184
     * @param mixed[] $columnDef
185
     */
186
    abstract public function getBigIntTypeDeclarationSQL(array $columnDef) : string;
187
188
    /**
189
     * Returns the SQL snippet that declares a 2 byte integer column.
190
     *
191
     * @param mixed[] $columnDef
192
     */
193
    abstract public function getSmallIntTypeDeclarationSQL(array $columnDef) : string;
194
195
    /**
196
     * Returns the SQL snippet that declares common properties of an integer column.
197
     *
198
     * @param mixed[] $columnDef
199
     */
200
    abstract protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef) : string;
201
202
    /**
203
     * Lazy load Doctrine Type Mappings.
204
     */
205
    abstract protected function initializeDoctrineTypeMappings() : void;
206
207
    /**
208
     * Initializes Doctrine Type Mappings with the platform defaults
209
     * and with all additional type mappings.
210
     */
211
    private function initializeAllDoctrineTypeMappings() : void
212
    {
213
        $this->initializeDoctrineTypeMappings();
214
215
        foreach (Type::getTypesMap() as $typeName => $className) {
216
            foreach (Type::getType($typeName)->getMappedDatabaseTypes($this) as $dbType) {
217
                $this->doctrineTypeMapping[$dbType] = $typeName;
218
            }
219
        }
220
    }
221
222
    /**
223
     * Returns the SQL snippet used to declare a VARCHAR column type.
224
     *
225
     * @param mixed[] $field
226
     */
227
    public function getVarcharTypeDeclarationSQL(array $field) : string
228
    {
229
        if (! isset($field['length'])) {
230 1292
            $field['length'] = $this->getVarcharDefaultLength();
231
        }
232 1292
233
        $fixed = $field['fixed'] ?? false;
234 1292
235 1292
        $maxLength = $fixed
236 1292
            ? $this->getCharMaxLength()
237
            : $this->getVarcharMaxLength();
238
239 1292
        if ($field['length'] > $maxLength) {
240
            return $this->getClobTypeDeclarationSQL($field);
241
        }
242
243
        return $this->getVarcharTypeDeclarationSQLSnippet($field['length'], $fixed);
244
    }
245
246
    /**
247
     * Returns the SQL snippet used to declare a BINARY/VARBINARY column type.
248 4990
     *
249
     * @param mixed[] $field The column definition.
250 4990
     */
251 1097
    public function getBinaryTypeDeclarationSQL(array $field) : string
252
    {
253
        if (! isset($field['length'])) {
254 4990
            $field['length'] = $this->getBinaryDefaultLength();
255
        }
256 4990
257 749
        $fixed = $field['fixed'] ?? false;
258 4990
259
        return $this->getBinaryTypeDeclarationSQLSnippet($field['length'], $fixed);
260 4990
    }
261
262
    /**
263
     * Returns the SQL snippet to declare a GUID/UUID field.
264 4990
     *
265
     * By default this maps directly to a CHAR(36) and only maps to more
266
     * special datatypes when the underlying databases support this datatype.
267
     *
268
     * @param mixed[] $field
269
     */
270
    public function getGuidTypeDeclarationSQL(array $field) : string
271
    {
272
        $field['length'] = 36;
273
        $field['fixed']  = true;
274 266
275
        return $this->getVarcharTypeDeclarationSQL($field);
276 266
    }
277 247
278
    /**
279
     * Returns the SQL snippet to declare a JSON field.
280 266
     *
281
     * By default this maps directly to a CLOB and only maps to more
282 266
     * special datatypes when the underlying databases support this datatype.
283
     *
284
     * @param mixed[] $field
285
     */
286
    public function getJsonTypeDeclarationSQL(array $field) : string
287
    {
288
        return $this->getClobTypeDeclarationSQL($field);
289
    }
290
291
    /**
292
     * @param int|null $length The length of the column.
293
     * @param bool     $fixed  Whether the column length is fixed.
294
     *
295 122
     * @throws DBALException If not supported on this platform.
296
     */
297 122
    protected function getVarcharTypeDeclarationSQLSnippet(?int $length, bool $fixed) : string
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

297
    protected function getVarcharTypeDeclarationSQLSnippet(?int $length, /** @scrutinizer ignore-unused */ bool $fixed) : string

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...
298 122
    {
299
        throw DBALException::notSupported('VARCHARs not supported by Platform.');
300 122
    }
301
302
    /**
303
     * Returns the SQL snippet used to declare a BINARY/VARBINARY column type.
304
     *
305
     * @param int|null $length The length of the column.
306
     * @param bool     $fixed  Whether the column length is fixed.
307
     *
308
     * @throws DBALException If not supported on this platform.
309
     */
310
    protected function getBinaryTypeDeclarationSQLSnippet(?int $length, bool $fixed) : string
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

310
    protected function getBinaryTypeDeclarationSQLSnippet(?int $length, /** @scrutinizer ignore-unused */ bool $fixed) : string

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...
311
    {
312
        throw DBALException::notSupported('BINARY/VARBINARY column types are not supported by this platform.');
313 307
    }
314
315 307
    /**
316
     * Returns the SQL snippet used to declare a CLOB column type.
317
     *
318
     * @param mixed[] $field
319
     */
320
    abstract public function getClobTypeDeclarationSQL(array $field) : string;
321
322
    /**
323
     * Returns the SQL Snippet used to declare a BLOB column type.
324
     *
325
     * @param mixed[] $field
326
     */
327
    abstract public function getBlobTypeDeclarationSQL(array $field) : string;
328
329
    /**
330
     * Gets the name of the platform.
331
     */
332
    abstract public function getName() : string;
333
334
    /**
335
     * Registers a doctrine type to be used in conjunction with a column type of this platform.
336
     *
337
     * @throws DBALException If the type is not found.
338
     */
339
    public function registerDoctrineTypeMapping(string $dbType, string $doctrineType) : void
340
    {
341
        if ($this->doctrineTypeMapping === null) {
342
            $this->initializeAllDoctrineTypeMappings();
343
        }
344
345
        if (! Types\Type::hasType($doctrineType)) {
346
            throw DBALException::typeNotFound($doctrineType);
347
        }
348
349
        $dbType                             = strtolower($dbType);
350
        $this->doctrineTypeMapping[$dbType] = $doctrineType;
351
352
        $doctrineType = Type::getType($doctrineType);
353
354
        if (! $doctrineType->requiresSQLCommentHint($this)) {
355
            return;
356
        }
357
358
        $this->markDoctrineTypeCommented($doctrineType);
359
    }
360
361
    /**
362
     * Gets the Doctrine type that is mapped for the given database column type.
363
     *
364
     * @throws DBALException
365
     */
366
    public function getDoctrineTypeMapping(string $dbType) : string
367
    {
368
        if ($this->doctrineTypeMapping === null) {
369
            $this->initializeAllDoctrineTypeMappings();
370
        }
371
372
        $dbType = strtolower($dbType);
373
374
        if (! isset($this->doctrineTypeMapping[$dbType])) {
375
            throw new DBALException('Unknown database type ' . $dbType . ' requested, ' . static::class . ' may not support it.');
376
        }
377
378
        return $this->doctrineTypeMapping[$dbType];
379 708
    }
380
381 708
    /**
382 703
     * Checks if a database type is currently supported by this platform.
383
     */
384
    public function hasDoctrineTypeMappingFor(string $dbType) : bool
385 708
    {
386 228
        if ($this->doctrineTypeMapping === null) {
387
            $this->initializeAllDoctrineTypeMappings();
388
        }
389 480
390 480
        $dbType = strtolower($dbType);
391
392 480
        return isset($this->doctrineTypeMapping[$dbType]);
393
    }
394 480
395 252
    /**
396
     * Initializes the Doctrine Type comments instance variable for in_array() checks.
397
     */
398 228
    protected function initializeCommentedDoctrineTypes() : void
399 228
    {
400
        $this->doctrineTypeComments = [];
401
402
        foreach (Type::getTypesMap() as $typeName => $className) {
403
            $type = Type::getType($typeName);
404
405
            if (! $type->requiresSQLCommentHint($this)) {
406
                continue;
407
            }
408
409
            $this->doctrineTypeComments[] = $typeName;
410 1691
        }
411
    }
412 1691
413 285
    /**
414
     * Is it necessary for the platform to add a parsable type comment to allow reverse engineering the given type?
415
     */
416 1691
    public function isCommentedDoctrineType(Type $doctrineType) : bool
417
    {
418 1691
        if ($this->doctrineTypeComments === null) {
419 228
            $this->initializeCommentedDoctrineTypes();
420
        }
421
422 1463
        return in_array($doctrineType->getName(), $this->doctrineTypeComments);
423
    }
424
425
    /**
426
     * Marks this type as to be commented in ALTER TABLE and CREATE TABLE statements.
427
     *
428
     * @param string|Type $doctrineType
429
     */
430
    public function markDoctrineTypeCommented($doctrineType) : void
431
    {
432 343
        if ($this->doctrineTypeComments === null) {
433
            $this->initializeCommentedDoctrineTypes();
434 343
        }
435 304
436
        $this->doctrineTypeComments[] = $doctrineType instanceof Type ? $doctrineType->getName() : $doctrineType;
437
    }
438 343
439
    /**
440 343
     * Gets the comment to append to a column comment that helps parsing this type in reverse engineering.
441
     */
442
    public function getDoctrineTypeComment(Type $doctrineType) : string
443
    {
444
        return '(DC2Type:' . $doctrineType->getName() . ')';
445
    }
446
447
    /**
448 11354
     * Gets the comment of a passed column modified by potential doctrine type comment hints.
449
     */
450 11354
    protected function getColumnComment(Column $column) : ?string
451
    {
452 11354
        $comment = $column->getComment();
453 11354
454
        if ($this->isCommentedDoctrineType($column->getType())) {
455 11354
            $comment .= $this->getDoctrineTypeComment($column->getType());
456 11354
        }
457
458
        return $comment;
459 11354
    }
460
461 11354
    /**
462
     * Gets the character used for identifier quoting.
463
     */
464
    public function getIdentifierQuoteCharacter() : string
465
    {
466
        return '"';
467
    }
468 14043
469
    /**
470 14043
     * Gets the string portion that starts an SQL comment.
471 11126
     */
472
    public function getSqlCommentStartString() : string
473
    {
474 14043
        return '--';
475
    }
476
477
    /**
478
     * Gets the string portion that ends an SQL comment.
479
     */
480
    public function getSqlCommentEndString() : string
481
    {
482
        return "\n";
483
    }
484 228
485
    /**
486 228
     * Gets the maximum length of a char field.
487 228
     */
488
    public function getCharMaxLength() : int
489
    {
490 228
        return $this->getVarcharMaxLength();
491 228
    }
492
493
    /**
494
     * Gets the maximum length of a varchar field.
495
     */
496
    public function getVarcharMaxLength() : int
497
    {
498 659
        return 4000;
499
    }
500 659
501
    /**
502
     * Gets the default length of a varchar field.
503
     */
504
    public function getVarcharDefaultLength() : int
505
    {
506
        return 255;
507
    }
508 8134
509
    /**
510 8134
     * Gets the maximum length of a binary field.
511
     */
512 8134
    public function getBinaryMaxLength() : int
513 659
    {
514
        return 4000;
515
    }
516 8134
517
    /**
518
     * Gets the default length of a binary field.
519
     */
520
    public function getBinaryDefaultLength() : int
521
    {
522
        return 255;
523
    }
524 3882
525
    /**
526 3882
     * Gets all SQL wildcard characters of the platform.
527
     *
528
     * @return string[]
529
     */
530
    public function getWildcards() : array
531
    {
532
        return ['%', '_'];
533
    }
534
535
    /**
536
     * Returns the regular expression operator.
537
     *
538
     * @throws DBALException If not supported on this platform.
539
     */
540
    public function getRegexpExpression() : string
541
    {
542
        throw DBALException::notSupported(__METHOD__);
543
    }
544
545
    /**
546
     * Returns the SQL snippet to get the average value of a column.
547
     *
548
     * @param string $expression The column to use.
549
     *
550
     * @return string Generated SQL including an AVG aggregate function.
551
     */
552 673
    public function getAvgExpression(string $expression) : string
553
    {
554 673
        return 'AVG(' . $expression . ')';
555
    }
556
557
    /**
558
     * Returns the SQL snippet to get the number of rows (without a NULL value) of a column.
559
     *
560
     * If a '*' is used instead of a column the number of selected rows is returned.
561
     *
562 2140
     * @param string $expression The expression to count.
563
     *
564 2140
     * @return string Generated SQL including a COUNT aggregate function.
565
     */
566
    public function getCountExpression(string $expression) : string
567
    {
568
        return 'COUNT(' . $expression . ')';
569
    }
570
571
    /**
572 1040
     * Returns the SQL snippet to get the highest value of a column.
573
     *
574 1040
     * @param string $expression The column to use.
575
     *
576
     * @return string Generated SQL including a MAX aggregate function.
577
     */
578
    public function getMaxExpression(string $expression) : string
579
    {
580
        return 'MAX(' . $expression . ')';
581
    }
582
583
    /**
584
     * Returns the SQL snippet to get the lowest value of a column.
585
     *
586
     * @param string $expression The column to use.
587
     *
588
     * @return string Generated SQL including a MIN aggregate function.
589
     */
590
    public function getMinExpression(string $expression) : string
591
    {
592 240
        return 'MIN(' . $expression . ')';
593
    }
594 240
595
    /**
596
     * Returns the SQL snippet to get the total sum of a column.
597
     *
598
     * @param string $expression The column to use.
599
     *
600
     * @return string Generated SQL including a SUM aggregate function.
601
     */
602
    public function getSumExpression(string $expression) : string
603
    {
604
        return 'SUM(' . $expression . ')';
605
    }
606
607
    // scalar functions
608
609
    /**
610
     * Returns the SQL snippet to get the md5 sum of a field.
611
     *
612
     * Note: Not SQL92, but common functionality.
613
     */
614 57
    public function getMd5Expression(string $expression) : string
615
    {
616 57
        return 'MD5(' . $expression . ')';
617
    }
618
619
    /**
620
     * Returns the SQL snippet to get the length of a text field.
621
     */
622
    public function getLengthExpression(string $expression) : string
623
    {
624
        return 'LENGTH(' . $expression . ')';
625
    }
626
627
    /**
628
     * Returns the SQL snippet to get the squared value of a column.
629
     *
630
     * @param string $expression The column to use.
631
     *
632
     * @return string Generated SQL including an SQRT aggregate function.
633
     */
634
    public function getSqrtExpression(string $expression) : string
635
    {
636
        return 'SQRT(' . $expression . ')';
637
    }
638
639
    /**
640
     * Returns the SQL snippet to round a numeric field to the number of decimals specified.
641
     */
642
    public function getRoundExpression(string $expression, int $decimals = 0) : string
643
    {
644
        return 'ROUND(' . $expression . ', ' . $decimals . ')';
645
    }
646
647
    /**
648
     * Returns the SQL snippet to get the remainder of the division operation $expression1 / $expression2.
649
     */
650
    public function getModExpression(string $expression1, string $expression2) : string
651
    {
652
        return 'MOD(' . $expression1 . ', ' . $expression2 . ')';
653
    }
654
655
    /**
656
     * Returns the SQL snippet to trim a string.
657
     *
658
     * @param string      $str  The expression to apply the trim to.
659
     * @param int         $mode The position of the trim (leading/trailing/both).
660
     * @param string|null $char The char to trim, has to be quoted already. Defaults to space.
661
     */
662
    public function getTrimExpression(string $str, int $mode = TrimMode::UNSPECIFIED, ?string $char = null) : string
663
    {
664
        $expression = '';
665
666
        switch ($mode) {
667
            case TrimMode::LEADING:
668
                $expression = 'LEADING ';
669
                break;
670
671
            case TrimMode::TRAILING:
672
                $expression = 'TRAILING ';
673
                break;
674
675
            case TrimMode::BOTH:
676
                $expression = 'BOTH ';
677
                break;
678
        }
679
680
        if ($char !== null) {
681
            $expression .= $char . ' ';
682
        }
683
684
        if ($mode || $char !== null) {
685
            $expression .= 'FROM ';
686
        }
687
688
        return 'TRIM(' . $expression . $str . ')';
689
    }
690
691
    /**
692
     * Returns the SQL snippet to trim trailing space characters from the expression.
693
     *
694
     * @param string $expression Literal string or column name.
695
     */
696
    public function getRtrimExpression(string $expression) : string
697
    {
698
        return 'RTRIM(' . $expression . ')';
699
    }
700
701
    /**
702
     * Returns the SQL snippet to trim leading space characters from the expression.
703
     *
704
     * @param string $expression Literal string or column name.
705
     */
706
    public function getLtrimExpression(string $expression) : string
707
    {
708
        return 'LTRIM(' . $expression . ')';
709
    }
710
711
    /**
712
     * Returns the SQL snippet to change all characters from the expression to uppercase,
713
     * according to the current character set mapping.
714
     *
715
     * @param string $expression Literal string or column name.
716
     */
717
    public function getUpperExpression(string $expression) : string
718
    {
719
        return 'UPPER(' . $expression . ')';
720
    }
721
722
    /**
723
     * Returns the SQL snippet to change all characters from the expression to lowercase,
724
     * according to the current character set mapping.
725
     *
726
     * @param string $expression Literal string or column name.
727
     */
728
    public function getLowerExpression(string $expression) : string
729
    {
730
        return 'LOWER(' . $expression . ')';
731
    }
732
733
    /**
734
     * Returns the SQL snippet to get the position of the first occurrence of substring $substr in string $str.
735
     *
736
     * @param string $str      Literal string.
737
     * @param string $substr   Literal string to find.
738
     * @param int    $startPos Position to start at, beginning of string by default.
739
     */
740
    public function getLocateExpression(string $str, string $substr, int $startPos = 1) : string
0 ignored issues
show
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

740
    public function getLocateExpression(string $str, string $substr, /** @scrutinizer ignore-unused */ int $startPos = 1) : string

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 $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

740
    public function getLocateExpression(string $str, /** @scrutinizer ignore-unused */ string $substr, int $startPos = 1) : string

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...
741
    {
742
        throw DBALException::notSupported(__METHOD__);
743
    }
744
745
    /**
746
     * Returns the SQL snippet to get the current system date.
747
     */
748
    public function getNowExpression() : string
749
    {
750
        return 'NOW()';
751
    }
752
753
    /**
754
     * Returns a SQL snippet to get a substring inside an SQL statement.
755
     *
756 540
     * Note: Not SQL92, but common functionality.
757
     *
758 540
     * SQLite only supports the 2 parameter variant of this function.
759
     *
760 540
     * @param string   $value  An sql string literal or column name/alias.
761
     * @param int      $from   Where to start the substring portion.
762 135
     * @param int|null $length The substring portion length.
763 135
     */
764
    public function getSubstringExpression(string $value, int $from, ?int $length = null) : string
765
    {
766 135
        if ($length === null) {
767 135
            return 'SUBSTRING(' . $value . ' FROM ' . $from . ')';
768
        }
769
770 135
        return 'SUBSTRING(' . $value . ' FROM ' . $from . ' FOR ' . $length . ')';
771 135
    }
772
773
    /**
774 540
     * Returns a SQL snippet to concatenate the given expressions.
775 420
     *
776
     * @param string[] ...$expressions
777
     */
778 540
    public function getConcatExpression(string ...$expressions) : string
779 510
    {
780
        return implode(' || ', $expressions);
781
    }
782 540
783
    /**
784
     * Returns the SQL for a logical not.
785
     *
786
     * Example:
787
     * <code>
788
     * $q = new Doctrine_Query();
789
     * $e = $q->expr;
790
     * $q->select('*')->from('table')
791
     *   ->where($e->eq('id', $e->not('null'));
792 19
     * </code>
793
     *
794 19
     * @return string The logical expression.
795
     */
796
    public function getNotExpression(string $expression) : string
797
    {
798
        return 'NOT(' . $expression . ')';
799
    }
800
801
    /**
802
     * Returns the SQL that checks if an expression is null.
803
     *
804 19
     * @param string $expression The expression that should be compared to null.
805
     *
806 19
     * @return string The logical expression.
807
     */
808
    public function getIsNullExpression(string $expression) : string
809
    {
810
        return $expression . ' IS NULL';
811
    }
812
813
    /**
814
     * Returns the SQL that checks if an expression is not null.
815
     *
816
     * @param string $expression The expression that should be compared to null.
817
     *
818
     * @return string The logical expression.
819
     */
820
    public function getIsNotNullExpression(string $expression) : string
821
    {
822
        return $expression . ' IS NOT NULL';
823
    }
824
825
    /**
826
     * Returns the SQL that checks if an expression evaluates to a value between two values.
827
     *
828
     * The parameter $expression is checked if it is between $value1 and $value2.
829
     *
830
     * Note: There is a slight difference in the way BETWEEN works on some databases.
831
     * http://www.w3schools.com/sql/sql_between.asp. If you want complete database
832
     * independence you should avoid using between().
833
     *
834
     * @param string $expression The value to compare to.
835
     * @param string $value1     The lower value to compare with.
836
     * @param string $value2     The higher value to compare with.
837
     *
838
     * @return string The logical expression.
839
     */
840
    public function getBetweenExpression(string $expression, string $value1, string $value2) : string
841
    {
842
        return $expression . ' BETWEEN ' . $value1 . ' AND ' . $value2;
843
    }
844
845
    /**
846
     * Returns the SQL to get the arccosine of a value.
847
     */
848
    public function getAcosExpression(string $value) : string
849
    {
850
        return 'ACOS(' . $value . ')';
851
    }
852
853
    /**
854
     * Returns the SQL to get the sine of a value.
855
     */
856
    public function getSinExpression(string $value) : string
857
    {
858
        return 'SIN(' . $value . ')';
859
    }
860
861
    /**
862
     * Returns the SQL to get the PI value.
863
     */
864
    public function getPiExpression() : string
865
    {
866
        return 'PI()';
867
    }
868
869
    /**
870
     * Returns the SQL to get the cosine of a value.
871
     */
872
    public function getCosExpression(string $value) : string
873
    {
874
        return 'COS(' . $value . ')';
875
    }
876
877
    /**
878
     * Returns the SQL to calculate the difference in days between the two passed dates.
879
     *
880
     * Computes diff = date1 - date2.
881
     *
882
     * @throws DBALException If not supported on this platform.
883
     */
884
    public function getDateDiffExpression(string $date1, string $date2) : string
0 ignored issues
show
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

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

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 $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

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

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...
885
    {
886
        throw DBALException::notSupported(__METHOD__);
887
    }
888
889
    /**
890 76
     * Returns the SQL to add the number of given seconds to a date.
891
     *
892 76
     * @throws DBALException If not supported on this platform.
893
     */
894
    public function getDateAddSecondsExpression(string $date, string $seconds) : string
895
    {
896
        return $this->getDateArithmeticIntervalExpression($date, '+', $seconds, DateIntervalUnit::SECOND);
897
    }
898
899
    /**
900
     * Returns the SQL to subtract the number of given seconds from a date.
901
     *
902
     * @throws DBALException If not supported on this platform.
903
     */
904
    public function getDateSubSecondsExpression(string $date, string $seconds) : string
905
    {
906
        return $this->getDateArithmeticIntervalExpression($date, '-', $seconds, DateIntervalUnit::SECOND);
907
    }
908
909
    /**
910
     * Returns the SQL to add the number of given minutes to a date.
911
     *
912
     * @throws DBALException If not supported on this platform.
913
     */
914
    public function getDateAddMinutesExpression(string $date, string $minutes) : string
915
    {
916
        return $this->getDateArithmeticIntervalExpression($date, '+', $minutes, DateIntervalUnit::MINUTE);
917
    }
918
919
    /**
920
     * Returns the SQL to subtract the number of given minutes from a date.
921
     *
922 76
     * @throws DBALException If not supported on this platform.
923
     */
924 76
    public function getDateSubMinutesExpression(string $date, string $minutes) : string
925
    {
926
        return $this->getDateArithmeticIntervalExpression($date, '-', $minutes, DateIntervalUnit::MINUTE);
927
    }
928
929
    /**
930
     * Returns the SQL to add the number of given hours to a date.
931
     *
932
     * @throws DBALException If not supported on this platform.
933
     */
934
    public function getDateAddHourExpression(string $date, string $hours) : string
935
    {
936
        return $this->getDateArithmeticIntervalExpression($date, '+', $hours, DateIntervalUnit::HOUR);
937
    }
938
939
    /**
940
     * Returns the SQL to subtract the number of given hours to a date.
941
     *
942
     * @throws DBALException If not supported on this platform.
943
     */
944
    public function getDateSubHourExpression(string $date, string $hours) : string
945
    {
946
        return $this->getDateArithmeticIntervalExpression($date, '-', $hours, DateIntervalUnit::HOUR);
947
    }
948
949
    /**
950
     * Returns the SQL to add the number of given days to a date.
951
     *
952
     * @throws DBALException If not supported on this platform.
953
     */
954
    public function getDateAddDaysExpression(string $date, string $days) : string
955
    {
956
        return $this->getDateArithmeticIntervalExpression($date, '+', $days, DateIntervalUnit::DAY);
957
    }
958
959
    /**
960
     * Returns the SQL to subtract the number of given days to a date.
961
     *
962
     * @throws DBALException If not supported on this platform.
963
     */
964
    public function getDateSubDaysExpression(string $date, string $days) : string
965
    {
966
        return $this->getDateArithmeticIntervalExpression($date, '-', $days, DateIntervalUnit::DAY);
967
    }
968
969
    /**
970
     * Returns the SQL to add the number of given weeks to a date.
971
     *
972
     * @throws DBALException If not supported on this platform.
973
     */
974
    public function getDateAddWeeksExpression(string $date, string $weeks) : string
975
    {
976
        return $this->getDateArithmeticIntervalExpression($date, '+', $weeks, DateIntervalUnit::WEEK);
977
    }
978
979
    /**
980
     * Returns the SQL to subtract the number of given weeks from a date.
981
     *
982
     * @throws DBALException If not supported on this platform.
983
     */
984
    public function getDateSubWeeksExpression(string $date, string $weeks) : string
985
    {
986
        return $this->getDateArithmeticIntervalExpression($date, '-', $weeks, DateIntervalUnit::WEEK);
987
    }
988
989
    /**
990
     * Returns the SQL to add the number of given months to a date.
991
     *
992
     * @throws DBALException If not supported on this platform.
993
     */
994
    public function getDateAddMonthExpression(string $date, string $months) : string
995
    {
996
        return $this->getDateArithmeticIntervalExpression($date, '+', $months, DateIntervalUnit::MONTH);
997
    }
998
999
    /**
1000
     * Returns the SQL to subtract the number of given months to a date.
1001
     *
1002
     * @throws DBALException If not supported on this platform.
1003
     */
1004
    public function getDateSubMonthExpression(string $date, string $months) : string
1005
    {
1006
        return $this->getDateArithmeticIntervalExpression($date, '-', $months, DateIntervalUnit::MONTH);
1007
    }
1008
1009
    /**
1010
     * Returns the SQL to add the number of given quarters to a date.
1011
     *
1012
     * @throws DBALException If not supported on this platform.
1013
     */
1014
    public function getDateAddQuartersExpression(string $date, string $quarters) : string
1015
    {
1016
        return $this->getDateArithmeticIntervalExpression($date, '+', $quarters, DateIntervalUnit::QUARTER);
1017
    }
1018
1019
    /**
1020
     * Returns the SQL to subtract the number of given quarters from a date.
1021
     *
1022
     * @throws DBALException If not supported on this platform.
1023
     */
1024
    public function getDateSubQuartersExpression(string $date, string $quarters) : string
1025
    {
1026
        return $this->getDateArithmeticIntervalExpression($date, '-', $quarters, DateIntervalUnit::QUARTER);
1027
    }
1028
1029
    /**
1030
     * Returns the SQL to add the number of given years to a date.
1031
     *
1032 57
     * @throws DBALException If not supported on this platform.
1033
     */
1034 57
    public function getDateAddYearsExpression(string $date, string $years) : string
1035
    {
1036
        return $this->getDateArithmeticIntervalExpression($date, '+', $years, DateIntervalUnit::YEAR);
1037
    }
1038
1039
    /**
1040
     * Returns the SQL to subtract the number of given years from a date.
1041
     *
1042
     * @throws DBALException If not supported on this platform.
1043
     */
1044
    public function getDateSubYearsExpression(string $date, string $years) : string
1045
    {
1046
        return $this->getDateArithmeticIntervalExpression($date, '-', $years, DateIntervalUnit::YEAR);
1047 57
    }
1048
1049 57
    /**
1050
     * Returns the SQL for a date arithmetic expression.
1051
     *
1052
     * @param string $date     The column or literal representing a date to perform the arithmetic operation on.
1053
     * @param string $operator The arithmetic operator (+ or -).
1054
     * @param string $interval The interval that shall be calculated into the date.
1055
     * @param string $unit     The unit of the interval that shall be calculated into the date.
1056
     *                                 One of the DATE_INTERVAL_UNIT_* constants.
1057
     *
1058
     * @throws DBALException If not supported on this platform.
1059
     */
1060
    protected function getDateArithmeticIntervalExpression(string $date, string $operator, string $interval, string $unit) : string
0 ignored issues
show
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

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

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...
1061
    {
1062 57
        throw DBALException::notSupported(__METHOD__);
1063
    }
1064 57
1065
    /**
1066
     * Converts the value of a natively unsupported date interval to a value of a supported one
1067
     *
1068
     * @param string $interval   SQL expression describing the value of the interval
1069
     * @param string $unit       Interval unit
1070
     * @param int    $multiplier Interval multiplier
1071
     *
1072
     * @throws DBALException
1073
     */
1074
    protected function convertNonNativeInterval(string $interval, string $unit, int $multiplier) : string
1075
    {
1076
        if (! is_numeric($interval)) {
1077 57
            throw new DBALException(sprintf('Non-numeric value of a %s interval is not supported', $unit));
1078
        }
1079 57
1080
        return (string) ((int) $interval * $multiplier);
1081
    }
1082
1083
    /**
1084
     * Returns the SQL bit AND comparison expression.
1085
     */
1086
    public function getBitAndComparisonExpression(string $value1, string $value2) : string
1087
    {
1088
        return '(' . $value1 . ' & ' . $value2 . ')';
1089
    }
1090
1091
    /**
1092 57
     * Returns the SQL bit OR comparison expression.
1093
     */
1094 57
    public function getBitOrComparisonExpression(string $value1, string $value2) : string
1095
    {
1096
        return '(' . $value1 . ' | ' . $value2 . ')';
1097
    }
1098
1099
    /**
1100
     * Returns the FOR UPDATE expression.
1101
     */
1102
    public function getForUpdateSQL() : string
1103
    {
1104
        return 'FOR UPDATE';
1105
    }
1106
1107 57
    /**
1108
     * Honors that some SQL vendors such as MsSql use table hints for locking instead of the ANSI SQL FOR UPDATE specification.
1109 57
     *
1110
     * @param string   $fromClause The FROM clause to append the hint for the given lock mode to.
1111
     * @param int|null $lockMode   One of the Doctrine\DBAL\LockMode::* constants. If null is given, nothing will
1112
     *                             be appended to the FROM clause.
1113
     */
1114
    public function appendLockHint(string $fromClause, ?int $lockMode) : string
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

1114
    public function appendLockHint(string $fromClause, /** @scrutinizer ignore-unused */ ?int $lockMode) : string

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...
1115
    {
1116
        return $fromClause;
1117
    }
1118
1119
    /**
1120
     * Returns the SQL snippet to append to any SELECT statement which locks rows in shared read lock.
1121
     *
1122 95
     * This defaults to the ANSI SQL "FOR UPDATE", which is an exclusive lock (Write). Some database
1123
     * vendors allow to lighten this constraint up to be a real read lock.
1124 95
     */
1125
    public function getReadLockSQL() : string
1126
    {
1127
        return $this->getForUpdateSQL();
1128
    }
1129
1130
    /**
1131
     * Returns the SQL snippet to append to any SELECT statement which obtains an exclusive lock on the rows.
1132
     *
1133
     * The semantics of this lock mode should equal the SELECT .. FOR UPDATE of the ANSI SQL standard.
1134
     */
1135
    public function getWriteLockSQL() : string
1136
    {
1137 59
        return $this->getForUpdateSQL();
1138
    }
1139 59
1140
    /**
1141
     * Returns the SQL snippet to drop an existing database.
1142
     *
1143
     * @param string $database The name of the database that should be dropped.
1144
     */
1145
    public function getDropDatabaseSQL(string $database) : string
1146
    {
1147
        return 'DROP DATABASE ' . $database;
1148
    }
1149
1150
    /**
1151
     * Returns the SQL snippet to drop an existing table.
1152 57
     *
1153
     * @param Table|string $table
1154 57
     *
1155
     * @throws InvalidArgumentException
1156
     */
1157
    public function getDropTableSQL($table) : string
1158
    {
1159
        $tableArg = $table;
1160
1161
        if ($table instanceof Table) {
1162
            $table = $table->getQuotedName($this);
1163
        }
1164
1165
        if (! is_string($table)) {
0 ignored issues
show
introduced by
The condition is_string($table) is always true.
Loading history...
1166
            throw new InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
1167 57
        }
1168
1169 57
        if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaDropTable)) {
1170
            $eventArgs = new SchemaDropTableEventArgs($tableArg, $this);
1171
            $this->_eventManager->dispatchEvent(Events::onSchemaDropTable, $eventArgs);
1172
1173
            if ($eventArgs->isDefaultPrevented()) {
1174
                return $eventArgs->getSql();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $eventArgs->getSql() could return the type null which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
1175
            }
1176
        }
1177
1178
        return 'DROP TABLE ' . $table;
1179
    }
1180
1181
    /**
1182 57
     * Returns the SQL to safely drop a temporary table WITHOUT implicitly committing an open transaction.
1183
     *
1184 57
     * @param Table|string $table
1185
     */
1186
    public function getDropTemporaryTableSQL($table) : string
1187
    {
1188
        return $this->getDropTableSQL($table);
1189
    }
1190
1191
    /**
1192
     * Returns the SQL to drop an index from a table.
1193
     *
1194
     * @param Index|string $index
1195
     * @param Table|string $table
1196
     *
1197 57
     * @throws InvalidArgumentException
1198
     */
1199 57
    public function getDropIndexSQL($index, $table = null) : string
1200
    {
1201
        if ($index instanceof Index) {
1202
            $index = $index->getQuotedName($this);
1203
        } elseif (! is_string($index)) {
0 ignored issues
show
introduced by
The condition is_string($index) is always true.
Loading history...
1204
            throw new InvalidArgumentException('AbstractPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
1205
        }
1206
1207
        return 'DROP INDEX ' . $index;
1208
    }
1209
1210
    /**
1211
     * Returns the SQL to drop a constraint.
1212 57
     *
1213
     * @param Constraint|string $constraint
1214 57
     * @param Table|string      $table
1215
     */
1216
    public function getDropConstraintSQL($constraint, $table) : string
1217
    {
1218
        if (! $constraint instanceof Constraint) {
1219
            $constraint = new Identifier($constraint);
1220
        }
1221
1222
        if (! $table instanceof Table) {
1223
            $table = new Identifier($table);
1224
        }
1225
1226
        $constraint = $constraint->getQuotedName($this);
1227 57
        $table      = $table->getQuotedName($this);
1228
1229 57
        return 'ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $constraint;
1230
    }
1231
1232
    /**
1233
     * Returns the SQL to drop a foreign key.
1234
     *
1235
     * @param ForeignKeyConstraint|string $foreignKey
1236
     * @param Table|string                $table
1237
     */
1238
    public function getDropForeignKeySQL($foreignKey, $table) : string
1239
    {
1240
        if (! $foreignKey instanceof ForeignKeyConstraint) {
1241
            $foreignKey = new Identifier($foreignKey);
1242 57
        }
1243
1244 57
        if (! $table instanceof Table) {
1245
            $table = new Identifier($table);
1246
        }
1247
1248
        $foreignKey = $foreignKey->getQuotedName($this);
1249
        $table      = $table->getQuotedName($this);
1250
1251
        return 'ALTER TABLE ' . $table . ' DROP FOREIGN KEY ' . $foreignKey;
1252
    }
1253
1254
    /**
1255
     * Returns the SQL statement(s) to create a table with the specified name, columns and constraints
1256
     * on this platform.
1257 57
     *
1258
     * @return string[] The sequence of SQL statements.
1259 57
     *
1260
     * @throws DBALException
1261
     * @throws InvalidArgumentException
1262
     */
1263
    public function getCreateTableSQL(Table $table, int $createFlags = self::CREATE_INDEXES) : array
1264
    {
1265
        if (count($table->getColumns()) === 0) {
1266
            throw DBALException::noColumnsSpecifiedForTable($table->getName());
1267
        }
1268
1269
        $tableName                    = $table->getQuotedName($this);
1270
        $options                      = $table->getOptions();
1271
        $options['uniqueConstraints'] = [];
1272
        $options['indexes']           = [];
1273
        $options['primary']           = [];
1274
1275
        if (($createFlags & self::CREATE_INDEXES) > 0) {
1276
            foreach ($table->getIndexes() as $index) {
1277
                /** @var $index Index */
1278
                if (! $index->isPrimary()) {
1279
                    $options['indexes'][$index->getQuotedName($this)] = $index;
1280
1281
                    continue;
1282
                }
1283
1284
                $options['primary']       = $index->getQuotedColumns($this);
1285
                $options['primary_index'] = $index;
1286
            }
1287
1288 207
            foreach ($table->getUniqueConstraints() as $uniqueConstraint) {
1289
                /** @var UniqueConstraint $uniqueConstraint */
1290 207
                $options['uniqueConstraints'][$uniqueConstraint->getQuotedName($this)] = $uniqueConstraint;
1291
            }
1292
        }
1293
1294
        if (($createFlags & self::CREATE_FOREIGNKEYS) > 0) {
1295
            $options['foreignKeys'] = [];
1296
1297
            foreach ($table->getForeignKeys() as $fkConstraint) {
1298
                $options['foreignKeys'][] = $fkConstraint;
1299
            }
1300
        }
1301 207
1302
        $columnSql = [];
1303 207
        $columns   = [];
1304
1305
        foreach ($table->getColumns() as $column) {
1306
            /** @var Column $column */
1307
            if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaCreateTableColumn)) {
1308
                $eventArgs = new SchemaCreateTableColumnEventArgs($column, $table, $this);
1309
                $this->_eventManager->dispatchEvent(Events::onSchemaCreateTableColumn, $eventArgs);
1310
1311 30
                $columnSql = array_merge($columnSql, $eventArgs->getSql());
1312
1313 30
                if ($eventArgs->isDefaultPrevented()) {
1314
                    continue;
1315
                }
1316
            }
1317
1318
            $columnData            = $column->toArray();
1319
            $columnData['name']    = $column->getQuotedName($this);
1320
            $columnData['version'] = $column->hasPlatformOption('version') ? $column->getPlatformOption('version') : false;
1321
            $columnData['comment'] = $this->getColumnComment($column);
1322
1323
            if ($columnData['type'] instanceof Types\StringType && $columnData['length'] === null) {
1324
                $columnData['length'] = 255;
1325 30
            }
1326
1327 30
            if (in_array($column->getName(), $options['primary'])) {
1328
                $columnData['primary'] = true;
1329
            }
1330
1331
            $columns[$columnData['name']] = $columnData;
1332
        }
1333
1334
        if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaCreateTable)) {
1335
            $eventArgs = new SchemaCreateTableEventArgs($table, $columns, $options, $this);
1336
            $this->_eventManager->dispatchEvent(Events::onSchemaCreateTable, $eventArgs);
1337
1338
            if ($eventArgs->isDefaultPrevented()) {
1339
                return array_merge($eventArgs->getSql(), $columnSql);
1340
            }
1341
        }
1342
1343
        $sql = $this->_getCreateTableSQL($tableName, $columns, $options);
1344
        if ($this->supportsCommentOnStatement()) {
1345
            foreach ($table->getColumns() as $column) {
1346
                $comment = $this->getColumnComment($column);
1347
1348
                if ($comment === '') {
1349
                    continue;
1350 34
                }
1351
1352 34
                $sql[] = $this->getCommentOnColumnSQL($tableName, $column->getQuotedName($this), $comment);
1353
            }
1354
        }
1355
1356
        return array_merge($sql, $columnSql);
1357
    }
1358
1359
    public function getCommentOnColumnSQL(string $tableName, string $columnName, string $comment) : string
1360
    {
1361
        $tableName  = new Identifier($tableName);
1362 67
        $columnName = new Identifier($columnName);
1363
        $comment    = $this->quoteStringLiteral($comment);
1364 67
1365
        return sprintf(
1366
            'COMMENT ON COLUMN %s.%s IS %s',
1367
            $tableName->getQuotedName($this),
1368
            $columnName->getQuotedName($this),
1369
            $comment
1370
        );
1371
    }
1372
1373
    /**
1374
     * Returns the SQL to create inline comment on a column.
1375
     *
1376 2791
     * @throws DBALException If not supported on this platform.
1377
     */
1378 2791
    public function getInlineColumnCommentSQL(string $comment) : string
1379
    {
1380 2791
        if (! $this->supportsInlineColumnComments()) {
1381 292
            throw DBALException::notSupported(__METHOD__);
1382 2525
        }
1383
1384
        return 'COMMENT ' . $this->quoteStringLiteral($comment);
1385
    }
1386 2791
1387 228
    /**
1388 228
     * Returns the SQL used to create a table.
1389
     *
1390 228
     * @param mixed[][] $columns
1391
     * @param mixed[]   $options
1392
     *
1393
     * @return string[]
1394
     */
1395 2791
    protected function _getCreateTableSQL(string $tableName, array $columns, array $options = []) : array
1396
    {
1397
        $columnListSql = $this->getColumnDeclarationListSQL($columns);
1398
1399
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
1400
            foreach ($options['uniqueConstraints'] as $name => $definition) {
1401
                $columnListSql .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
1402
            }
1403
        }
1404
1405 18
        if (isset($options['primary']) && ! empty($options['primary'])) {
1406
            $columnListSql .= ', PRIMARY KEY(' . implode(', ', array_unique(array_values($options['primary']))) . ')';
1407 18
        }
1408
1409
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
1410
            foreach ($options['indexes'] as $index => $definition) {
1411
                $columnListSql .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
1412
            }
1413
        }
1414
1415
        $query = 'CREATE TABLE ' . $tableName . ' (' . $columnListSql;
1416
1417
        $check = $this->getCheckDeclarationSQL($columns);
1418
        if (! empty($check)) {
1419
            $query .= ', ' . $check;
1420 139
        }
1421
        $query .= ')';
1422 139
1423 130
        $sql[] = $query;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$sql was never initialized. Although not strictly required by PHP, it is generally a good practice to add $sql = array(); before regardless.
Loading history...
1424 9
1425
        if (isset($options['foreignKeys'])) {
1426
            foreach ((array) $options['foreignKeys'] as $definition) {
1427
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
1428 139
            }
1429
        }
1430
1431
        return $sql;
1432
    }
1433
1434
    public function getCreateTemporaryTableSnippetSQL() : string
1435
    {
1436
        return 'CREATE TEMPORARY TABLE';
1437
    }
1438
1439 653
    /**
1440
     * Returns the SQL to create a sequence on this platform.
1441 653
     *
1442 534
     * @throws DBALException If not supported on this platform.
1443
     */
1444
    public function getCreateSequenceSQL(Sequence $sequence) : string
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

1444
    public function getCreateSequenceSQL(/** @scrutinizer ignore-unused */ Sequence $sequence) : string

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...
1445 653
    {
1446 653
        throw DBALException::notSupported(__METHOD__);
1447
    }
1448
1449 653
    /**
1450 653
     * Returns the SQL to change a sequence on this platform.
1451
     *
1452 653
     * @throws DBALException If not supported on this platform.
1453
     */
1454
    public function getAlterSequenceSQL(Sequence $sequence) : string
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

1454
    public function getAlterSequenceSQL(/** @scrutinizer ignore-unused */ Sequence $sequence) : string

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...
1455
    {
1456
        throw DBALException::notSupported(__METHOD__);
1457
    }
1458
1459
    /**
1460
     * Returns the SQL to create a constraint on a table on this platform.
1461
     *
1462
     * @param Table|string $table
1463 299
     *
1464
     * @throws InvalidArgumentException
1465 299
     */
1466 95
    public function getCreateConstraintSQL(Constraint $constraint, $table) : string
1467
    {
1468
        if ($table instanceof Table) {
1469 299
            $table = $table->getQuotedName($this);
1470 299
        }
1471
1472
        $query = 'ALTER TABLE ' . $table . ' ADD CONSTRAINT ' . $constraint->getQuotedName($this);
1473 299
1474 299
        $columnList = '(' . implode(', ', $constraint->getQuotedColumns($this)) . ')';
1475
1476 299
        $referencesClause = '';
1477
        if ($constraint instanceof Index) {
1478
            if ($constraint->isPrimary()) {
1479
                $query .= ' PRIMARY KEY';
1480
            } elseif ($constraint->isUnique()) {
1481
                $query .= ' UNIQUE';
1482
            } else {
1483
                throw new InvalidArgumentException(
1484
                    'Can only create primary or unique constraints, no common indexes with getCreateConstraintSQL().'
1485
                );
1486
            }
1487
        } elseif ($constraint instanceof ForeignKeyConstraint) {
1488
            $query .= ' FOREIGN KEY';
1489
1490 6595
            $referencesClause = ' REFERENCES ' . $constraint->getQuotedForeignTableName($this) .
1491
                ' (' . implode(', ', $constraint->getQuotedForeignColumns($this)) . ')';
1492 6595
        }
1493
        $query .= ' ' . $columnList . $referencesClause;
1494
1495
        return $query;
1496 6595
    }
1497 228
1498
    /**
1499
     * Returns the SQL to create an index on a table on this platform.
1500 6367
     *
1501 6367
     * @param Table|string $table The name of the table on which the index is to be created.
1502 6367
     *
1503 6367
     * @throws InvalidArgumentException
1504 6367
     */
1505
    public function getCreateIndexSQL(Index $index, $table) : string
1506 6367
    {
1507 6101
        if ($table instanceof Table) {
1508
            $table = $table->getQuotedName($this);
1509 4099
        }
1510 1274
        $name    = $index->getQuotedName($this);
1511
        $columns = $index->getColumns();
1512 1274
1513
        if (count($columns) === 0) {
1514
            throw new InvalidArgumentException("Incomplete definition. 'columns' required.");
1515 3177
        }
1516 3177
1517
        if ($index->isPrimary()) {
1518
            return $this->getCreatePrimaryKeySQL($index, $table);
1519 6101
        }
1520
1521
        $query  = 'CREATE ' . $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name . ' ON ' . $table;
1522
        $query .= ' (' . $this->getIndexFieldDeclarationListSQL($index) . ')' . $this->getPartialIndexSQL($index);
1523
1524
        return $query;
1525 6367
    }
1526 3518
1527
    /**
1528 3518
     * Adds condition for partial index.
1529 553
     */
1530
    protected function getPartialIndexSQL(Index $index) : string
1531
    {
1532
        if ($this->supportsPartialIndexes() && $index->hasOption('where')) {
1533 6367
            return ' WHERE ' . $index->getOption('where');
1534 6367
        }
1535
1536 6367
        return '';
1537
    }
1538 6367
1539 228
    /**
1540 228
     * Adds additional flags for index generation.
1541
     */
1542 228
    protected function getCreateIndexSQLFlags(Index $index) : string
1543
    {
1544 228
        return $index->isUnique() ? 'UNIQUE ' : '';
1545
    }
1546
1547
    /**
1548
     * Returns the SQL to create an unnamed primary key constraint.
1549 6367
     *
1550 6367
     * @param Table|string $table
1551 6367
     */
1552 6367
    public function getCreatePrimaryKeySQL(Index $index, $table) : string
1553
    {
1554 6367
        return 'ALTER TABLE ' . $table . ' ADD PRIMARY KEY (' . $this->getIndexFieldDeclarationListSQL($index) . ')';
0 ignored issues
show
Bug introduced by
Are you sure $table of type Doctrine\DBAL\Schema\Table|string 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

1554
        return 'ALTER TABLE ' . /** @scrutinizer ignore-type */ $table . ' ADD PRIMARY KEY (' . $this->getIndexFieldDeclarationListSQL($index) . ')';
Loading history...
1555 2377
    }
1556
1557
    /**
1558 6367
     * Returns the SQL to create a named schema.
1559 2911
     *
1560
     * @throws DBALException If not supported on this platform.
1561
     */
1562 6367
    public function getCreateSchemaSQL(string $schemaName) : string
1563
    {
1564
        throw DBALException::notSupported(__METHOD__);
1565 6367
    }
1566 228
1567 228
    /**
1568
     * Quotes a string so that it can be safely used as a table or column name,
1569 228
     * even if it is a reserved word of the platform. This also detects identifier
1570
     * chains separated by dot and quotes them independently.
1571
     *
1572
     * NOTE: Just because you CAN use quoted identifiers doesn't mean
1573
     * you SHOULD use them. In general, they end up causing way more
1574 6367
     * problems than they solve.
1575 6367
     *
1576 2527
     * @param string $str The identifier name to be quoted.
1577 2527
     *
1578
     * @return string The quoted identifier string.
1579 2527
     */
1580 2372
    public function quoteIdentifier(string $str) : string
1581
    {
1582
        if (strpos($str, '.') !== false) {
1583 446
            $parts = array_map([$this, 'quoteSingleIdentifier'], explode('.', $str));
1584
1585
            return implode('.', $parts);
1586
        }
1587 6367
1588
        return $this->quoteSingleIdentifier($str);
1589
    }
1590
1591
    /**
1592
     * Quotes a single identifier (no dot chain separation).
1593
     *
1594
     * @param string $str The identifier name to be quoted.
1595
     *
1596
     * @return string The quoted identifier string.
1597 653
     */
1598
    public function quoteSingleIdentifier(string $str) : string
1599 653
    {
1600 653
        $c = $this->getIdentifierQuoteCharacter();
1601 653
1602
        return $c . str_replace($c, $c . $c, $str) . $c;
1603 653
    }
1604 653
1605 653
    /**
1606 653
     * Returns the SQL to create a new foreign key.
1607 653
     *
1608
     * @param ForeignKeyConstraint $foreignKey The foreign key constraint.
1609
     * @param Table|string         $table      The name of the table on which the foreign key is to be created.
1610
     */
1611
    public function getCreateForeignKeySQL(ForeignKeyConstraint $foreignKey, $table) : string
1612
    {
1613
        if ($table instanceof Table) {
1614
            $table = $table->getQuotedName($this);
1615
        }
1616
1617
        return 'ALTER TABLE ' . $table . ' ADD ' . $this->getForeignKeyDeclarationSQL($foreignKey);
1618
    }
1619
1620 933
    /**
1621
     * Gets the SQL statements for altering an existing table.
1622 933
     *
1623 152
     * This method returns an array of SQL statements, since some platforms need several statements.
1624
     *
1625
     * @return string[]
1626 781
     *
1627
     * @throws DBALException If not supported on this platform.
1628
     */
1629
    public function getAlterTableSQL(TableDiff $diff)
1630
    {
1631
        throw DBALException::notSupported(__METHOD__);
1632
    }
1633
1634
    /**
1635
     * @param mixed[] $columnSql
1636
     */
1637
    protected function onSchemaAlterTableAddColumn(Column $column, TableDiff $diff, array &$columnSql) : bool
1638 713
    {
1639
        if ($this->_eventManager === null) {
1640 713
            return false;
1641
        }
1642 713
1643
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableAddColumn)) {
1644
            return false;
1645
        }
1646
1647
        $eventArgs = new SchemaAlterTableAddColumnEventArgs($column, $diff, $this);
1648 713
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableAddColumn, $eventArgs);
1649 372
1650
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
1651
1652 713
        return $eventArgs->isDefaultPrevented();
1653
    }
1654
1655
    /**
1656
     * @param string[] $columnSql
1657
     */
1658 713
    protected function onSchemaAlterTableRemoveColumn(Column $column, TableDiff $diff, array &$columnSql) : bool
1659
    {
1660 713
        if ($this->_eventManager === null) {
1661 713
            return false;
1662 19
        }
1663
1664 713
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableRemoveColumn)) {
1665
            return false;
1666 713
        }
1667
1668 713
        $eventArgs = new SchemaAlterTableRemoveColumnEventArgs($column, $diff, $this);
1669 315
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableRemoveColumn, $eventArgs);
1670 75
1671
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
1672
1673
        return $eventArgs->isDefaultPrevented();
1674 713
    }
1675
1676
    /**
1677
     * @param string[] $columnSql
1678
     */
1679
    protected function onSchemaAlterTableChangeColumn(ColumnDiff $columnDiff, TableDiff $diff, array &$columnSql) : bool
1680 30
    {
1681
        if ($this->_eventManager === null) {
1682 30
            return false;
1683
        }
1684
1685
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableChangeColumn)) {
1686
            return false;
1687
        }
1688
1689
        $eventArgs = new SchemaAlterTableChangeColumnEventArgs($columnDiff, $diff, $this);
1690
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableChangeColumn, $eventArgs);
1691
1692
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
1693
1694
        return $eventArgs->isDefaultPrevented();
1695
    }
1696
1697
    /**
1698
     * @param string[] $columnSql
1699
     */
1700
    protected function onSchemaAlterTableRenameColumn(string $oldColumnName, Column $column, TableDiff $diff, array &$columnSql) : bool
1701
    {
1702
        if ($this->_eventManager === null) {
1703
            return false;
1704
        }
1705
1706
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableRenameColumn)) {
1707
            return false;
1708
        }
1709
1710
        $eventArgs = new SchemaAlterTableRenameColumnEventArgs($oldColumnName, $column, $diff, $this);
1711
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableRenameColumn, $eventArgs);
1712
1713
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
1714
1715
        return $eventArgs->isDefaultPrevented();
1716
    }
1717
1718 295
    /**
1719
     * @param string[] $sql
1720 295
     */
1721
    protected function onSchemaAlterTable(TableDiff $diff, array &$sql) : bool
1722
    {
1723
        if ($this->_eventManager === null) {
1724 295
            return false;
1725
        }
1726 295
1727
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTable)) {
1728 295
            return false;
1729 295
        }
1730 295
1731 295
        $eventArgs = new SchemaAlterTableEventArgs($diff, $this);
1732 190
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTable, $eventArgs);
1733 190
1734
        $sql = array_merge($sql, $eventArgs->getSql());
1735
1736 295
        return $eventArgs->isDefaultPrevented();
1737
    }
1738
1739 190
    /**
1740 190
     * @return string[]
1741
     */
1742 190
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) : array
1743 190
    {
1744
        $tableName = $diff->getName($this)->getQuotedName($this);
1745 295
1746
        $sql = [];
1747 295
        if ($this->supportsForeignKeyConstraints()) {
1748
            foreach ($diff->removedForeignKeys as $foreignKey) {
1749
                $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
1750
            }
1751
            foreach ($diff->changedForeignKeys as $foreignKey) {
1752
                $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
1753
            }
1754
        }
1755
1756
        foreach ($diff->removedIndexes as $index) {
1757
            $sql[] = $this->getDropIndexSQL($index, $tableName);
1758
        }
1759 2192
        foreach ($diff->changedIndexes as $index) {
1760
            $sql[] = $this->getDropIndexSQL($index, $tableName);
1761 2192
        }
1762 19
1763
        return $sql;
1764 2192
    }
1765 2192
1766
    /**
1767 2192
     * @return string[]
1768
     */
1769
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff) : array
1770
    {
1771 2192
        $tableName = $diff->newName !== false
1772 361
            ? $diff->getNewName()->getQuotedName($this)
1773
            : $diff->getName($this)->getQuotedName($this);
1774
1775 1850
        $sql = [];
1776 1850
1777
        if ($this->supportsForeignKeyConstraints()) {
1778 1850
            foreach ($diff->addedForeignKeys as $foreignKey) {
1779
                $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
1780
            }
1781
1782
            foreach ($diff->changedForeignKeys as $foreignKey) {
1783
                $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
1784
            }
1785
        }
1786 2526
1787
        foreach ($diff->addedIndexes as $index) {
1788 2526
            $sql[] = $this->getCreateIndexSQL($index, $tableName);
1789 62
        }
1790
1791
        foreach ($diff->changedIndexes as $index) {
1792 2464
            $sql[] = $this->getCreateIndexSQL($index, $tableName);
1793
        }
1794
1795
        foreach ($diff->renamedIndexes as $oldIndexName => $index) {
1796
            $oldIndexName = new Identifier($oldIndexName);
1797
            $sql          = array_merge(
1798
                $sql,
1799
                $this->getRenameIndexSQL($oldIndexName->getQuotedName($this), $index, $tableName)
1800 1042
            );
1801
        }
1802 1042
1803
        return $sql;
1804
    }
1805
1806
    /**
1807
     * Returns the SQL for renaming an index on a table.
1808
     *
1809
     * @param string $oldIndexName The name of the index to rename from.
1810
     * @param Index  $index        The definition of the index to rename to.
1811
     * @param string $tableName    The table to rename the given index on.
1812 323
     *
1813
     * @return string[] The sequence of SQL statements for renaming the given index.
1814 323
     */
1815
    protected function getRenameIndexSQL(string $oldIndexName, Index $index, string $tableName) : array
1816
    {
1817
        return [
1818
            $this->getDropIndexSQL($oldIndexName, $tableName),
1819
            $this->getCreateIndexSQL($index, $tableName),
1820
        ];
1821
    }
1822
1823
    /**
1824
     * Common code for alter table statement generation that updates the changed Index and Foreign Key definitions.
1825
     *
1826 133
     * @return string[]
1827
     */
1828 133
    protected function _getAlterTableIndexForeignKeySQL(TableDiff $diff) : array
1829
    {
1830
        return array_merge($this->getPreAlterTableIndexForeignKeySQL($diff), $this->getPostAlterTableIndexForeignKeySQL($diff));
1831
    }
1832
1833
    /**
1834
     * Gets declaration of a number of fields in bulk.
1835
     *
1836
     * @param mixed[][] $fields A multidimensional associative array.
1837
     *                          The first dimension determines the field name, while the second
1838
     *                          dimension is keyed with the name of the properties
1839
     *                          of the field being declared as array indexes. Currently, the types
1840
     *                          of supported field properties are as follows:
1841
     *
1842
     *      length
1843
     *          Integer value that determines the maximum length of the text
1844 5274
     *          field. If this argument is missing the field should be
1845
     *          declared to have the longest length allowed by the DBMS.
1846 5274
     *
1847 252
     *      default
1848
     *          Text value to be used as default for this field.
1849 252
     *
1850
     *      notnull
1851
     *          Boolean flag that indicates whether this field is constrained
1852 5274
     *          to not be set to null.
1853
     *      charset
1854
     *          Text value with the default CHARACTER SET for this field.
1855
     *      collation
1856
     *          Text value with the default COLLATION for this field.
1857
     *      unique
1858
     *          unique constraint
1859
     */
1860
    public function getColumnDeclarationListSQL(array $fields) : string
1861
    {
1862 5247
        $queryFields = [];
1863
1864 5247
        foreach ($fields as $fieldName => $field) {
1865
            $queryFields[] = $this->getColumnDeclarationSQL($fieldName, $field);
1866 5247
        }
1867
1868
        return implode(', ', $queryFields);
1869
    }
1870
1871
    /**
1872
     * Obtains DBMS specific SQL code portion needed to declare a generic type
1873
     * field to be used in statements like CREATE TABLE.
1874
     *
1875
     * @param string  $name  The name the field to be declared.
1876
     * @param mixed[] $field An associative array with the name of the properties
1877 1229
     *                       of the field being declared as array indexes. Currently, the types
1878
     *                       of supported field properties are as follows:
1879 1229
     *
1880 19
     *      length
1881
     *          Integer value that determines the maximum length of the text
1882
     *          field. If this argument is missing the field should be
1883 1229
     *          declared to have the longest length allowed by the DBMS.
1884
     *
1885
     *      default
1886
     *          Text value to be used as default for this field.
1887
     *
1888
     *      notnull
1889
     *          Boolean flag that indicates whether this field is constrained
1890
     *          to not be set to null.
1891
     *      charset
1892
     *          Text value with the default CHARACTER SET for this field.
1893
     *      collation
1894
     *          Text value with the default COLLATION for this field.
1895
     *      unique
1896
     *          unique constraint
1897
     *      check
1898
     *          column check constraint
1899
     *      columnDefinition
1900
     *          a string that defines the complete column
1901
     *
1902
     * @return string DBMS specific SQL code portion that should be used to declare the column.
1903
     */
1904
    public function getColumnDeclarationSQL(string $name, array $field) : string
1905 1315
    {
1906
        if (isset($field['columnDefinition'])) {
1907 1315
            $columnDef = $this->getCustomTypeDeclarationSQL($field);
1908 1064
        } else {
1909
            $default = $this->getDefaultValueDeclarationSQL($field);
1910
1911 251
            $charset = isset($field['charset']) && $field['charset'] ?
1912 23
                ' ' . $this->getColumnCharsetDeclarationSQL($field['charset']) : '';
1913
1914
            $collation = isset($field['collation']) && $field['collation'] ?
1915 228
                ' ' . $this->getColumnCollationDeclarationSQL($field['collation']) : '';
1916 228
1917
            $notnull = isset($field['notnull']) && $field['notnull'] ? ' NOT NULL' : '';
1918 228
1919
            $unique = isset($field['unique']) && $field['unique'] ?
1920 228
                ' ' . $this->getUniqueFieldDeclarationSQL() : '';
1921
1922
            $check = isset($field['check']) && $field['check'] ?
1923
                ' ' . $field['check'] : '';
1924
1925
            $typeDecl  = $field['type']->getSQLDeclaration($field, $this);
1926
            $columnDef = $typeDecl . $charset . $default . $notnull . $unique . $check . $collation;
1927
1928 975
            if ($this->supportsInlineColumnComments() && isset($field['comment']) && $field['comment'] !== '') {
1929
                $columnDef .= ' ' . $this->getInlineColumnCommentSQL($field['comment']);
1930 975
            }
1931 722
        }
1932
1933
        return $name . ' ' . $columnDef;
1934 253
    }
1935 25
1936
    /**
1937
     * Returns the SQL snippet that declares a floating point column of arbitrary precision.
1938 228
     *
1939 228
     * @param mixed[] $columnDef
1940
     */
1941 228
    public function getDecimalTypeDeclarationSQL(array $columnDef) : string
1942
    {
1943 228
        $columnDef['precision'] = ! isset($columnDef['precision']) || empty($columnDef['precision'])
1944
            ? 10 : $columnDef['precision'];
1945
        $columnDef['scale']     = ! isset($columnDef['scale']) || empty($columnDef['scale'])
1946
            ? 0 : $columnDef['scale'];
1947
1948
        return 'NUMERIC(' . $columnDef['precision'] . ', ' . $columnDef['scale'] . ')';
1949
    }
1950
1951 2559
    /**
1952
     * Obtains DBMS specific SQL code portion needed to set a default value
1953 2559
     * declaration to be used in statements like CREATE TABLE.
1954 2071
     *
1955
     * @param mixed[] $field The field definition array.
1956
     *
1957 488
     * @return string DBMS specific SQL code portion needed to set a default value.
1958 260
     */
1959
    public function getDefaultValueDeclarationSQL(array $field) : string
1960
    {
1961 228
        if (! isset($field['default'])) {
1962 228
            return empty($field['notnull']) ? ' DEFAULT NULL' : '';
1963
        }
1964 228
1965
        $default = $field['default'];
1966 228
1967
        if (! isset($field['type'])) {
1968
            return " DEFAULT '" . $default . "'";
1969
        }
1970
1971
        $type = $field['type'];
1972
1973
        if ($type instanceof Types\PhpIntegerMappingType) {
1974
            return ' DEFAULT ' . $default;
1975 990
        }
1976
1977 990
        if ($type instanceof Types\PhpDateTimeMappingType && $default === $this->getCurrentTimestampSQL()) {
1978 741
            return ' DEFAULT ' . $this->getCurrentTimestampSQL();
1979
        }
1980
1981 249
        if ($type instanceof Types\TimeType && $default === $this->getCurrentTimeSQL()) {
1982 21
            return ' DEFAULT ' . $this->getCurrentTimeSQL();
1983
        }
1984
1985 228
        if ($type instanceof Types\DateType && $default === $this->getCurrentDateSQL()) {
1986 228
            return ' DEFAULT ' . $this->getCurrentDateSQL();
1987
        }
1988 228
1989
        if ($type instanceof Types\BooleanType) {
1990 228
            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

1990
            return " DEFAULT '" . /** @scrutinizer ignore-type */ $this->convertBooleans($default) . "'";
Loading history...
1991
        }
1992
1993
        return " DEFAULT '" . $default . "'";
1994
    }
1995
1996
    /**
1997
     * Obtains DBMS specific SQL code portion needed to set a CHECK constraint
1998 5008
     * declaration to be used in statements like CREATE TABLE.
1999
     *
2000 5008
     * @param mixed[][] $definition The check definition.
2001 4427
     *
2002
     * @return string DBMS specific SQL code portion needed to set a CHECK constraint.
2003
     */
2004 581
    public function getCheckDeclarationSQL(array $definition) : string
2005 353
    {
2006
        $constraints = [];
2007
        foreach ($definition as $field => $def) {
2008 228
            if (is_string($def)) {
2009 228
                $constraints[] = 'CHECK (' . $def . ')';
2010
            } else {
2011 228
                if (isset($def['min'])) {
2012
                    $constraints[] = 'CHECK (' . $field . ' >= ' . $def['min'] . ')';
2013 228
                }
2014
2015
                if (isset($def['max'])) {
2016
                    $constraints[] = 'CHECK (' . $field . ' <= ' . $def['max'] . ')';
2017
                }
2018
            }
2019 4723
        }
2020
2021 4723
        return implode(', ', $constraints);
2022
    }
2023 4723
2024 4723
    /**
2025 4723
     * Obtains DBMS specific SQL code portion needed to set a unique
2026 340
     * constraint declaration to be used in statements like CREATE TABLE.
2027
     *
2028 4723
     * @param string|null      $name       The name of the unique constraint.
2029 266
     * @param UniqueConstraint $constraint The unique constraint definition.
2030
     *
2031
     * @return string DBMS specific SQL code portion needed to set a constraint.
2032
     *
2033 4723
     * @throws InvalidArgumentException
2034 204
     */
2035
    public function getUniqueConstraintDeclarationSQL(?string $name, UniqueConstraint $constraint) : string
2036 4723
    {
2037 338
        $columns = $constraint->getColumns();
2038
        $name    = new Identifier($name);
2039
2040 4723
        if (count($columns) === 0) {
2041
            throw new InvalidArgumentException("Incomplete definition. 'columns' required.");
2042
        }
2043
2044
        $flags = ['UNIQUE'];
2045
2046 4723
        if ($constraint->hasFlag('clustered')) {
2047
            $flags[] = 'CLUSTERED';
2048 4723
        }
2049 422
2050 4723
        $constraintName  = $name->getQuotedName($this);
2051
        $constraintName  = ! empty($constraintName) ? $constraintName . ' ' : '';
2052 4723
        $columnListNames = $this->getIndexFieldDeclarationListSQL($columns);
2053
2054 4723
        return sprintf('CONSTRAINT %s%s (%s)', $constraintName, implode(' ', $flags), $columnListNames);
2055 4723
    }
2056 300
2057
    /**
2058
     * Obtains DBMS specific SQL code portion needed to set an index
2059 4723
     * declaration to be used in statements like CREATE TABLE.
2060 266
     *
2061
     * @param string $name  The name of the index.
2062
     * @param Index  $index The index definition.
2063
     *
2064 4723
     * @return string DBMS specific SQL code portion needed to set an index.
2065 74
     *
2066
     * @throws InvalidArgumentException
2067
     */
2068 4723
    public function getIndexDeclarationSQL(string $name, Index $index) : string
2069 338
    {
2070
        $columns = $index->getColumns();
2071
        $name    = new Identifier($name);
2072 4723
2073 1079
        if (count($columns) === 0) {
2074 1079
            throw new InvalidArgumentException("Incomplete definition. 'columns' required.");
2075 1079
        }
2076 1079
2077
        return $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name->getQuotedName($this) . ' ('
2078
            . $this->getIndexFieldDeclarationListSQL($index)
2079
            . ')' . $this->getPartialIndexSQL($index);
2080 4723
    }
2081
2082
    /**
2083
     * Obtains SQL code portion needed to create a custom column,
2084
     * e.g. when a field has the "columnDefinition" keyword.
2085
     * Only "AUTOINCREMENT" and "PRIMARY KEY" are added if appropriate.
2086
     *
2087
     * @param mixed[] $columnDef
2088
     */
2089
    public function getCustomTypeDeclarationSQL(array $columnDef) : string
2090
    {
2091
        return $columnDef['columnDefinition'];
2092 202
    }
2093
2094
    /**
2095 202
     * Obtains DBMS specific SQL code portion needed to set an index
2096 202
     * declaration to be used in statements like CREATE TABLE.
2097
     *
2098
     * @param mixed[][]|Index $columnsOrIndex array declaration is deprecated, prefer passing Index to this method
2099
     */
2100
    public function getIndexFieldDeclarationListSQL($columnsOrIndex) : string
2101
    {
2102
        if ($columnsOrIndex instanceof Index) {
2103
            return implode(', ', $columnsOrIndex->getQuotedColumns($this));
2104
        }
2105
2106
        if (! is_array($columnsOrIndex)) {
0 ignored issues
show
introduced by
The condition is_array($columnsOrIndex) is always true.
Loading history...
2107
            throw new InvalidArgumentException('Fields argument should be an Index or array.');
2108
        }
2109
2110
        $ret = [];
2111
2112
        foreach ($columnsOrIndex as $column => $definition) {
2113
            if (is_array($definition)) {
2114
                $ret[] = $column;
2115
            } else {
2116
                $ret[] = $definition;
2117
            }
2118
        }
2119
2120
        return implode(', ', $ret);
2121
    }
2122
2123
    /**
2124
     * Returns the required SQL string that fits between CREATE ... TABLE
2125
     * to create the table as a temporary table.
2126
     *
2127
     * Should be overridden in driver classes to return the correct string for the
2128
     * specific database type.
2129
     *
2130
     * The default is to return the string "TEMPORARY" - this will result in a
2131
     * SQL error for any database that does not support temporary tables, or that
2132
     * requires a different SQL command from "CREATE TEMPORARY TABLE".
2133
     *
2134
     * @return string The string required to be placed between "CREATE" and "TABLE"
2135
     *                to generate a temporary table, if possible.
2136
     */
2137
    public function getTemporaryTableSQL() : string
2138
    {
2139 6367
        return 'TEMPORARY';
2140
    }
2141 6367
2142
    /**
2143 6367
     * Some vendors require temporary table names to be qualified specially.
2144 6367
     */
2145
    public function getTemporaryTableName(string $tableName) : string
2146
    {
2147 6367
        return $tableName;
2148
    }
2149
2150
    /**
2151
     * Obtain DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
2152
     * of a field declaration to be used in statements like CREATE TABLE.
2153
     *
2154
     * @return string DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
2155
     *                of a field declaration.
2156
     */
2157
    public function getForeignKeyDeclarationSQL(ForeignKeyConstraint $foreignKey) : string
2158
    {
2159
        $sql  = $this->getForeignKeyBaseDeclarationSQL($foreignKey);
2160
        $sql .= $this->getAdvancedForeignKeyOptionsSQL($foreignKey);
2161
2162
        return $sql;
2163
    }
2164
2165
    /**
2166
     * Returns the FOREIGN KEY query section dealing with non-standard options
2167
     * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
2168
     *
2169
     * @param ForeignKeyConstraint $foreignKey The foreign key definition.
2170
     */
2171
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey) : string
2172
    {
2173
        $query = '';
2174
        if ($this->supportsForeignKeyOnUpdate() && $foreignKey->hasOption('onUpdate')) {
2175
            $query .= ' ON UPDATE ' . $this->getForeignKeyReferentialActionSQL($foreignKey->getOption('onUpdate'));
2176
        }
2177
        if ($foreignKey->hasOption('onDelete')) {
2178
            $query .= ' ON DELETE ' . $this->getForeignKeyReferentialActionSQL($foreignKey->getOption('onDelete'));
2179
        }
2180
2181
        return $query;
2182
    }
2183 6423
2184
    /**
2185 6423
     * Returns the given referential action in uppercase if valid, otherwise throws an exception.
2186 181
     *
2187
     * @param string $action The foreign key referential action.
2188 6252
     *
2189
     * @throws InvalidArgumentException If unknown referential action given.
2190 6252
     */
2191 6252
    public function getForeignKeyReferentialActionSQL(string $action) : string
2192
    {
2193 6252
        $upper = strtoupper($action);
2194 6252
        switch ($upper) {
2195
            case 'CASCADE':
2196 6252
            case 'SET NULL':
2197
            case 'NO ACTION':
2198 6252
            case 'RESTRICT':
2199 6252
            case 'SET DEFAULT':
2200
                return $upper;
2201 6252
            default:
2202 6252
                throw new InvalidArgumentException('Invalid foreign key action: ' . $upper);
2203
        }
2204 6252
    }
2205 6252
2206
    /**
2207 6252
     * Obtains DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
2208 731
     * of a field declaration to be used in statements like CREATE TABLE.
2209
     *
2210
     * @throws InvalidArgumentException
2211
     */
2212 6423
    public function getForeignKeyBaseDeclarationSQL(ForeignKeyConstraint $foreignKey) : string
2213
    {
2214
        $sql = '';
2215
        if (strlen($foreignKey->getName())) {
2216
            $sql .= 'CONSTRAINT ' . $foreignKey->getQuotedName($this) . ' ';
2217
        }
2218
        $sql .= 'FOREIGN KEY (';
2219
2220
        if (count($foreignKey->getLocalColumns()) === 0) {
2221
            throw new InvalidArgumentException("Incomplete definition. 'local' required.");
2222 1828
        }
2223
        if (count($foreignKey->getForeignColumns()) === 0) {
2224 1828
            throw new InvalidArgumentException("Incomplete definition. 'foreign' required.");
2225 1828
        }
2226 1828
        if (strlen($foreignKey->getForeignTableName()) === 0) {
2227 1828
            throw new InvalidArgumentException("Incomplete definition. 'foreignTable' required.");
2228
        }
2229 1828
2230
        return $sql . implode(', ', $foreignKey->getQuotedLocalColumns($this))
2231
            . ') REFERENCES '
2232
            . $foreignKey->getQuotedForeignTableName($this) . ' ('
2233
            . implode(', ', $foreignKey->getQuotedForeignColumns($this)) . ')';
2234
    }
2235
2236
    /**
2237
     * Obtains DBMS specific SQL code portion needed to set the UNIQUE constraint
2238
     * of a field declaration to be used in statements like CREATE TABLE.
2239
     *
2240 7314
     * @return string DBMS specific SQL code portion needed to set the UNIQUE constraint
2241
     *                of a field declaration.
2242 7314
     */
2243 6417
    public function getUniqueFieldDeclarationSQL() : string
2244
    {
2245
        return 'UNIQUE';
2246 1241
    }
2247
2248 1241
    /**
2249
     * Obtains DBMS specific SQL code portion needed to set the CHARACTER SET
2250
     * of a field declaration to be used in statements like CREATE TABLE.
2251
     *
2252 1241
     * @param string $charset The name of the charset.
2253
     *
2254 1241
     * @return string DBMS specific SQL code portion needed to set the CHARACTER SET
2255 372
     *                of a field declaration.
2256
     */
2257
    public function getColumnCharsetDeclarationSQL(string $charset) : string
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

2257
    public function getColumnCharsetDeclarationSQL(/** @scrutinizer ignore-unused */ string $charset) : string

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...
2258 916
    {
2259 208
        return '';
2260
    }
2261
2262 718
    /**
2263 2
     * Obtains DBMS specific SQL code portion needed to set the COLLATION
2264
     * of a field declaration to be used in statements like CREATE TABLE.
2265
     *
2266 718
     * @param string $collation The name of the collation.
2267 192
     *
2268
     * @return string DBMS specific SQL code portion needed to set the COLLATION
2269
     *                of a field declaration.
2270 526
     */
2271 195
    public function getColumnCollationDeclarationSQL(string $collation) : string
2272
    {
2273
        return $this->supportsColumnCollation() ? 'COLLATE ' . $collation : '';
2274 521
    }
2275
2276
    /**
2277
     * Whether the platform prefers sequences for ID generation.
2278
     * Subclasses should override this method to return TRUE if they prefer sequences.
2279
     */
2280
    public function prefersSequences() : bool
2281
    {
2282
        return false;
2283
    }
2284
2285 1863
    /**
2286
     * Whether the platform prefers identity columns (eg. autoincrement) for ID generation.
2287 1863
     * Subclasses should override this method to return TRUE if they prefer identity columns.
2288 1863
     */
2289 1863
    public function prefersIdentityColumns() : bool
2290
    {
2291
        return false;
2292 1863
    }
2293 38
2294
    /**
2295
     * Some platforms need the boolean values to be converted.
2296 1863
     *
2297 1863
     * The default conversion in this implementation converts to integers (false => 0, true => 1).
2298
     *
2299
     * Note: if the input is not a boolean the original input might be returned.
2300
     *
2301
     * There are two contexts when converting booleans: Literals and Prepared Statements.
2302 1863
     * This method should handle the literal case
2303
     *
2304
     * @param mixed $item A boolean or an array of them.
2305
     *
2306
     * @return mixed A boolean database value or an array of them.
2307
     */
2308
    public function convertBooleans($item)
2309
    {
2310
        if (is_array($item)) {
2311
            foreach ($item as $k => $value) {
2312
                if (! is_bool($value)) {
2313
                    continue;
2314
                }
2315
2316 494
                $item[$k] = (int) $value;
2317
            }
2318 494
        } elseif (is_bool($item)) {
2319 494
            $item = (int) $item;
2320
        }
2321 494
2322 19
        return $item;
2323
    }
2324
2325 475
    /**
2326
     * Some platforms have boolean literals that needs to be correctly converted
2327 475
     *
2328 19
     * The default conversion tries to convert value into bool "(bool)$item"
2329
     *
2330
     * @param mixed $item
2331 475
     */
2332 475
    public function convertFromBoolean($item) : ?bool
2333 475
    {
2334
        return $item === null ? null: (bool) $item;
2335 475
    }
2336
2337
    /**
2338
     * This method should handle the prepared statements case. When there is no
2339
     * distinction, it's OK to use the same method.
2340
     *
2341
     * Note: if the input is not a boolean the original input might be returned.
2342
     *
2343
     * @param mixed $item A boolean or an array of them.
2344
     *
2345
     * @return mixed A boolean database value or an array of them.
2346
     */
2347
    public function convertBooleansToDatabaseValue($item)
2348
    {
2349 888
        return $this->convertBooleans($item);
2350
    }
2351 888
2352 888
    /**
2353
     * Returns the SQL specific for the platform to get the current date.
2354 888
     */
2355
    public function getCurrentDateSQL() : string
2356
    {
2357
        return 'CURRENT_DATE';
2358 888
    }
2359 888
2360 888
    /**
2361
     * Returns the SQL specific for the platform to get the current time.
2362
     */
2363
    public function getCurrentTimeSQL() : string
2364
    {
2365
        return 'CURRENT_TIME';
2366
    }
2367
2368
    /**
2369
     * Returns the SQL specific for the platform to get the current timestamp
2370
     */
2371
    public function getCurrentTimestampSQL() : string
2372 238
    {
2373
        return 'CURRENT_TIMESTAMP';
2374 238
    }
2375
2376
    /**
2377
     * Returns the SQL for a given transaction isolation level Connection constant.
2378
     *
2379
     * @throws InvalidArgumentException
2380
     */
2381
    protected function _getTransactionIsolationLevelSQL(int $level) : string
2382
    {
2383
        switch ($level) {
2384
            case TransactionIsolationLevel::READ_UNCOMMITTED:
2385 3400
                return 'READ UNCOMMITTED';
2386
            case TransactionIsolationLevel::READ_COMMITTED:
2387 3400
                return 'READ COMMITTED';
2388
            case TransactionIsolationLevel::REPEATABLE_READ:
2389 3400
                return 'REPEATABLE READ';
2390 3400
            case TransactionIsolationLevel::SERIALIZABLE:
2391
                return 'SERIALIZABLE';
2392
            default:
2393 3400
                throw new InvalidArgumentException('Invalid isolation level:' . $level);
2394
        }
2395
    }
2396
2397 3400
    /**
2398
     * @throws DBALException If not supported on this platform.
2399
     */
2400
    public function getListDatabasesSQL() : string
2401
    {
2402
        throw DBALException::notSupported(__METHOD__);
2403
    }
2404
2405
    /**
2406
     * Returns the SQL statement for retrieving the namespaces defined in the database.
2407
     *
2408
     * @throws DBALException If not supported on this platform.
2409
     */
2410
    public function getListNamespacesSQL() : string
2411
    {
2412
        throw DBALException::notSupported(__METHOD__);
2413
    }
2414
2415
    /**
2416
     * @throws DBALException If not supported on this platform.
2417
     */
2418
    public function getListSequencesSQL(?string $database) : ?string
2419
    {
2420
        throw DBALException::notSupported(__METHOD__);
2421
    }
2422
2423
    /**
2424
     * @throws DBALException If not supported on this platform.
2425
     */
2426 26
    public function getListTableConstraintsSQL(string $table) : string
2427
    {
2428 26
        throw DBALException::notSupported(__METHOD__);
2429
    }
2430
2431
    /**
2432
     * @throws DBALException If not supported on this platform.
2433
     */
2434
    public function getListTableColumnsSQL(string $table, ?string $database = null) : string
2435
    {
2436
        throw DBALException::notSupported(__METHOD__);
2437
    }
2438 1497
2439
    /**
2440 1497
     * @throws DBALException If not supported on this platform.
2441 1440
     */
2442
    public function getListTablesSQL() : string
2443 1440
    {
2444
        throw DBALException::notSupported(__METHOD__);
2445
    }
2446
2447
    /**
2448
     * @throws DBALException If not supported on this platform.
2449
     */
2450
    public function getListUsersSQL() : string
2451
    {
2452
        throw DBALException::notSupported(__METHOD__);
2453
    }
2454 1340
2455
    /**
2456 1340
     * Returns the SQL to list all views of a database or user.
2457 1340
     *
2458 19
     * @throws DBALException If not supported on this platform.
2459
     */
2460 1340
    public function getListViewsSQL(?string $database) : string
2461 91
    {
2462
        throw DBALException::notSupported(__METHOD__);
2463
    }
2464 1340
2465
    /**
2466
     * Returns the list of indexes for the current database.
2467
     *
2468
     * The current database parameter is optional but will always be passed
2469
     * when using the SchemaManager API and is the database the given table is in.
2470
     *
2471
     * Attention: Some platforms only support currentDatabase when they
2472
     * are connected with that database. Cross-database information schema
2473
     * requests may be impossible.
2474
     *
2475
     * @throws DBALException If not supported on this platform.
2476 1497
     */
2477
    public function getListTableIndexesSQL(string $table, ?string $currentDatabase = null) : string
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

2477
    public function getListTableIndexesSQL(string $table, /** @scrutinizer ignore-unused */ ?string $currentDatabase = null) : string

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...
2478 1497
    {
2479 1497
        throw DBALException::notSupported(__METHOD__);
2480 1497
    }
2481 1012
2482 784
    /**
2483 594
     * @throws DBALException If not supported on this platform.
2484 423
     */
2485 1288
    public function getListTableForeignKeysSQL(string $table, ?string $database = null) : string
2486
    {
2487 209
        throw DBALException::notSupported(__METHOD__);
2488
    }
2489
2490
    /**
2491
     * @throws DBALException If not supported on this platform.
2492
     */
2493
    public function getCreateViewSQL(string $name, string $sql) : string
2494
    {
2495
        throw DBALException::notSupported(__METHOD__);
2496
    }
2497
2498
    /**
2499 1307
     * @throws DBALException If not supported on this platform.
2500
     */
2501 1307
    public function getDropViewSQL(string $name) : string
2502 1307
    {
2503 1098
        throw DBALException::notSupported(__METHOD__);
2504
    }
2505 1307
2506
    /**
2507 1307
     * Returns the SQL snippet to drop an existing sequence.
2508
     *
2509
     * @param Sequence|string $sequence
2510 1307
     *
2511
     * @throws DBALException If not supported on this platform.
2512
     */
2513 1307
    public function getDropSequenceSQL($sequence) : string
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

2513
    public function getDropSequenceSQL(/** @scrutinizer ignore-unused */ $sequence) : string

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...
2514
    {
2515
        throw DBALException::notSupported(__METHOD__);
2516
    }
2517 1307
2518 1307
    /**
2519 1307
     * @throws DBALException If not supported on this platform.
2520 1307
     */
2521
    public function getSequenceNextValSQL(string $sequenceName) : string
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

2521
    public function getSequenceNextValSQL(/** @scrutinizer ignore-unused */ string $sequenceName) : string

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...
2522
    {
2523
        throw DBALException::notSupported(__METHOD__);
2524
    }
2525
2526
    /**
2527
     * Returns the SQL to create a new database.
2528
     *
2529
     * @param string $database The name of the database that should be created.
2530
     *
2531
     * @throws DBALException If not supported on this platform.
2532
     */
2533
    public function getCreateDatabaseSQL(string $database) : string
2534
    {
2535
        throw DBALException::notSupported(__METHOD__);
2536
    }
2537
2538
    /**
2539
     * Returns the SQL to set the transaction isolation level.
2540
     *
2541
     * @throws DBALException If not supported on this platform.
2542
     */
2543
    public function getSetTransactionIsolationSQL(int $level) : string
2544
    {
2545
        throw DBALException::notSupported(__METHOD__);
2546
    }
2547
2548
    /**
2549
     * Obtains DBMS specific SQL to be used to create datetime fields in
2550
     * statements like CREATE TABLE.
2551
     *
2552
     * @param mixed[] $fieldDeclaration
2553
     *
2554
     * @throws DBALException If not supported on this platform.
2555
     */
2556
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration) : string
2557
    {
2558 240
        throw DBALException::notSupported(__METHOD__);
2559
    }
2560 240
2561
    /**
2562
     * Obtains DBMS specific SQL to be used to create datetime with timezone offset fields.
2563
     *
2564
     * @param mixed[] $fieldDeclaration
2565
     */
2566
    public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration) : string
2567
    {
2568
        return $this->getDateTimeTypeDeclarationSQL($fieldDeclaration);
2569 38
    }
2570
2571 38
    /**
2572
     * Obtains DBMS specific SQL to be used to create date fields in statements
2573
     * like CREATE TABLE.
2574
     *
2575
     * @param mixed[] $fieldDeclaration
2576
     *
2577
     * @throws DBALException If not supported on this platform.
2578
     */
2579
    public function getDateTypeDeclarationSQL(array $fieldDeclaration) : string
2580 76
    {
2581
        throw DBALException::notSupported(__METHOD__);
2582 76
    }
2583
2584
    /**
2585
     * Obtains DBMS specific SQL to be used to create time fields in statements
2586
     * like CREATE TABLE.
2587
     *
2588
     * @param mixed[] $fieldDeclaration
2589
     *
2590
     * @throws DBALException If not supported on this platform.
2591
     */
2592
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration) : string
2593
    {
2594
        throw DBALException::notSupported(__METHOD__);
2595
    }
2596
2597
    /**
2598
     * @param mixed[] $fieldDeclaration
2599 290
     */
2600
    public function getFloatDeclarationSQL(array $fieldDeclaration) : string
2601 290
    {
2602
        return 'DOUBLE PRECISION';
2603
    }
2604
2605
    /**
2606
     * Gets the default transaction isolation level of the platform.
2607
     *
2608
     * @see TransactionIsolationLevel
2609 290
     *
2610 271
     * @return int The default isolation level.
2611
     */
2612
    public function getDefaultTransactionIsolationLevel() : int
2613 290
    {
2614
        return TransactionIsolationLevel::READ_COMMITTED;
2615
    }
2616
2617
    /* supports*() methods */
2618
2619
    /**
2620
     * Whether the platform supports sequences.
2621
     */
2622
    public function supportsSequences() : bool
2623
    {
2624
        return false;
2625 589
    }
2626
2627 589
    /**
2628
     * Whether the platform supports identity columns.
2629
     *
2630
     * Identity columns are columns that receive an auto-generated value from the
2631
     * database on insert of a row.
2632
     */
2633
    public function supportsIdentityColumns() : bool
2634
    {
2635
        return false;
2636
    }
2637
2638
    /**
2639
     * Whether the platform emulates identity columns through sequences.
2640 104
     *
2641
     * Some platforms that do not support identity columns natively
2642 104
     * but support sequences can emulate identity columns by using
2643
     * sequences.
2644
     */
2645
    public function usesSequenceEmulatedIdentityColumns() : bool
2646
    {
2647
        return false;
2648
    }
2649
2650 185
    /**
2651
     * Gets the sequence name prefix based on table information.
2652 185
     */
2653
    public function getSequencePrefix(string $tableName, ?string $schemaName = null) : string
2654
    {
2655
        if (! $schemaName) {
2656
            return $tableName;
2657
        }
2658
2659
        // Prepend the schema name to the table name if there is one
2660 6
        return ! $this->supportsSchemas() && $this->canEmulateSchemas()
2661
            ? $schemaName . '__' . $tableName
2662 6
            : $schemaName . '.' . $tableName;
2663
    }
2664
2665
    /**
2666
     * Returns the name of the sequence for a particular identity column in a particular table.
2667
     *
2668
     * @see    usesSequenceEmulatedIdentityColumns
2669
     *
2670 252
     * @param string $tableName  The name of the table to return the sequence name for.
2671
     * @param string $columnName The name of the identity column in the table to return the sequence name for.
2672 252
     *
2673
     * @throws DBALException If not supported on this platform.
2674
     */
2675
    public function getIdentitySequenceName(string $tableName, string $columnName) : string
2676
    {
2677
        throw DBALException::notSupported(__METHOD__);
2678
    }
2679
2680
    /**
2681
     * Whether the platform supports indexes.
2682
     */
2683
    public function supportsIndexes() : bool
2684 152
    {
2685
        return true;
2686 152
    }
2687
2688 152
    /**
2689
     * Whether the platform supports partial indexes.
2690 152
     */
2691
    public function supportsPartialIndexes() : bool
2692 152
    {
2693
        return false;
2694 152
    }
2695
2696
    /**
2697
     * Whether the platform supports indexes with column length definitions.
2698
     */
2699
    public function supportsColumnLengthIndexes() : bool
2700
    {
2701
        return false;
2702
    }
2703
2704
    /**
2705 2
     * Whether the platform supports altering tables.
2706
     */
2707 2
    public function supportsAlterTable() : bool
2708
    {
2709
        return true;
2710
    }
2711
2712
    /**
2713
     * Whether the platform supports transactions.
2714
     */
2715
    public function supportsTransactions() : bool
2716
    {
2717
        return true;
2718
    }
2719
2720
    /**
2721
     * Whether the platform supports savepoints.
2722
     */
2723
    public function supportsSavepoints() : bool
2724
    {
2725
        return true;
2726
    }
2727
2728
    /**
2729
     * Whether the platform supports releasing savepoints.
2730
     */
2731
    public function supportsReleaseSavepoints() : bool
2732
    {
2733
        return $this->supportsSavepoints();
2734
    }
2735
2736
    /**
2737
     * Whether the platform supports primary key constraints.
2738
     */
2739
    public function supportsPrimaryConstraints() : bool
2740
    {
2741
        return true;
2742
    }
2743
2744
    /**
2745
     * Whether the platform supports foreign key constraints.
2746
     */
2747
    public function supportsForeignKeyConstraints() : bool
2748
    {
2749
        return true;
2750
    }
2751
2752
    /**
2753
     * Whether this platform supports onUpdate in foreign key constraints.
2754
     */
2755
    public function supportsForeignKeyOnUpdate() : bool
2756
    {
2757
        return $this->supportsForeignKeyConstraints();
2758
    }
2759
2760
    /**
2761
     * Whether the platform supports database schemas.
2762
     */
2763
    public function supportsSchemas() : bool
2764
    {
2765
        return false;
2766
    }
2767
2768
    /**
2769
     * Whether this platform can emulate schemas.
2770
     *
2771
     * Platforms that either support or emulate schemas don't automatically
2772
     * filter a schema for the namespaced elements in {@link
2773
     * AbstractManager#createSchema}.
2774
     */
2775
    public function canEmulateSchemas() : bool
2776
    {
2777
        return false;
2778
    }
2779
2780
    /**
2781
     * Returns the default schema name.
2782
     *
2783
     * @throws DBALException If not supported on this platform.
2784
     */
2785
    public function getDefaultSchemaName() : string
2786
    {
2787
        throw DBALException::notSupported(__METHOD__);
2788
    }
2789
2790
    /**
2791
     * Whether this platform supports create database.
2792
     *
2793
     * Some databases don't allow to create and drop databases at all or only with certain tools.
2794
     */
2795
    public function supportsCreateDropDatabase() : bool
2796
    {
2797
        return true;
2798
    }
2799
2800
    /**
2801
     * Whether the platform supports getting the affected rows of a recent update/delete type query.
2802
     */
2803
    public function supportsGettingAffectedRows() : bool
2804
    {
2805
        return true;
2806
    }
2807
2808
    /**
2809
     * Whether this platform support to add inline column comments as postfix.
2810
     */
2811
    public function supportsInlineColumnComments() : bool
2812
    {
2813
        return false;
2814
    }
2815
2816
    /**
2817
     * Whether this platform support the proprietary syntax "COMMENT ON asset".
2818
     */
2819
    public function supportsCommentOnStatement() : bool
2820
    {
2821
        return false;
2822
    }
2823
2824
    /**
2825
     * Does this platform have native guid type.
2826
     */
2827
    public function hasNativeGuidType() : bool
2828
    {
2829
        return false;
2830
    }
2831
2832
    /**
2833
     * Does this platform have native JSON type.
2834
     */
2835
    public function hasNativeJsonType() : bool
2836
    {
2837
        return false;
2838
    }
2839
2840
    /**
2841
     * @deprecated
2842
     *
2843
     * @todo Remove in 3.0
2844
     */
2845
    public function getIdentityColumnNullInsertSQL() : string
2846
    {
2847
        return '';
2848
    }
2849
2850
    /**
2851
     * Whether this platform supports views.
2852
     */
2853
    public function supportsViews() : bool
2854
    {
2855
        return true;
2856
    }
2857
2858
    /**
2859
     * Does this platform support column collation?
2860
     */
2861
    public function supportsColumnCollation() : bool
2862
    {
2863
        return false;
2864
    }
2865
2866
    /**
2867
     * Gets the format string, as accepted by the date() function, that describes
2868
     * the format of a stored datetime value of this platform.
2869
     *
2870
     * @return string The format string.
2871
     */
2872
    public function getDateTimeFormatString() : string
2873
    {
2874
        return 'Y-m-d H:i:s';
2875
    }
2876
2877
    /**
2878
     * Gets the format string, as accepted by the date() function, that describes
2879
     * the format of a stored datetime with timezone value of this platform.
2880
     *
2881
     * @return string The format string.
2882
     */
2883
    public function getDateTimeTzFormatString() : string
2884
    {
2885
        return 'Y-m-d H:i:s';
2886
    }
2887 19
2888
    /**
2889 19
     * Gets the format string, as accepted by the date() function, that describes
2890
     * the format of a stored date value of this platform.
2891
     *
2892
     * @return string The format string.
2893
     */
2894
    public function getDateFormatString() : string
2895
    {
2896
        return 'Y-m-d';
2897
    }
2898
2899
    /**
2900
     * Gets the format string, as accepted by the date() function, that describes
2901
     * the format of a stored time value of this platform.
2902
     *
2903
     * @return string The format string.
2904
     */
2905
    public function getTimeFormatString() : string
2906
    {
2907
        return 'H:i:s';
2908
    }
2909
2910
    /**
2911
     * Adds an driver-specific LIMIT clause to the query.
2912
     *
2913
     * @throws DBALException
2914
     */
2915
    final public function modifyLimitQuery(string $query, ?int $limit, int $offset = 0) : string
2916
    {
2917
        if ($offset < 0) {
2918
            throw new DBALException(sprintf(
2919
                'Offset must be a positive integer or zero, %d given',
2920
                $offset
2921
            ));
2922
        }
2923
2924
        if ($offset > 0 && ! $this->supportsLimitOffset()) {
2925
            throw new DBALException(sprintf(
2926
                'Platform %s does not support offset values in limit queries.',
2927
                $this->getName()
2928 150
            ));
2929
        }
2930 150
2931
        return $this->doModifyLimitQuery($query, $limit, $offset);
2932
    }
2933
2934
    /**
2935
     * Adds an platform-specific LIMIT clause to the query.
2936
     */
2937
    protected function doModifyLimitQuery(string $query, ?int $limit, int $offset) : string
2938
    {
2939
        if ($limit !== null) {
2940
            $query .= sprintf(' LIMIT %d', $limit);
2941
        }
2942
2943
        if ($offset > 0) {
2944
            $query .= sprintf(' OFFSET %d', $offset);
2945
        }
2946
2947
        return $query;
2948
    }
2949
2950
    /**
2951
     * Whether the database platform support offsets in modify limit clauses.
2952
     */
2953
    public function supportsLimitOffset() : bool
2954
    {
2955
        return true;
2956
    }
2957
2958
    /**
2959
     * Gets the character casing of a column in an SQL result set of this platform.
2960
     *
2961
     * @param string $column The column name for which to get the correct character casing.
2962
     *
2963
     * @return string The column name in the character casing used in SQL result sets.
2964
     */
2965
    public function getSQLResultCasing(string $column) : string
2966
    {
2967
        return $column;
2968
    }
2969 1196
2970
    /**
2971 1196
     * Makes any fixes to a name of a schema element (table, sequence, ...) that are required
2972
     * by restrictions of the platform, like a maximum length.
2973
     */
2974
    public function fixSchemaElementName(string $schemaElementName) : string
2975
    {
2976
        return $schemaElementName;
2977
    }
2978
2979
    /**
2980
     * Maximum length of any given database identifier, like tables or column names.
2981
     */
2982
    public function getMaxIdentifierLength() : int
2983
    {
2984
        return 63;
2985
    }
2986
2987
    /**
2988
     * Returns the insert SQL for an empty insert statement.
2989
     */
2990
    public function getEmptyIdentityInsertSQL(string $tableName, string $identifierColumnName) : string
2991
    {
2992
        return 'INSERT INTO ' . $tableName . ' (' . $identifierColumnName . ') VALUES (null)';
2993 67
    }
2994
2995 67
    /**
2996
     * Generates a Truncate Table SQL statement for a given table.
2997
     *
2998
     * Cascade is not supported on many platforms but would optionally cascade the truncate by
2999
     * following the foreign keys.
3000
     */
3001
    public function getTruncateTableSQL(string $tableName, bool $cascade = false) : string
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

3001
    public function getTruncateTableSQL(string $tableName, /** @scrutinizer ignore-unused */ bool $cascade = false) : string

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...
3002
    {
3003
        $tableIdentifier = new Identifier($tableName);
3004
3005
        return 'TRUNCATE ' . $tableIdentifier->getQuotedName($this);
3006 23
    }
3007
3008 23
    /**
3009
     * This is for test reasons, many vendors have special requirements for dummy statements.
3010
     */
3011
    public function getDummySelectSQL(string $expression = '1') : string
3012
    {
3013
        return sprintf('SELECT %s', $expression);
3014
    }
3015
3016
    /**
3017
     * Returns the SQL to create a new savepoint.
3018
     */
3019
    public function createSavePoint(string $savepoint) : string
3020 164
    {
3021
        return 'SAVEPOINT ' . $savepoint;
3022 164
    }
3023
3024
    /**
3025
     * Returns the SQL to release a savepoint.
3026
     */
3027
    public function releaseSavePoint(string $savepoint) : string
3028
    {
3029
        return 'RELEASE SAVEPOINT ' . $savepoint;
3030
    }
3031
3032
    /**
3033
     * Returns the SQL to rollback a savepoint.
3034
     */
3035
    public function rollbackSavePoint(string $savepoint) : string
3036
    {
3037
        return 'ROLLBACK TO SAVEPOINT ' . $savepoint;
3038
    }
3039
3040
    /**
3041
     * Returns the keyword list instance of this platform.
3042
     *
3043
     * @throws DBALException If no keyword list is specified.
3044
     */
3045
    final public function getReservedKeywordsList() : KeywordList
3046
    {
3047
        // Check for an existing instantiation of the keywords class.
3048
        if ($this->_keywords) {
3049
            return $this->_keywords;
3050
        }
3051
3052
        $class    = $this->getReservedKeywordsClass();
3053
        $keywords = new $class();
3054
        if (! $keywords instanceof KeywordList) {
3055
            throw DBALException::notSupported(__METHOD__);
3056
        }
3057 152
3058
        // Store the instance so it doesn't need to be generated on every request.
3059 152
        $this->_keywords = $keywords;
3060
3061
        return $keywords;
3062
    }
3063
3064
    /**
3065
     * Returns the class name of the reserved keywords list.
3066
     *
3067 19
     * @return string
3068
     *
3069 19
     * @throws DBALException If not supported on this platform.
3070
     */
3071
    protected function getReservedKeywordsClass()
3072
    {
3073
        throw DBALException::notSupported(__METHOD__);
3074
    }
3075
3076
    /**
3077 2037
     * Quotes a literal string.
3078
     * This method is NOT meant to fix SQL injections!
3079 2037
     * It is only meant to escape this platform's string literal
3080
     * quote character inside the given literal string.
3081
     *
3082
     * @param string $str The literal string to be quoted.
3083
     *
3084
     * @return string The quoted literal string.
3085
     */
3086
    public function quoteStringLiteral(string $str) : string
3087 38
    {
3088
        $c = $this->getStringLiteralQuoteCharacter();
3089 38
3090
        return $c . str_replace($c, $c . $c, $str) . $c;
3091
    }
3092
3093
    /**
3094
     * Gets the character used for string literal quoting.
3095
     */
3096
    public function getStringLiteralQuoteCharacter() : string
3097 19
    {
3098
        return "'";
3099 19
    }
3100
3101
    /**
3102
     * Escapes metacharacters in a string intended to be used with a LIKE
3103
     * operator.
3104
     *
3105
     * @param string $inputString a literal, unquoted string
3106
     * @param string $escapeChar  should be reused by the caller in the LIKE
3107 247
     *                            expression.
3108
     */
3109 247
    final public function escapeStringForLike(string $inputString, string $escapeChar) : string
3110
    {
3111
        return preg_replace(
3112
            '~([' . preg_quote($this->getLikeWildcardCharacters() . $escapeChar, '~') . '])~u',
3113
            addcslashes($escapeChar, '\\') . '$1',
3114
            $inputString
3115
        );
3116
    }
3117 34
3118
    protected function getLikeWildcardCharacters() : string
3119 34
    {
3120
        return '%_';
3121
    }
3122
}
3123