AbstractPlatform::getColumnDeclarationSQL()   B
last analyzed

Complexity

Conditions 10
Paths 65

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 10

Importance

Changes 0
Metric Value
cc 10
eloc 17
nc 65
nop 2
dl 0
loc 29
ccs 17
cts 17
cp 1
crap 10
rs 7.6666
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\DBAL\Platforms;
6
7
use Doctrine\Common\EventManager;
8
use Doctrine\DBAL\DBALException;
9
use Doctrine\DBAL\Event\SchemaAlterTableAddColumnEventArgs;
10
use Doctrine\DBAL\Event\SchemaAlterTableChangeColumnEventArgs;
11
use Doctrine\DBAL\Event\SchemaAlterTableEventArgs;
12
use Doctrine\DBAL\Event\SchemaAlterTableRemoveColumnEventArgs;
13
use Doctrine\DBAL\Event\SchemaAlterTableRenameColumnEventArgs;
14
use Doctrine\DBAL\Event\SchemaCreateTableColumnEventArgs;
15
use Doctrine\DBAL\Event\SchemaCreateTableEventArgs;
16
use Doctrine\DBAL\Event\SchemaDropTableEventArgs;
17
use Doctrine\DBAL\Events;
18
use Doctrine\DBAL\Exception\ColumnLengthRequired;
19
use Doctrine\DBAL\Platforms\Exception\NoColumnsSpecifiedForTable;
20
use Doctrine\DBAL\Platforms\Exception\NotSupported;
21
use Doctrine\DBAL\Platforms\Keywords\KeywordList;
22
use Doctrine\DBAL\Schema\Column;
23
use Doctrine\DBAL\Schema\ColumnDiff;
24
use Doctrine\DBAL\Schema\Constraint;
25
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
26
use Doctrine\DBAL\Schema\Identifier;
27
use Doctrine\DBAL\Schema\Index;
28
use Doctrine\DBAL\Schema\Sequence;
29
use Doctrine\DBAL\Schema\Table;
30
use Doctrine\DBAL\Schema\TableDiff;
31
use Doctrine\DBAL\Schema\UniqueConstraint;
32
use Doctrine\DBAL\TransactionIsolationLevel;
33
use Doctrine\DBAL\Types;
34
use Doctrine\DBAL\Types\Exception\TypeNotFound;
35
use Doctrine\DBAL\Types\Type;
36
use InvalidArgumentException;
37
use UnexpectedValueException;
38
use function addcslashes;
39
use function array_map;
40
use function array_merge;
41
use function array_unique;
42
use function array_values;
43
use function assert;
44
use function count;
45
use function explode;
46
use function implode;
47
use function in_array;
48
use function is_array;
49
use function is_bool;
50
use function is_float;
51
use function is_int;
52
use function is_string;
53
use function preg_quote;
54
use function preg_replace;
55
use function sprintf;
56
use function str_replace;
57
use function strlen;
58
use function strpos;
59
use function strtolower;
60
use function strtoupper;
61
62
/**
63
 * Base class for all DatabasePlatforms. The DatabasePlatforms are the central
64
 * point of abstraction of platform-specific behaviors, features and SQL dialects.
65
 * They are a passive source of information.
66
 *
67
 * @todo Remove any unnecessary methods.
68
 */
69
abstract class AbstractPlatform
70
{
71
    public const CREATE_INDEXES = 1;
72
73
    public const CREATE_FOREIGNKEYS = 2;
74
75
    /** @var string[]|null */
76
    protected $doctrineTypeMapping = null;
77
78
    /**
79
     * Contains a list of all columns that should generate parseable column comments for type-detection
80
     * in reverse engineering scenarios.
81
     *
82
     * @var string[]|null
83
     */
84
    protected $doctrineTypeComments = null;
85
86
    /** @var EventManager|null */
87
    protected $_eventManager;
88
89
    /**
90
     * Holds the KeywordList instance for the current platform.
91
     *
92
     * @var KeywordList|null
93
     */
94
    protected $_keywords;
95
96 41259
    public function __construct()
97
    {
98 41259
    }
99
100
    /**
101
     * Sets the EventManager used by the Platform.
102
     */
103 1275
    public function setEventManager(EventManager $eventManager) : void
104
    {
105 1275
        $this->_eventManager = $eventManager;
106 1275
    }
107
108
    /**
109
     * Gets the EventManager used by the Platform.
110
     */
111 1678
    public function getEventManager() : ?EventManager
112
    {
113 1678
        return $this->_eventManager;
114
    }
115
116
    /**
117
     * Returns the SQL snippet that declares a boolean column.
118
     *
119
     * @param mixed[] $columnDef
120
     */
121
    abstract public function getBooleanTypeDeclarationSQL(array $columnDef) : string;
122
123
    /**
124
     * Returns the SQL snippet that declares a 4 byte integer column.
125
     *
126
     * @param mixed[] $columnDef
127
     */
128
    abstract public function getIntegerTypeDeclarationSQL(array $columnDef) : string;
129
130
    /**
131
     * Returns the SQL snippet that declares an 8 byte integer column.
132
     *
133
     * @param mixed[] $columnDef
134
     */
135
    abstract public function getBigIntTypeDeclarationSQL(array $columnDef) : string;
136
137
    /**
138
     * Returns the SQL snippet that declares a 2 byte integer column.
139
     *
140
     * @param mixed[] $columnDef
141
     */
142
    abstract public function getSmallIntTypeDeclarationSQL(array $columnDef) : string;
143
144
    /**
145
     * Returns the SQL snippet that declares common properties of an integer column.
146
     *
147
     * @param mixed[] $columnDef
148
     */
149
    abstract protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef) : string;
150
151
    /**
152
     * Lazy load Doctrine Type Mappings.
153
     */
154
    abstract protected function initializeDoctrineTypeMappings() : void;
155
156
    /**
157
     * Initializes Doctrine Type Mappings with the platform defaults
158
     * and with all additional type mappings.
159
     */
160 1266
    private function initializeAllDoctrineTypeMappings() : void
161
    {
162 1266
        $this->initializeDoctrineTypeMappings();
163
164 1266
        foreach (Type::getTypesMap() as $typeName => $className) {
165 1266
            foreach (Type::getType($typeName)->getMappedDatabaseTypes($this) as $dbType) {
166 684
                $this->doctrineTypeMapping[$dbType] = $typeName;
167
            }
168
        }
169 1266
    }
170
171
    /**
172
     * Returns the SQL snippet used to declare a string column type.
173
     *
174
     * @param array<string, mixed> $column The column definition.
175
     *
176
     * @throws ColumnLengthRequired
177
     */
178 5789
    public function getStringTypeDeclarationSQL(array $column) : string
179
    {
180 5789
        $length = $column['length'] ?? null;
181
182 5789
        if (empty($column['fixed'])) {
183 4919
            return $this->getVarcharTypeDeclarationSQLSnippet($length);
184
        }
185
186 1002
        return $this->getCharTypeDeclarationSQLSnippet($length);
187
    }
188
189
    /**
190
     * Returns the SQL snippet used to declare a binary string column type.
191
     *
192
     * @param array<string, mixed> $column The column definition.
193
     *
194
     * @throws ColumnLengthRequired
195
     */
196 989
    public function getBinaryTypeDeclarationSQL(array $column) : string
197
    {
198 989
        $length = $column['length'] ?? null;
199
200 989
        if (empty($column['fixed'])) {
201 505
            return $this->getVarbinaryTypeDeclarationSQLSnippet($length);
202
        }
203
204 527
        return $this->getBinaryTypeDeclarationSQLSnippet($length);
205
    }
206
207
    /**
208
     * Returns the SQL snippet to declare a GUID/UUID field.
209
     *
210
     * By default this maps directly to a CHAR(36) and only maps to more
211
     * special datatypes when the underlying databases support this datatype.
212
     *
213
     * @param array<string, mixed> $column The column definition.
214
     *
215
     * @throws DBALException
216
     */
217 144
    public function getGuidTypeDeclarationSQL(array $column) : string
218
    {
219 144
        $column['length'] = 36;
220 144
        $column['fixed']  = true;
221
222 144
        return $this->getStringTypeDeclarationSQL($column);
223
    }
224
225
    /**
226
     * Returns the SQL snippet to declare a JSON field.
227
     *
228
     * By default this maps directly to a CLOB and only maps to more
229
     * special datatypes when the underlying databases support this datatype.
230
     *
231
     * @param mixed[] $field
232
     */
233 271
    public function getJsonTypeDeclarationSQL(array $field) : string
234
    {
235 271
        return $this->getClobTypeDeclarationSQL($field);
236
    }
237
238
    /**
239
     * @param int|null $length The length of the column in characters
240
     *                         or NULL if the length should be omitted.
241
     *
242
     * @throws ColumnLengthRequired
243
     */
244 945
    protected function getCharTypeDeclarationSQLSnippet(?int $length) : string
245
    {
246 945
        $sql = 'CHAR';
247
248 945
        if ($length !== null) {
249 725
            $sql .= sprintf('(%d)', $length);
250
        }
251
252 945
        return $sql;
253
    }
254
255
    /**
256
     * @param int|null $length The length of the column in characters
257
     *                         or NULL if the length should be omitted.
258
     *
259
     * @throws ColumnLengthRequired
260
     */
261 2578
    protected function getVarcharTypeDeclarationSQLSnippet(?int $length) : string
262
    {
263 2578
        if ($length === null) {
264 132
            throw ColumnLengthRequired::new($this, 'VARCHAR');
265
        }
266
267 2446
        return sprintf('VARCHAR(%d)', $length);
268
    }
269
270
    /**
271
     * Returns the SQL snippet used to declare a fixed length binary column type.
272
     *
273
     * @param int|null $length The length of the column in bytes
274
     *                         or NULL if the length should be omitted.
275
     *
276
     * @throws ColumnLengthRequired
277
     */
278 292
    protected function getBinaryTypeDeclarationSQLSnippet(?int $length) : string
279
    {
280 292
        $sql = 'BINARY';
281
282 292
        if ($length !== null) {
283 146
            $sql .= sprintf('(%d)', $length);
284
        }
285
286 292
        return $sql;
287
    }
288
289
    /**
290
     * Returns the SQL snippet used to declare a variable length binary column type.
291
     *
292
     * @param int|null $length The length of the column in bytes
293
     *                         or NULL if the length should be omitted.
294
     *
295
     * @throws ColumnLengthRequired
296
     */
297 270
    protected function getVarbinaryTypeDeclarationSQLSnippet(?int $length) : string
298
    {
299 270
        if ($length === null) {
300 110
            throw ColumnLengthRequired::new($this, 'VARBINARY');
301
        }
302
303 160
        return sprintf('VARBINARY(%d)', $length);
304
    }
305
306
    /**
307
     * Returns the SQL snippet used to declare a CLOB column type.
308
     *
309
     * @param mixed[] $field
310
     */
311
    abstract public function getClobTypeDeclarationSQL(array $field) : string;
312
313
    /**
314
     * Returns the SQL Snippet used to declare a BLOB column type.
315
     *
316
     * @param mixed[] $field
317
     */
318
    abstract public function getBlobTypeDeclarationSQL(array $field) : string;
319
320
    /**
321
     * Gets the name of the platform.
322
     */
323
    abstract public function getName() : string;
324
325
    /**
326
     * Registers a doctrine type to be used in conjunction with a column type of this platform.
327
     *
328
     * @throws DBALException If the type is not found.
329
     */
330 687
    public function registerDoctrineTypeMapping(string $dbType, string $doctrineType) : void
331
    {
332 687
        if ($this->doctrineTypeMapping === null) {
333 682
            $this->initializeAllDoctrineTypeMappings();
334
        }
335
336 687
        if (! Types\Type::hasType($doctrineType)) {
337 220
            throw TypeNotFound::new($doctrineType);
338
        }
339
340 467
        $dbType                             = strtolower($dbType);
341 467
        $this->doctrineTypeMapping[$dbType] = $doctrineType;
342
343 467
        $doctrineType = Type::getType($doctrineType);
344
345 467
        if (! $doctrineType->requiresSQLCommentHint($this)) {
346 247
            return;
347
        }
348
349 220
        $this->markDoctrineTypeCommented($doctrineType);
350 220
    }
351
352
    /**
353
     * Gets the Doctrine type that is mapped for the given database column type.
354
     *
355
     * @throws DBALException
356
     */
357 2287
    public function getDoctrineTypeMapping(string $dbType) : string
358
    {
359 2287
        if ($this->doctrineTypeMapping === null) {
360 298
            $this->initializeAllDoctrineTypeMappings();
361
        }
362
363 2287
        $dbType = strtolower($dbType);
364
365 2287
        if (! isset($this->doctrineTypeMapping[$dbType])) {
366 220
            throw new DBALException(sprintf(
367 10
                'Unknown database type "%s" requested, %s may not support it.',
368 220
                $dbType,
369 220
                static::class
370
            ));
371
        }
372
373 2067
        return $this->doctrineTypeMapping[$dbType];
374
    }
375
376
    /**
377
     * Checks if a database type is currently supported by this platform.
378
     */
379 328
    public function hasDoctrineTypeMappingFor(string $dbType) : bool
380
    {
381 328
        if ($this->doctrineTypeMapping === null) {
382 286
            $this->initializeAllDoctrineTypeMappings();
383
        }
384
385 328
        $dbType = strtolower($dbType);
386
387 328
        return isset($this->doctrineTypeMapping[$dbType]);
388
    }
389
390
    /**
391
     * Initializes the Doctrine Type comments instance variable for in_array() checks.
392
     */
393 10907
    protected function initializeCommentedDoctrineTypes() : void
394
    {
395 10907
        $this->doctrineTypeComments = [];
396
397 10907
        foreach (Type::getTypesMap() as $typeName => $className) {
398 10907
            $type = Type::getType($typeName);
399
400 10907
            if (! $type->requiresSQLCommentHint($this)) {
401 10907
                continue;
402
            }
403
404 10907
            $this->doctrineTypeComments[] = $typeName;
405
        }
406 10907
    }
407
408
    /**
409
     * Is it necessary for the platform to add a parsable type comment to allow reverse engineering the given type?
410
     */
411 14089
    public function isCommentedDoctrineType(Type $doctrineType) : bool
412
    {
413 14089
        if ($this->doctrineTypeComments === null) {
414 10687
            $this->initializeCommentedDoctrineTypes();
415
        }
416
417 14089
        assert(is_array($this->doctrineTypeComments));
418
419 14089
        return in_array($doctrineType->getName(), $this->doctrineTypeComments, true);
420
    }
421
422
    /**
423
     * Marks this type as to be commented in ALTER TABLE and CREATE TABLE statements.
424
     *
425
     * @param string|Type $doctrineType
426
     */
427 220
    public function markDoctrineTypeCommented($doctrineType) : void
428
    {
429 220
        if ($this->doctrineTypeComments === null) {
430 220
            $this->initializeCommentedDoctrineTypes();
431
        }
432
433 220
        assert(is_array($this->doctrineTypeComments));
434
435 220
        $this->doctrineTypeComments[] = $doctrineType instanceof Type ? $doctrineType->getName() : $doctrineType;
436 220
    }
437
438
    /**
439
     * Gets the comment to append to a column comment that helps parsing this type in reverse engineering.
440
     */
441 659
    public function getDoctrineTypeComment(Type $doctrineType) : string
442
    {
443 659
        return '(DC2Type:' . $doctrineType->getName() . ')';
444
    }
445
446
    /**
447
     * Gets the comment of a passed column modified by potential doctrine type comment hints.
448
     */
449 8612
    protected function getColumnComment(Column $column) : string
450
    {
451 8612
        $comment = $column->getComment();
452
453 8612
        if ($this->isCommentedDoctrineType($column->getType())) {
454 659
            $comment .= $this->getDoctrineTypeComment($column->getType());
455
        }
456
457 8612
        return $comment;
458
    }
459
460
    /**
461
     * Gets the character used for identifier quoting.
462
     */
463 3780
    public function getIdentifierQuoteCharacter() : string
464
    {
465 3780
        return '"';
466
    }
467
468
    /**
469
     * Gets the string portion that starts an SQL comment.
470
     */
471
    public function getSqlCommentStartString() : string
472
    {
473
        return '--';
474
    }
475
476
    /**
477
     * Gets the string portion that ends an SQL comment.
478
     */
479
    public function getSqlCommentEndString() : string
480
    {
481
        return "\n";
482
    }
483
484
    /**
485
     * Gets all SQL wildcard characters of the platform.
486
     *
487
     * @return string[]
488
     */
489
    public function getWildcards() : array
490
    {
491
        return ['%', '_'];
492
    }
493
494
    /**
495
     * Returns the regular expression operator.
496
     *
497
     * @throws DBALException If not supported on this platform.
498
     */
499 44
    public function getRegexpExpression() : string
500
    {
501 44
        throw NotSupported::new(__METHOD__);
502
    }
503
504
    /**
505
     * Returns the SQL snippet to get the average value of a column.
506
     *
507
     * @param string $value SQL expression producing the value.
508
     */
509
    public function getAvgExpression(string $value) : string
510
    {
511
        return 'AVG(' . $value . ')';
512
    }
513
514
    /**
515
     * Returns the SQL snippet to get the number of rows (without a NULL value) of a column.
516
     *
517
     * If a '*' is used instead of a column the number of selected rows is returned.
518
     *
519
     * @param string $expression The expression to count.
520
     */
521
    public function getCountExpression(string $expression) : string
522
    {
523
        return 'COUNT(' . $expression . ')';
524
    }
525
526
    /**
527
     * Returns the SQL snippet to get the maximum value in a set of values.
528
     *
529
     * @param string $value SQL expression producing the value.
530
     */
531
    public function getMaxExpression(string $value) : string
532
    {
533
        return 'MAX(' . $value . ')';
534
    }
535
536
    /**
537
     * Returns the SQL snippet to get the minimum value in a set of values.
538
     *
539
     * @param string $value SQL expression producing the value.
540
     */
541
    public function getMinExpression(string $value) : string
542
    {
543
        return 'MIN(' . $value . ')';
544
    }
545
546
    /**
547
     * Returns the SQL snippet to get the total sum of the values in a set.
548
     *
549
     * @param string $value SQL expression producing the value.
550
     */
551
    public function getSumExpression(string $value) : string
552
    {
553
        return 'SUM(' . $value . ')';
554
    }
555
556
    // scalar functions
557
558
    /**
559
     * Returns the SQL snippet to get the md5 sum of the value.
560
     *
561
     * Note: Not SQL92, but common functionality.
562
     *
563
     * @param string $string SQL expression producing the string.
564
     */
565
    public function getMd5Expression(string $string) : string
566
    {
567
        return 'MD5(' . $string . ')';
568
    }
569
570
    /**
571
     * Returns the SQL snippet to get the length of a text field.
572
     *
573
     * @param string $string SQL expression producing the string.
574
     */
575
    public function getLengthExpression(string $string) : string
576
    {
577
        return 'LENGTH(' . $string . ')';
578
    }
579
580
    /**
581
     * Returns the SQL snippet to get the square root of the value.
582
     *
583
     * @param string $number SQL expression producing the number.
584
     */
585
    public function getSqrtExpression(string $number) : string
586
    {
587
        return 'SQRT(' . $number . ')';
588
    }
589
590
    /**
591
     * Returns the SQL snippet to round a number to the number of decimals specified.
592
     *
593
     * @param string $number   SQL expression producing the number to round.
594
     * @param string $decimals SQL expression producing the number of decimals.
595
     */
596
    public function getRoundExpression(string $number, string $decimals = '0') : string
597
    {
598
        return 'ROUND(' . $number . ', ' . $decimals . ')';
599
    }
600
601
    /**
602
     * Returns the SQL snippet to get the remainder of the operation of division of dividend by divisor.
603
     *
604
     * @param string $dividend SQL expression producing the dividend.
605
     * @param string $divisor  SQL expression producing the divisor.
606
     */
607
    public function getModExpression(string $dividend, string $divisor) : string
608
    {
609
        return 'MOD(' . $dividend . ', ' . $divisor . ')';
610
    }
611
612
    /**
613
     * Returns the SQL snippet to trim a string.
614
     *
615
     * @param string      $str  The expression to apply the trim to.
616
     * @param int         $mode The position of the trim (leading/trailing/both).
617
     * @param string|null $char The char to trim, has to be quoted already. Defaults to space.
618
     *
619
     * @throws InvalidArgumentException
620
     */
621 703
    public function getTrimExpression(string $str, int $mode = TrimMode::UNSPECIFIED, ?string $char = null) : string
622
    {
623 703
        $tokens = [];
624
625 703
        switch ($mode) {
626
            case TrimMode::UNSPECIFIED:
627 171
                break;
628
629
            case TrimMode::LEADING:
630 171
                $tokens[] = 'LEADING';
631 171
                break;
632
633
            case TrimMode::TRAILING:
634 171
                $tokens[] = 'TRAILING';
635 171
                break;
636
637
            case TrimMode::BOTH:
638 171
                $tokens[] = 'BOTH';
639 171
                break;
640
641
            default:
642 19
                throw new InvalidArgumentException(
643 19
                    sprintf(
644 1
                        'The value of $mode is expected to be one of the TrimMode constants, %d given.',
645 19
                        $mode
646
                    )
647
                );
648
        }
649
650 684
        if ($char !== null) {
651 532
            $tokens[] = $char;
652
        }
653
654 684
        if (count($tokens) > 0) {
655 646
            $tokens[] = 'FROM';
656
        }
657
658 684
        $tokens[] = $str;
659
660 684
        return sprintf('TRIM(%s)', implode(' ', $tokens));
661
    }
662
663
    /**
664
     * Returns the SQL snippet to trim trailing space characters from the string.
665
     *
666
     * @param string $string SQL expression producing the string.
667
     */
668 22
    public function getRtrimExpression(string $string) : string
669
    {
670 22
        return 'RTRIM(' . $string . ')';
671
    }
672
673
    /**
674
     * Returns the SQL snippet to trim leading space characters from the string.
675
     *
676
     * @param string $string SQL expression producing the string.
677
     */
678 22
    public function getLtrimExpression(string $string) : string
679
    {
680 22
        return 'LTRIM(' . $string . ')';
681
    }
682
683
    /**
684
     * Returns the SQL snippet to change all characters from the string to uppercase,
685
     * according to the current character set mapping.
686
     *
687
     * @param string $string SQL expression producing the string.
688
     */
689
    public function getUpperExpression(string $string) : string
690
    {
691
        return 'UPPER(' . $string . ')';
692
    }
693
694
    /**
695
     * Returns the SQL snippet to change all characters from the string to lowercase,
696
     * according to the current character set mapping.
697
     *
698
     * @param string $string SQL expression producing the string.
699
     */
700
    public function getLowerExpression(string $string) : string
701
    {
702
        return 'LOWER(' . $string . ')';
703
    }
704
705
    /**
706
     * Returns the SQL snippet to get the position of the first occurrence of the substring in the string.
707
     *
708
     * @param string      $string    SQL expression producing the string to locate the substring in.
709
     * @param string      $substring SQL expression producing the substring to locate.
710
     * @param string|null $start     SQL expression producing the position to start at.
711
     *                               Defaults to the beginning of the string.
712
     *
713
     * @throws DBALException If not supported on this platform.
714
     */
715
    public function getLocateExpression(string $string, string $substring, ?string $start = null) : string
0 ignored issues
show
Unused Code introduced by
The parameter $substring 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

715
    public function getLocateExpression(string $string, /** @scrutinizer ignore-unused */ string $substring, ?string $start = 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...
716
    {
717
        throw NotSupported::new(__METHOD__);
718
    }
719
720
    /**
721
     * Returns the SQL snippet to get the current system date.
722
     */
723
    public function getNowExpression() : string
724
    {
725
        return 'NOW()';
726
    }
727
728
    /**
729
     * Returns an SQL snippet to get a substring inside the string.
730
     *
731
     * Note: Not SQL92, but common functionality.
732
     *
733
     * @param string      $string SQL expression producing the string from which a substring should be extracted.
734
     * @param string      $start  SQL expression producing the position to start at,
735
     * @param string|null $length SQL expression producing the length of the substring portion to be returned.
736
     *                            By default, the entire substring is returned.
737
     */
738 100
    public function getSubstringExpression(string $string, string $start, ?string $length = null) : string
739
    {
740 100
        if ($length === null) {
741 66
            return sprintf('SUBSTRING(%s FROM %s)', $string, $start);
742
        }
743
744 78
        return sprintf('SUBSTRING(%s FROM %s FOR %s)', $string, $start, $length);
745
    }
746
747
    /**
748
     * Returns a SQL snippet to concatenate the given strings.
749
     *
750
     * @param string[] ...$string
751
     */
752 159
    public function getConcatExpression(string ...$string) : string
753
    {
754 159
        return implode(' || ', $string);
755
    }
756
757
    /**
758
     * Returns the SQL for a logical not.
759
     *
760
     * @param string $value SQL expression producing the value to negate.
761
     */
762
    public function getNotExpression(string $value) : string
763
    {
764
        return 'NOT(' . $value . ')';
765
    }
766
767
    /**
768
     * Returns the SQL that checks if an expression is null.
769
     *
770
     * @param string $value SQL expression producing the to be compared to null.
771
     */
772 88
    public function getIsNullExpression(string $value) : string
773
    {
774 88
        return $value . ' IS NULL';
775
    }
776
777
    /**
778
     * Returns the SQL that checks if an expression is not null.
779
     *
780
     * @param string $value SQL expression producing the to be compared to null.
781
     */
782
    public function getIsNotNullExpression(string $value) : string
783
    {
784
        return $value . ' IS NOT NULL';
785
    }
786
787
    /**
788
     * Returns the SQL that checks if an expression evaluates to a value between two values.
789
     *
790
     * The parameter $value is checked if it is between $min and $max.
791
     *
792
     * Note: There is a slight difference in the way BETWEEN works on some databases.
793
     * http://www.w3schools.com/sql/sql_between.asp. If you want complete database
794
     * independence you should avoid using between().
795
     *
796
     * @param string $value SQL expression producing the value to compare.
797
     * @param string $min   SQL expression producing the lower value to compare with.
798
     * @param string $max   SQL expression producing the higher value to compare with.
799
     */
800
    public function getBetweenExpression(string $value, string $min, string $max) : string
801
    {
802
        return $value . ' BETWEEN ' . $min . ' AND ' . $max;
803
    }
804
805
    /**
806
     * Returns the SQL to get the arccosine of a value.
807
     *
808
     * @param string $number SQL expression producing the number.
809
     */
810
    public function getAcosExpression(string $number) : string
811
    {
812
        return 'ACOS(' . $number . ')';
813
    }
814
815
    /**
816
     * Returns the SQL to get the sine of a value.
817
     *
818
     * @param string $number SQL expression producing the number.
819
     */
820
    public function getSinExpression(string $number) : string
821
    {
822
        return 'SIN(' . $number . ')';
823
    }
824
825
    /**
826
     * Returns the SQL to get the PI value.
827
     */
828
    public function getPiExpression() : string
829
    {
830
        return 'PI()';
831
    }
832
833
    /**
834
     * Returns the SQL to get the cosine of a value.
835
     *
836
     * @param string $number SQL expression producing the number.
837
     */
838
    public function getCosExpression(string $number) : string
839
    {
840
        return 'COS(' . $number . ')';
841
    }
842
843
    /**
844
     * Returns the SQL to calculate the difference in days between the two passed dates.
845
     *
846
     * Computes diff = date1 - date2.
847
     *
848
     * @throws DBALException If not supported on this platform.
849
     */
850
    public function getDateDiffExpression(string $date1, string $date2) : string
0 ignored issues
show
Unused Code introduced by
The parameter $date1 is not used and could be removed. ( Ignorable by Annotation )

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

850
    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...
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

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

1075
    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...
Unused Code introduced by
The parameter $unit is not used and could be removed. ( Ignorable by Annotation )

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

1075
    protected function getDateArithmeticIntervalExpression(string $date, string $operator, string $interval, /** @scrutinizer ignore-unused */ 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...
1076
    {
1077
        throw NotSupported::new(__METHOD__);
1078
    }
1079
1080
    /**
1081
     * Generates the SQL expression which represents the given date interval multiplied by a number
1082
     *
1083
     * @param string $interval   SQL expression describing the interval value
1084
     * @param int    $multiplier Interval multiplier
1085
     *
1086
     * @throws DBALException
1087
     */
1088 88
    protected function multiplyInterval(string $interval, int $multiplier) : string
1089
    {
1090 88
        return sprintf('(%s * %d)', $interval, $multiplier);
1091
    }
1092
1093
    /**
1094
     * Returns the SQL bit AND comparison expression.
1095
     *
1096
     * @param string $value1 SQL expression producing the first value.
1097
     * @param string $value2 SQL expression producing the second value.
1098
     */
1099 196
    public function getBitAndComparisonExpression(string $value1, string $value2) : string
1100
    {
1101 196
        return '(' . $value1 . ' & ' . $value2 . ')';
1102
    }
1103
1104
    /**
1105
     * Returns the SQL bit OR comparison expression.
1106
     *
1107
     * @param string $value1 SQL expression producing the first value.
1108
     * @param string $value2 SQL expression producing the second value.
1109
     */
1110 196
    public function getBitOrComparisonExpression(string $value1, string $value2) : string
1111
    {
1112 196
        return '(' . $value1 . ' | ' . $value2 . ')';
1113
    }
1114
1115
    /**
1116
     * Returns the SQL expression which represents the currently selected database.
1117
     */
1118
    abstract public function getCurrentDatabaseExpression() : string;
1119
1120
    /**
1121
     * Returns the FOR UPDATE expression.
1122
     */
1123 36
    public function getForUpdateSQL() : string
1124
    {
1125 36
        return 'FOR UPDATE';
1126
    }
1127
1128
    /**
1129
     * Honors that some SQL vendors such as MsSql use table hints for locking instead of the ANSI SQL FOR UPDATE specification.
1130
     *
1131
     * @param string   $fromClause The FROM clause to append the hint for the given lock mode to.
1132
     * @param int|null $lockMode   One of the Doctrine\DBAL\LockMode::* constants. If null is given, nothing will
1133
     *                             be appended to the FROM clause.
1134
     */
1135 38
    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

1135
    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...
1136
    {
1137 38
        return $fromClause;
1138
    }
1139
1140
    /**
1141
     * Returns the SQL snippet to append to any SELECT statement which locks rows in shared read lock.
1142
     *
1143
     * This defaults to the ANSI SQL "FOR UPDATE", which is an exclusive lock (Write). Some database
1144
     * vendors allow to lighten this constraint up to be a real read lock.
1145
     */
1146
    public function getReadLockSQL() : string
1147
    {
1148
        return $this->getForUpdateSQL();
1149
    }
1150
1151
    /**
1152
     * Returns the SQL snippet to append to any SELECT statement which obtains an exclusive lock on the rows.
1153
     *
1154
     * The semantics of this lock mode should equal the SELECT .. FOR UPDATE of the ANSI SQL standard.
1155
     */
1156 42
    public function getWriteLockSQL() : string
1157
    {
1158 42
        return $this->getForUpdateSQL();
1159
    }
1160
1161
    /**
1162
     * Returns the SQL snippet to drop an existing database.
1163
     *
1164
     * @param string $database The name of the database that should be dropped.
1165
     */
1166 54
    public function getDropDatabaseSQL(string $database) : string
1167
    {
1168 54
        return 'DROP DATABASE ' . $database;
1169
    }
1170
1171
    /**
1172
     * Returns the SQL snippet to drop an existing table.
1173
     *
1174
     * @param Table|string $table
1175
     *
1176
     * @throws InvalidArgumentException
1177
     */
1178 3959
    public function getDropTableSQL($table) : string
1179
    {
1180 3959
        $tableArg = $table;
1181
1182 3959
        if ($table instanceof Table) {
1183 320
            $table = $table->getQuotedName($this);
1184
        }
1185
1186 3959
        if (! is_string($table)) {
0 ignored issues
show
introduced by
The condition is_string($table) is always true.
Loading history...
1187
            throw new InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
1188
        }
1189
1190 3959
        if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaDropTable)) {
1191 220
            $eventArgs = new SchemaDropTableEventArgs($tableArg, $this);
1192 220
            $this->_eventManager->dispatchEvent(Events::onSchemaDropTable, $eventArgs);
1193
1194 220
            if ($eventArgs->isDefaultPrevented()) {
1195
                $sql = $eventArgs->getSql();
1196
1197
                if ($sql === null) {
1198
                    throw new UnexpectedValueException('Default implementation of DROP TABLE was overridden with NULL.');
1199
                }
1200
1201
                return $sql;
1202
            }
1203
        }
1204
1205 3959
        return 'DROP TABLE ' . $table;
1206
    }
1207
1208
    /**
1209
     * Returns the SQL to safely drop a temporary table WITHOUT implicitly committing an open transaction.
1210
     *
1211
     * @param Table|string $table
1212
     */
1213 18
    public function getDropTemporaryTableSQL($table) : string
1214
    {
1215 18
        return $this->getDropTableSQL($table);
1216
    }
1217
1218
    /**
1219
     * Returns the SQL to drop an index from a table.
1220
     *
1221
     * @param Index|string $index
1222
     * @param Table|string $table
1223
     *
1224
     * @throws InvalidArgumentException
1225
     */
1226 135
    public function getDropIndexSQL($index, $table = null) : string
1227
    {
1228 135
        if ($index instanceof Index) {
1229 127
            $index = $index->getQuotedName($this);
1230 8
        } elseif (! is_string($index)) {
0 ignored issues
show
introduced by
The condition is_string($index) is always true.
Loading history...
1231
            throw new InvalidArgumentException('AbstractPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
1232
        }
1233
1234 135
        return 'DROP INDEX ' . $index;
1235
    }
1236
1237
    /**
1238
     * Returns the SQL to drop a constraint.
1239
     *
1240
     * @param Constraint|string $constraint
1241
     * @param Table|string      $table
1242
     */
1243 554
    public function getDropConstraintSQL($constraint, $table) : string
1244
    {
1245 554
        if (! $constraint instanceof Constraint) {
1246 461
            $constraint = new Identifier($constraint);
1247
        }
1248
1249 554
        if (! $table instanceof Table) {
1250 554
            $table = new Identifier($table);
1251
        }
1252
1253 554
        $constraint = $constraint->getQuotedName($this);
1254 554
        $table      = $table->getQuotedName($this);
1255
1256 554
        return 'ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $constraint;
1257
    }
1258
1259
    /**
1260
     * Returns the SQL to drop a foreign key.
1261
     *
1262
     * @param ForeignKeyConstraint|string $foreignKey
1263
     * @param Table|string                $table
1264
     */
1265 351
    public function getDropForeignKeySQL($foreignKey, $table) : string
1266
    {
1267 351
        if (! $foreignKey instanceof ForeignKeyConstraint) {
1268 110
            $foreignKey = new Identifier($foreignKey);
1269
        }
1270
1271 351
        if (! $table instanceof Table) {
1272 351
            $table = new Identifier($table);
1273
        }
1274
1275 351
        $foreignKey = $foreignKey->getQuotedName($this);
1276 351
        $table      = $table->getQuotedName($this);
1277
1278 351
        return 'ALTER TABLE ' . $table . ' DROP FOREIGN KEY ' . $foreignKey;
1279
    }
1280
1281
    /**
1282
     * Returns the SQL statement(s) to create a table with the specified name, columns and constraints
1283
     * on this platform.
1284
     *
1285
     * @return array<int, string> The sequence of SQL statements.
1286
     *
1287
     * @throws DBALException
1288
     */
1289 6994
    public function getCreateTableSQL(Table $table, int $createFlags = self::CREATE_INDEXES) : array
1290
    {
1291 6994
        if (count($table->getColumns()) === 0) {
1292 220
            throw NoColumnsSpecifiedForTable::new($table->getName());
1293
        }
1294
1295 6774
        $tableName                    = $table->getQuotedName($this);
1296 6774
        $options                      = $table->getOptions();
1297 6774
        $options['uniqueConstraints'] = [];
1298 6774
        $options['indexes']           = [];
1299 6774
        $options['primary']           = [];
1300
1301 6774
        if (($createFlags & self::CREATE_INDEXES) > 0) {
1302 6510
            foreach ($table->getIndexes() as $index) {
1303 4437
                if (! $index->isPrimary()) {
1304 1424
                    $options['indexes'][$index->getQuotedName($this)] = $index;
1305
1306 1424
                    continue;
1307
                }
1308
1309 3472
                $options['primary']       = $index->getQuotedColumns($this);
1310 3472
                $options['primary_index'] = $index;
1311
            }
1312
1313 6510
            foreach ($table->getUniqueConstraints() as $uniqueConstraint) {
1314
                /** @var UniqueConstraint $uniqueConstraint */
1315
                $options['uniqueConstraints'][$uniqueConstraint->getQuotedName($this)] = $uniqueConstraint;
1316
            }
1317
        }
1318
1319 6774
        if (($createFlags & self::CREATE_FOREIGNKEYS) > 0) {
1320 4080
            $options['foreignKeys'] = [];
1321
1322 4080
            foreach ($table->getForeignKeys() as $fkConstraint) {
1323 615
                $options['foreignKeys'][] = $fkConstraint;
1324
            }
1325
        }
1326
1327 6774
        $columnSql = [];
1328 6774
        $columns   = [];
1329
1330 6774
        foreach ($table->getColumns() as $column) {
1331 6774
            if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaCreateTableColumn)) {
1332 220
                $eventArgs = new SchemaCreateTableColumnEventArgs($column, $table, $this);
1333 220
                $this->_eventManager->dispatchEvent(Events::onSchemaCreateTableColumn, $eventArgs);
1334
1335 220
                $columnSql = array_merge($columnSql, $eventArgs->getSql());
1336
1337 220
                if ($eventArgs->isDefaultPrevented()) {
1338
                    continue;
1339
                }
1340
            }
1341
1342 6774
            $columnData            = $column->toArray();
1343 6774
            $columnData['name']    = $column->getQuotedName($this);
1344 6774
            $columnData['version'] = $column->hasPlatformOption('version') ? $column->getPlatformOption('version') : false;
1345 6774
            $columnData['comment'] = $this->getColumnComment($column);
1346
1347 6774
            if (in_array($column->getName(), $options['primary'], true)) {
1348 3208
                $columnData['primary'] = true;
1349
            }
1350
1351 6774
            $columns[] = $columnData;
1352
        }
1353
1354 6774
        if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaCreateTable)) {
1355 220
            $eventArgs = new SchemaCreateTableEventArgs($table, $columns, $options, $this);
1356 220
            $this->_eventManager->dispatchEvent(Events::onSchemaCreateTable, $eventArgs);
1357
1358 220
            if ($eventArgs->isDefaultPrevented()) {
1359
                return array_merge($eventArgs->getSql(), $columnSql);
1360
            }
1361
        }
1362
1363 6774
        $sql = $this->_getCreateTableSQL($tableName, $columns, $options);
1364 6774
        if ($this->supportsCommentOnStatement()) {
1365 2478
            if ($table->hasOption('comment')) {
1366 51
                $sql[] = $this->getCommentOnTableSQL($tableName, $table->getOption('comment'));
1367
            }
1368
1369 2478
            foreach ($table->getColumns() as $column) {
1370 2478
                $comment = $this->getColumnComment($column);
1371
1372 2478
                if ($comment === '') {
1373 2346
                    continue;
1374
                }
1375
1376 354
                $sql[] = $this->getCommentOnColumnSQL($tableName, $column->getQuotedName($this), $comment);
1377
            }
1378
        }
1379
1380 6774
        return array_merge($sql, $columnSql);
1381
    }
1382
1383 51
    protected function getCommentOnTableSQL(string $tableName, string $comment) : string
1384
    {
1385 51
        $tableName = new Identifier($tableName);
1386
1387 51
        return sprintf(
1388 3
            'COMMENT ON TABLE %s IS %s',
1389 51
            $tableName->getQuotedName($this),
1390 51
            $this->quoteStringLiteral($comment)
1391
        );
1392
    }
1393
1394 1292
    public function getCommentOnColumnSQL(string $tableName, string $columnName, string $comment) : string
1395
    {
1396 1292
        $tableName  = new Identifier($tableName);
1397 1292
        $columnName = new Identifier($columnName);
1398
1399 1292
        return sprintf(
1400 73
            'COMMENT ON COLUMN %s.%s IS %s',
1401 1292
            $tableName->getQuotedName($this),
1402 1292
            $columnName->getQuotedName($this),
1403 1292
            $this->quoteStringLiteral($comment)
1404
        );
1405
    }
1406
1407
    /**
1408
     * Returns the SQL to create inline comment on a column.
1409
     *
1410
     * @throws DBALException If not supported on this platform.
1411
     */
1412 998
    public function getInlineColumnCommentSQL(string $comment) : string
1413
    {
1414 998
        if (! $this->supportsInlineColumnComments()) {
1415 132
            throw NotSupported::new(__METHOD__);
1416
        }
1417
1418 866
        return 'COMMENT ' . $this->quoteStringLiteral($comment);
1419
    }
1420
1421
    /**
1422
     * Returns the SQL used to create a table.
1423
     *
1424
     * @param mixed[][] $columns
1425
     * @param mixed[]   $options
1426
     *
1427
     * @return array<int, string>
1428
     */
1429 764
    protected function _getCreateTableSQL(string $tableName, array $columns, array $options = []) : array
1430
    {
1431 764
        $columnListSql = $this->getColumnDeclarationListSQL($columns);
1432
1433 764
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
1434
            foreach ($options['uniqueConstraints'] as $name => $definition) {
1435
                $columnListSql .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
1436
            }
1437
        }
1438
1439 764
        if (isset($options['primary']) && ! empty($options['primary'])) {
1440 393
            $columnListSql .= ', PRIMARY KEY(' . implode(', ', array_unique(array_values($options['primary']))) . ')';
1441
        }
1442
1443 764
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
1444
            foreach ($options['indexes'] as $index => $definition) {
1445
                $columnListSql .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
1446
            }
1447
        }
1448
1449 764
        $query = 'CREATE TABLE ' . $tableName . ' (' . $columnListSql;
1450
1451 764
        $check = $this->getCheckDeclarationSQL($columns);
1452 764
        if (! empty($check)) {
1453 22
            $query .= ', ' . $check;
1454
        }
1455
1456 764
        $query .= ')';
1457
1458 764
        $sql = [$query];
1459
1460 764
        if (isset($options['foreignKeys'])) {
1461 309
            foreach ((array) $options['foreignKeys'] as $definition) {
1462 79
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
1463
            }
1464
        }
1465
1466 764
        return $sql;
1467
    }
1468
1469 36
    public function getCreateTemporaryTableSnippetSQL() : string
1470
    {
1471 36
        return 'CREATE TEMPORARY TABLE';
1472
    }
1473
1474
    /**
1475
     * Returns the SQL to create a sequence on this platform.
1476
     *
1477
     * @throws DBALException If not supported on this platform.
1478
     */
1479
    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

1479
    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...
1480
    {
1481
        throw NotSupported::new(__METHOD__);
1482
    }
1483
1484
    /**
1485
     * Returns the SQL to change a sequence on this platform.
1486
     *
1487
     * @throws DBALException If not supported on this platform.
1488
     */
1489
    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

1489
    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...
1490
    {
1491
        throw NotSupported::new(__METHOD__);
1492
    }
1493
1494
    /**
1495
     * Returns the SQL to create a constraint on a table on this platform.
1496
     *
1497
     * @param Table|string $table
1498
     *
1499
     * @throws InvalidArgumentException
1500
     */
1501 266
    public function getCreateConstraintSQL(Constraint $constraint, $table) : string
1502
    {
1503 266
        if ($table instanceof Table) {
1504
            $table = $table->getQuotedName($this);
1505
        }
1506
1507 266
        $query = 'ALTER TABLE ' . $table . ' ADD CONSTRAINT ' . $constraint->getQuotedName($this);
1508
1509 266
        $columnList = '(' . implode(', ', $constraint->getQuotedColumns($this)) . ')';
1510
1511 266
        $referencesClause = '';
1512 266
        if ($constraint instanceof Index) {
1513 266
            if ($constraint->isPrimary()) {
1514 266
                $query .= ' PRIMARY KEY';
1515 176
            } elseif ($constraint->isUnique()) {
1516 176
                $query .= ' UNIQUE';
1517
            } else {
1518
                throw new InvalidArgumentException(
1519 266
                    'Can only create primary or unique constraints, no common indexes with getCreateConstraintSQL().'
1520
                );
1521
            }
1522 176
        } elseif ($constraint instanceof ForeignKeyConstraint) {
1523 176
            $query .= ' FOREIGN KEY';
1524
1525 176
            $referencesClause = ' REFERENCES ' . $constraint->getQuotedForeignTableName($this) .
1526 176
                ' (' . implode(', ', $constraint->getQuotedForeignColumns($this)) . ')';
1527
        }
1528
1529 266
        $query .= ' ' . $columnList . $referencesClause;
1530
1531 266
        return $query;
1532
    }
1533
1534
    /**
1535
     * Returns the SQL to create an index on a table on this platform.
1536
     *
1537
     * @param Table|string $table The name of the table on which the index is to be created.
1538
     *
1539
     * @throws InvalidArgumentException
1540
     */
1541 2237
    public function getCreateIndexSQL(Index $index, $table) : string
1542
    {
1543 2237
        if ($table instanceof Table) {
1544 22
            $table = $table->getQuotedName($this);
1545
        }
1546
1547 2237
        $name    = $index->getQuotedName($this);
1548 2237
        $columns = $index->getColumns();
1549
1550 2237
        if (count($columns) === 0) {
1551
            throw new InvalidArgumentException('Incomplete definition. "columns" required.');
1552
        }
1553
1554 2237
        if ($index->isPrimary()) {
1555 396
            return $this->getCreatePrimaryKeySQL($index, $table);
1556
        }
1557
1558 1863
        $query  = 'CREATE ' . $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name . ' ON ' . $table;
1559 1863
        $query .= ' (' . $this->getIndexFieldDeclarationListSQL($index) . ')' . $this->getPartialIndexSQL($index);
1560
1561 1863
        return $query;
1562
    }
1563
1564
    /**
1565
     * Adds condition for partial index.
1566
     */
1567 2675
    protected function getPartialIndexSQL(Index $index) : string
1568
    {
1569 2675
        if ($this->supportsPartialIndexes() && $index->hasOption('where')) {
1570 49
            return ' WHERE ' . $index->getOption('where');
1571
        }
1572
1573 2626
        return '';
1574
    }
1575
1576
    /**
1577
     * Adds additional flags for index generation.
1578
     */
1579 1049
    protected function getCreateIndexSQLFlags(Index $index) : string
1580
    {
1581 1049
        return $index->isUnique() ? 'UNIQUE ' : '';
1582
    }
1583
1584
    /**
1585
     * Returns the SQL to create an unnamed primary key constraint.
1586
     *
1587
     * @param Table|string $table
1588
     */
1589 374
    public function getCreatePrimaryKeySQL(Index $index, $table) : string
1590
    {
1591 374
        if ($table instanceof Table) {
1592
            $table = $table->getQuotedName($this);
1593
        }
1594
1595 374
        return 'ALTER TABLE ' . $table . ' ADD PRIMARY KEY (' . $this->getIndexFieldDeclarationListSQL($index) . ')';
1596
    }
1597
1598
    /**
1599
     * Returns the SQL to create a named schema.
1600
     *
1601
     * @throws DBALException If not supported on this platform.
1602
     */
1603 154
    public function getCreateSchemaSQL(string $schemaName) : string
1604
    {
1605 154
        throw NotSupported::new(__METHOD__);
1606
    }
1607
1608
    /**
1609
     * Quotes a string so that it can be safely used as a table or column name,
1610
     * even if it is a reserved word of the platform. This also detects identifier
1611
     * chains separated by dot and quotes them independently.
1612
     *
1613
     * NOTE: Just because you CAN use quoted identifiers doesn't mean
1614
     * you SHOULD use them. In general, they end up causing way more
1615
     * problems than they solve.
1616
     *
1617
     * @param string $identifier The identifier name to be quoted.
1618
     *
1619
     * @return string The quoted identifier string.
1620
     */
1621 4775
    public function quoteIdentifier(string $identifier) : string
1622
    {
1623 4775
        if (strpos($identifier, '.') !== false) {
1624 238
            $parts = array_map([$this, 'quoteSingleIdentifier'], explode('.', $identifier));
1625
1626 238
            return implode('.', $parts);
1627
        }
1628
1629 4775
        return $this->quoteSingleIdentifier($identifier);
1630
    }
1631
1632
    /**
1633
     * Quotes a single identifier (no dot chain separation).
1634
     *
1635
     * @param string $str The identifier name to be quoted.
1636
     *
1637
     * @return string The quoted identifier string.
1638
     */
1639 8082
    public function quoteSingleIdentifier(string $str) : string
1640
    {
1641 8082
        $c = $this->getIdentifierQuoteCharacter();
1642
1643 8082
        return $c . str_replace($c, $c . $c, $str) . $c;
1644
    }
1645
1646
    /**
1647
     * Returns the SQL to create a new foreign key.
1648
     *
1649
     * @param ForeignKeyConstraint $foreignKey The foreign key constraint.
1650
     * @param Table|string         $table      The name of the table on which the foreign key is to be created.
1651
     */
1652 1103
    public function getCreateForeignKeySQL(ForeignKeyConstraint $foreignKey, $table) : string
1653
    {
1654 1103
        if ($table instanceof Table) {
1655 64
            $table = $table->getQuotedName($this);
1656
        }
1657
1658 1103
        return 'ALTER TABLE ' . $table . ' ADD ' . $this->getForeignKeyDeclarationSQL($foreignKey);
1659
    }
1660
1661
    /**
1662
     * Gets the SQL statements for altering an existing table.
1663
     *
1664
     * This method returns an array of SQL statements, since some platforms need several statements.
1665
     *
1666
     * @return array<int, string>
1667
     *
1668
     * @throws DBALException If not supported on this platform.
1669
     */
1670
    public function getAlterTableSQL(TableDiff $diff) : array
1671
    {
1672
        throw NotSupported::new(__METHOD__);
1673
    }
1674
1675
    /**
1676
     * @param mixed[] $columnSql
1677
     */
1678 1222
    protected function onSchemaAlterTableAddColumn(Column $column, TableDiff $diff, array &$columnSql) : bool
1679
    {
1680 1222
        if ($this->_eventManager === null) {
1681 968
            return false;
1682
        }
1683
1684 254
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableAddColumn)) {
1685 34
            return false;
1686
        }
1687
1688 220
        $eventArgs = new SchemaAlterTableAddColumnEventArgs($column, $diff, $this);
1689 220
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableAddColumn, $eventArgs);
1690
1691 220
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
1692
1693 220
        return $eventArgs->isDefaultPrevented();
1694
    }
1695
1696
    /**
1697
     * @param string[] $columnSql
1698
     */
1699 840
    protected function onSchemaAlterTableRemoveColumn(Column $column, TableDiff $diff, array &$columnSql) : bool
1700
    {
1701 840
        if ($this->_eventManager === null) {
1702 594
            return false;
1703
        }
1704
1705 246
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableRemoveColumn)) {
1706 26
            return false;
1707
        }
1708
1709 220
        $eventArgs = new SchemaAlterTableRemoveColumnEventArgs($column, $diff, $this);
1710 220
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableRemoveColumn, $eventArgs);
1711
1712 220
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
1713
1714 220
        return $eventArgs->isDefaultPrevented();
1715
    }
1716
1717
    /**
1718
     * @param string[] $columnSql
1719
     */
1720 2387
    protected function onSchemaAlterTableChangeColumn(ColumnDiff $columnDiff, TableDiff $diff, array &$columnSql) : bool
1721
    {
1722 2387
        if ($this->_eventManager === null) {
1723 1958
            return false;
1724
        }
1725
1726 429
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableChangeColumn)) {
1727 209
            return false;
1728
        }
1729
1730 220
        $eventArgs = new SchemaAlterTableChangeColumnEventArgs($columnDiff, $diff, $this);
1731 220
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableChangeColumn, $eventArgs);
1732
1733 220
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
1734
1735 220
        return $eventArgs->isDefaultPrevented();
1736
    }
1737
1738
    /**
1739
     * @param string[] $columnSql
1740
     */
1741 926
    protected function onSchemaAlterTableRenameColumn(string $oldColumnName, Column $column, TableDiff $diff, array &$columnSql) : bool
1742
    {
1743 926
        if ($this->_eventManager === null) {
1744 682
            return false;
1745
        }
1746
1747 244
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableRenameColumn)) {
1748 24
            return false;
1749
        }
1750
1751 220
        $eventArgs = new SchemaAlterTableRenameColumnEventArgs($oldColumnName, $column, $diff, $this);
1752 220
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableRenameColumn, $eventArgs);
1753
1754 220
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
1755
1756 220
        return $eventArgs->isDefaultPrevented();
1757
    }
1758
1759
    /**
1760
     * @param string[] $sql
1761
     */
1762 4888
    protected function onSchemaAlterTable(TableDiff $diff, array &$sql) : bool
1763
    {
1764 4888
        if ($this->_eventManager === null) {
1765 4334
            return false;
1766
        }
1767
1768 554
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTable)) {
1769 334
            return false;
1770
        }
1771
1772 220
        $eventArgs = new SchemaAlterTableEventArgs($diff, $this);
1773 220
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTable, $eventArgs);
1774
1775 220
        $sql = array_merge($sql, $eventArgs->getSql());
1776
1777 220
        return $eventArgs->isDefaultPrevented();
1778
    }
1779
1780
    /**
1781
     * @return string[]
1782
     */
1783 4584
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) : array
1784
    {
1785 4584
        $tableName = $diff->getName($this)->getQuotedName($this);
1786
1787 4584
        $sql = [];
1788 4584
        if ($this->supportsForeignKeyConstraints()) {
1789 4584
            foreach ($diff->removedForeignKeys as $foreignKey) {
1790 329
                $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
1791
            }
1792
1793 4584
            foreach ($diff->changedForeignKeys as $foreignKey) {
1794 264
                $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
1795
            }
1796
        }
1797
1798 4584
        foreach ($diff->removedIndexes as $index) {
1799 221
            $sql[] = $this->getDropIndexSQL($index, $tableName);
1800
        }
1801
1802 4584
        foreach ($diff->changedIndexes as $index) {
1803 394
            $sql[] = $this->getDropIndexSQL($index, $tableName);
1804
        }
1805
1806 4584
        return $sql;
1807
    }
1808
1809
    /**
1810
     * @return string[]
1811
     */
1812 4584
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff) : array
1813
    {
1814 4584
        $sql     = [];
1815 4584
        $newName = $diff->getNewName();
1816
1817 4584
        if ($newName !== null) {
1818 399
            $tableName = $newName->getQuotedName($this);
1819
        } else {
1820 4187
            $tableName = $diff->getName($this)->getQuotedName($this);
1821
        }
1822
1823 4584
        if ($this->supportsForeignKeyConstraints()) {
1824 4584
            foreach ($diff->addedForeignKeys as $foreignKey) {
1825 306
                $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
1826
            }
1827
1828 4584
            foreach ($diff->changedForeignKeys as $foreignKey) {
1829 264
                $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
1830
            }
1831
        }
1832
1833 4584
        foreach ($diff->addedIndexes as $index) {
1834 87
            $sql[] = $this->getCreateIndexSQL($index, $tableName);
1835
        }
1836
1837 4584
        foreach ($diff->changedIndexes as $index) {
1838 394
            $sql[] = $this->getCreateIndexSQL($index, $tableName);
1839
        }
1840
1841 4584
        foreach ($diff->renamedIndexes as $oldIndexName => $index) {
1842 1032
            $oldIndexName = new Identifier($oldIndexName);
1843 1032
            $sql          = array_merge(
1844 1032
                $sql,
1845 1032
                $this->getRenameIndexSQL($oldIndexName->getQuotedName($this), $index, $tableName)
1846
            );
1847
        }
1848
1849 4584
        return $sql;
1850
    }
1851
1852
    /**
1853
     * Returns the SQL for renaming an index on a table.
1854
     *
1855
     * @param string $oldIndexName The name of the index to rename from.
1856
     * @param Index  $index        The definition of the index to rename to.
1857
     * @param string $tableName    The table to rename the given index on.
1858
     *
1859
     * @return string[] The sequence of SQL statements for renaming the given index.
1860
     */
1861 236
    protected function getRenameIndexSQL(string $oldIndexName, Index $index, string $tableName) : array
1862
    {
1863
        return [
1864 236
            $this->getDropIndexSQL($oldIndexName, $tableName),
1865 236
            $this->getCreateIndexSQL($index, $tableName),
1866
        ];
1867
    }
1868
1869
    /**
1870
     * Gets declaration of a number of fields in bulk.
1871
     *
1872
     * @param mixed[][] $fields A multidimensional array.
1873
     *                          The first dimension determines the ordinal position of the field,
1874
     *                          while the second dimension is keyed with the name of the properties
1875
     *                          of the field being declared as array indexes. Currently, the types
1876
     *                          of supported field properties are as follows:
1877
     *
1878
     *      length
1879
     *          Integer value that determines the maximum length of the text
1880
     *          field. If this argument is missing the field should be
1881
     *          declared to have the longest length allowed by the DBMS.
1882
     *
1883
     *      default
1884
     *          Text value to be used as default for this field.
1885
     *
1886
     *      notnull
1887
     *          Boolean flag that indicates whether this field is constrained
1888
     *          to not be set to null.
1889
     *      charset
1890
     *          Text value with the default CHARACTER SET for this field.
1891
     *      collation
1892
     *          Text value with the default COLLATION for this field.
1893
     *      unique
1894
     *          unique constraint
1895
     */
1896 6774
    public function getColumnDeclarationListSQL(array $fields) : string
1897
    {
1898 6774
        $queryFields = [];
1899
1900 6774
        foreach ($fields as $field) {
1901 6774
            $queryFields[] = $this->getColumnDeclarationSQL($field['name'], $field);
1902
        }
1903
1904 6774
        return implode(', ', $queryFields);
1905
    }
1906
1907
    /**
1908
     * Obtains DBMS specific SQL code portion needed to declare a generic type
1909
     * field to be used in statements like CREATE TABLE.
1910
     *
1911
     * @param string  $name  The name the field to be declared.
1912
     * @param mixed[] $field An associative array with the name of the properties
1913
     *                       of the field being declared as array indexes. Currently, the types
1914
     *                       of supported field properties are as follows:
1915
     *
1916
     *      length
1917
     *          Integer value that determines the maximum length of the text
1918
     *          field. If this argument is missing the field should be
1919
     *          declared to have the longest length allowed by the DBMS.
1920
     *
1921
     *      default
1922
     *          Text value to be used as default for this field.
1923
     *
1924
     *      notnull
1925
     *          Boolean flag that indicates whether this field is constrained
1926
     *          to not be set to null.
1927
     *      charset
1928
     *          Text value with the default CHARACTER SET for this field.
1929
     *      collation
1930
     *          Text value with the default COLLATION for this field.
1931
     *      unique
1932
     *          unique constraint
1933
     *      check
1934
     *          column check constraint
1935
     *      columnDefinition
1936
     *          a string that defines the complete column
1937
     *
1938
     * @return string DBMS specific SQL code portion that should be used to declare the column.
1939
     */
1940 7359
    public function getColumnDeclarationSQL(string $name, array $field) : string
1941
    {
1942 7359
        if (isset($field['columnDefinition'])) {
1943 176
            $columnDef = $this->getCustomTypeDeclarationSQL($field);
1944
        } else {
1945 7183
            $default = $this->getDefaultValueDeclarationSQL($field);
1946
1947 7183
            $charset = ! empty($field['charset']) ?
1948 7183
                ' ' . $this->getColumnCharsetDeclarationSQL($field['charset']) : '';
1949
1950 7183
            $collation = ! empty($field['collation']) ?
1951 7183
                ' ' . $this->getColumnCollationDeclarationSQL($field['collation']) : '';
1952
1953 7183
            $notnull = ! empty($field['notnull']) ? ' NOT NULL' : '';
1954
1955 7183
            $unique = ! empty($field['unique']) ?
1956 7183
                ' ' . $this->getUniqueFieldDeclarationSQL() : '';
1957
1958 7183
            $check = ! empty($field['check']) ? ' ' . $field['check'] : '';
1959
1960 7183
            $typeDecl  = $field['type']->getSQLDeclaration($field, $this);
1961 7183
            $columnDef = $typeDecl . $charset . $default . $notnull . $unique . $check . $collation;
1962
1963 7183
            if ($this->supportsInlineColumnComments() && isset($field['comment']) && $field['comment'] !== '') {
1964 756
                $columnDef .= ' ' . $this->getInlineColumnCommentSQL($field['comment']);
1965
            }
1966
        }
1967
1968 7359
        return $name . ' ' . $columnDef;
1969
    }
1970
1971
    /**
1972
     * Returns the SQL snippet that declares a floating point column of arbitrary precision.
1973
     *
1974
     * @param mixed[] $columnDef
1975
     */
1976 1835
    public function getDecimalTypeDeclarationSQL(array $columnDef) : string
1977
    {
1978 1835
        $columnDef['precision'] = ! isset($columnDef['precision']) || empty($columnDef['precision'])
1979 1835
            ? 10 : $columnDef['precision'];
1980 1835
        $columnDef['scale']     = ! isset($columnDef['scale']) || empty($columnDef['scale'])
1981 1835
            ? 0 : $columnDef['scale'];
1982
1983 1835
        return 'NUMERIC(' . $columnDef['precision'] . ', ' . $columnDef['scale'] . ')';
1984
    }
1985
1986
    /**
1987
     * Obtains DBMS specific SQL code portion needed to set a default value
1988
     * declaration to be used in statements like CREATE TABLE.
1989
     *
1990
     * @param mixed[] $field The field definition array.
1991
     *
1992
     * @return string DBMS specific SQL code portion needed to set a default value.
1993
     */
1994 8707
    public function getDefaultValueDeclarationSQL(array $field) : string
1995
    {
1996 8707
        if (! isset($field['default'])) {
1997 7276
            return empty($field['notnull']) ? ' DEFAULT NULL' : '';
1998
        }
1999
2000 1868
        $default = $field['default'];
2001
2002 1868
        if (! isset($field['type'])) {
2003 88
            return " DEFAULT '" . $default . "'";
2004
        }
2005
2006 1780
        $type = $field['type'];
2007
2008 1780
        if ($type instanceof Types\PhpIntegerMappingType) {
2009 501
            return ' DEFAULT ' . $default;
2010
        }
2011
2012 1364
        if ($type instanceof Types\PhpDateTimeMappingType && $default === $this->getCurrentTimestampSQL()) {
2013 270
            return ' DEFAULT ' . $this->getCurrentTimestampSQL();
2014
        }
2015
2016 1110
        if ($type instanceof Types\TimeType && $default === $this->getCurrentTimeSQL()) {
2017 13
            return ' DEFAULT ' . $this->getCurrentTimeSQL();
2018
        }
2019
2020 1101
        if ($type instanceof Types\DateType && $default === $this->getCurrentDateSQL()) {
2021 234
            return ' DEFAULT ' . $this->getCurrentDateSQL();
2022
        }
2023
2024 867
        if ($type instanceof Types\BooleanType) {
2025 249
            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

2025
            return " DEFAULT '" . /** @scrutinizer ignore-type */ $this->convertBooleans($default) . "'";
Loading history...
2026
        }
2027
2028 840
        if (is_int($default) || is_float($default)) {
2029 19
            return ' DEFAULT ' . $default;
2030
        }
2031
2032 838
        return ' DEFAULT ' . $this->quoteStringLiteral($default);
2033
    }
2034
2035
    /**
2036
     * Obtains DBMS specific SQL code portion needed to set a CHECK constraint
2037
     * declaration to be used in statements like CREATE TABLE.
2038
     *
2039
     * @param string[]|mixed[][] $definition The check definition.
2040
     *
2041
     * @return string DBMS specific SQL code portion needed to set a CHECK constraint.
2042
     */
2043 1660
    public function getCheckDeclarationSQL(array $definition) : string
2044
    {
2045 1660
        $constraints = [];
2046 1660
        foreach ($definition as $def) {
2047 1660
            if (is_string($def)) {
2048
                $constraints[] = 'CHECK (' . $def . ')';
2049
            } else {
2050 1660
                if (isset($def['min'])) {
2051 44
                    $constraints[] = 'CHECK (' . $def['name'] . ' >= ' . $def['min'] . ')';
2052
                }
2053
2054 1660
                if (! isset($def['max'])) {
2055 1660
                    continue;
2056
                }
2057
2058 44
                $constraints[] = 'CHECK (' . $def['name'] . ' <= ' . $def['max'] . ')';
2059
            }
2060
        }
2061
2062 1660
        return implode(', ', $constraints);
2063
    }
2064
2065
    /**
2066
     * Obtains DBMS specific SQL code portion needed to set a unique
2067
     * constraint declaration to be used in statements like CREATE TABLE.
2068
     *
2069
     * @param string           $name       The name of the unique constraint.
2070
     * @param UniqueConstraint $constraint The unique constraint definition.
2071
     *
2072
     * @return string DBMS specific SQL code portion needed to set a constraint.
2073
     *
2074
     * @throws InvalidArgumentException
2075
     */
2076 484
    public function getUniqueConstraintDeclarationSQL(string $name, UniqueConstraint $constraint) : string
2077
    {
2078 484
        $columns = $constraint->getColumns();
2079
2080 484
        if (count($columns) === 0) {
2081 22
            throw new InvalidArgumentException('Incomplete definition. "columns" required.');
2082
        }
2083
2084 462
        $chunks = ['CONSTRAINT'];
2085
2086 462
        if ($name !== '') {
2087 462
            $chunks[] = (new Identifier($name))->getQuotedName($this);
2088
        }
2089
2090 462
        $chunks[] = 'UNIQUE';
2091
2092 462
        if ($constraint->hasFlag('clustered')) {
2093 22
            $chunks[] = 'CLUSTERED';
2094
        }
2095
2096 462
        $chunks[] = sprintf('(%s)', $this->getColumnsFieldDeclarationListSQL($columns));
2097
2098 462
        return implode(' ', $chunks);
2099
    }
2100
2101
    /**
2102
     * Obtains DBMS specific SQL code portion needed to set an index
2103
     * declaration to be used in statements like CREATE TABLE.
2104
     *
2105
     * @param string $name  The name of the index.
2106
     * @param Index  $index The index definition.
2107
     *
2108
     * @return string DBMS specific SQL code portion needed to set an index.
2109
     *
2110
     * @throws InvalidArgumentException
2111
     */
2112 1020
    public function getIndexDeclarationSQL(string $name, Index $index) : string
2113
    {
2114 1020
        $columns = $index->getColumns();
2115 1020
        $name    = new Identifier($name);
2116
2117 1020
        if (count($columns) === 0) {
2118
            throw new InvalidArgumentException('Incomplete definition. "columns" required.');
2119
        }
2120
2121 1020
        return $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name->getQuotedName($this) . ' ('
2122 1020
            . $this->getIndexFieldDeclarationListSQL($index)
2123 1020
            . ')' . $this->getPartialIndexSQL($index);
2124
    }
2125
2126
    /**
2127
     * Obtains SQL code portion needed to create a custom column,
2128
     * e.g. when a field has the "columnDefinition" keyword.
2129
     * Only "AUTOINCREMENT" and "PRIMARY KEY" are added if appropriate.
2130
     *
2131
     * @param mixed[] $columnDef
2132
     */
2133 220
    public function getCustomTypeDeclarationSQL(array $columnDef) : string
2134
    {
2135 220
        return $columnDef['columnDefinition'];
2136
    }
2137
2138
    /**
2139
     * Obtains DBMS specific SQL code portion needed to set an index
2140
     * declaration to be used in statements like CREATE TABLE.
2141
     */
2142 3159
    public function getIndexFieldDeclarationListSQL(Index $index) : string
2143
    {
2144 3159
        return implode(', ', $index->getQuotedColumns($this));
2145
    }
2146
2147
    /**
2148
     * Obtains DBMS specific SQL code portion needed to set an index
2149
     * declaration to be used in statements like CREATE TABLE.
2150
     *
2151
     * @param mixed[] $columns
2152
     */
2153 660
    public function getColumnsFieldDeclarationListSQL(array $columns) : string
2154
    {
2155 660
        $ret = [];
2156
2157 660
        foreach ($columns as $column => $definition) {
2158 660
            if (is_array($definition)) {
2159
                $ret[] = $column;
2160
            } else {
2161 660
                $ret[] = $definition;
2162
            }
2163
        }
2164
2165 660
        return implode(', ', $ret);
2166
    }
2167
2168
    /**
2169
     * Returns the required SQL string that fits between CREATE ... TABLE
2170
     * to create the table as a temporary table.
2171
     *
2172
     * Should be overridden in driver classes to return the correct string for the
2173
     * specific database type.
2174
     *
2175
     * The default is to return the string "TEMPORARY" - this will result in a
2176
     * SQL error for any database that does not support temporary tables, or that
2177
     * requires a different SQL command from "CREATE TEMPORARY TABLE".
2178
     *
2179
     * @return string The string required to be placed between "CREATE" and "TABLE"
2180
     *                to generate a temporary table, if possible.
2181
     */
2182
    public function getTemporaryTableSQL() : string
2183
    {
2184
        return 'TEMPORARY';
2185
    }
2186
2187
    /**
2188
     * Some vendors require temporary table names to be qualified specially.
2189
     */
2190 34
    public function getTemporaryTableName(string $tableName) : string
2191
    {
2192 34
        return $tableName;
2193
    }
2194
2195
    /**
2196
     * Obtain DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
2197
     * of a field declaration to be used in statements like CREATE TABLE.
2198
     *
2199
     * @return string DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
2200
     *                of a field declaration.
2201
     */
2202 1402
    public function getForeignKeyDeclarationSQL(ForeignKeyConstraint $foreignKey) : string
2203
    {
2204 1402
        $sql  = $this->getForeignKeyBaseDeclarationSQL($foreignKey);
2205 1336
        $sql .= $this->getAdvancedForeignKeyOptionsSQL($foreignKey);
2206
2207 1336
        return $sql;
2208
    }
2209
2210
    /**
2211
     * Returns the FOREIGN KEY query section dealing with non-standard options
2212
     * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
2213
     *
2214
     * @param ForeignKeyConstraint $foreignKey The foreign key definition.
2215
     */
2216 1256
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey) : string
2217
    {
2218 1256
        $query = '';
2219 1256
        if ($this->supportsForeignKeyOnUpdate() && $foreignKey->hasOption('onUpdate')) {
2220 22
            $query .= ' ON UPDATE ' . $this->getForeignKeyReferentialActionSQL($foreignKey->getOption('onUpdate'));
2221
        }
2222
2223 1256
        if ($foreignKey->hasOption('onDelete')) {
2224 87
            $query .= ' ON DELETE ' . $this->getForeignKeyReferentialActionSQL($foreignKey->getOption('onDelete'));
2225
        }
2226
2227 1256
        return $query;
2228
    }
2229
2230
    /**
2231
     * Returns the given referential action in uppercase if valid, otherwise throws an exception.
2232
     *
2233
     * @param string $action The foreign key referential action.
2234
     *
2235
     * @throws InvalidArgumentException If unknown referential action given.
2236
     */
2237 1429
    public function getForeignKeyReferentialActionSQL(string $action) : string
2238
    {
2239 1429
        $upper = strtoupper($action);
2240 64
        switch ($upper) {
2241 1429
            case 'CASCADE':
2242 973
            case 'SET NULL':
2243 753
            case 'NO ACTION':
2244 577
            case 'RESTRICT':
2245 401
            case 'SET DEFAULT':
2246 1231
                return $upper;
2247
2248
            default:
2249 198
                throw new InvalidArgumentException(sprintf('Invalid foreign key action "%s".', $upper));
2250
        }
2251
    }
2252
2253
    /**
2254
     * Obtains DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
2255
     * of a field declaration to be used in statements like CREATE TABLE.
2256
     *
2257
     * @throws InvalidArgumentException
2258
     */
2259 1204
    public function getForeignKeyBaseDeclarationSQL(ForeignKeyConstraint $foreignKey) : string
2260
    {
2261 1204
        $sql = '';
2262 1204
        if ($foreignKey->getName() !== '') {
2263 1006
            $sql .= 'CONSTRAINT ' . $foreignKey->getQuotedName($this) . ' ';
2264
        }
2265
2266 1204
        $sql .= 'FOREIGN KEY (';
2267
2268 1204
        if (count($foreignKey->getLocalColumns()) === 0) {
2269
            throw new InvalidArgumentException('Incomplete definition. "local" required.');
2270
        }
2271
2272 1204
        if (count($foreignKey->getForeignColumns()) === 0) {
2273
            throw new InvalidArgumentException('Incomplete definition. "foreign" required.');
2274
        }
2275
2276 1204
        if (strlen($foreignKey->getForeignTableName()) === 0) {
2277
            throw new InvalidArgumentException('Incomplete definition. "foreignTable" required.');
2278
        }
2279
2280 1204
        return $sql . implode(', ', $foreignKey->getQuotedLocalColumns($this))
2281 1204
            . ') REFERENCES '
2282 1204
            . $foreignKey->getQuotedForeignTableName($this) . ' ('
2283 1204
            . implode(', ', $foreignKey->getQuotedForeignColumns($this)) . ')';
2284
    }
2285
2286
    /**
2287
     * Obtains DBMS specific SQL code portion needed to set the UNIQUE constraint
2288
     * of a field declaration to be used in statements like CREATE TABLE.
2289
     *
2290
     * @return string DBMS specific SQL code portion needed to set the UNIQUE constraint
2291
     *                of a field declaration.
2292
     */
2293
    public function getUniqueFieldDeclarationSQL() : string
2294
    {
2295
        return 'UNIQUE';
2296
    }
2297
2298
    /**
2299
     * Obtains DBMS specific SQL code portion needed to set the CHARACTER SET
2300
     * of a field declaration to be used in statements like CREATE TABLE.
2301
     *
2302
     * @param string $charset The name of the charset.
2303
     *
2304
     * @return string DBMS specific SQL code portion needed to set the CHARACTER SET
2305
     *                of a field declaration.
2306
     */
2307
    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

2307
    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...
2308
    {
2309
        return '';
2310
    }
2311
2312
    /**
2313
     * Obtains DBMS specific SQL code portion needed to set the COLLATION
2314
     * of a field declaration to be used in statements like CREATE TABLE.
2315
     *
2316
     * @param string $collation The name of the collation.
2317
     *
2318
     * @return string DBMS specific SQL code portion needed to set the COLLATION
2319
     *                of a field declaration.
2320
     */
2321 93
    public function getColumnCollationDeclarationSQL(string $collation) : string
2322
    {
2323 93
        return $this->supportsColumnCollation() ? 'COLLATE ' . $collation : '';
2324
    }
2325
2326
    /**
2327
     * Whether the platform prefers sequences for ID generation.
2328
     * Subclasses should override this method to return TRUE if they prefer sequences.
2329
     */
2330 44
    public function prefersSequences() : bool
2331
    {
2332 44
        return false;
2333
    }
2334
2335
    /**
2336
     * Whether the platform prefers identity columns (eg. autoincrement) for ID generation.
2337
     * Subclasses should override this method to return TRUE if they prefer identity columns.
2338
     */
2339 66
    public function prefersIdentityColumns() : bool
2340
    {
2341 66
        return false;
2342
    }
2343
2344
    /**
2345
     * Some platforms need the boolean values to be converted.
2346
     *
2347
     * The default conversion in this implementation converts to integers (false => 0, true => 1).
2348
     *
2349
     * Note: if the input is not a boolean the original input might be returned.
2350
     *
2351
     * There are two contexts when converting booleans: Literals and Prepared Statements.
2352
     * This method should handle the literal case
2353
     *
2354
     * @param mixed $item A boolean or an array of them.
2355
     *
2356
     * @return mixed A boolean database value or an array of them.
2357
     */
2358 287
    public function convertBooleans($item)
2359
    {
2360 287
        if (is_array($item)) {
2361
            foreach ($item as $k => $value) {
2362
                if (! is_bool($value)) {
2363
                    continue;
2364
                }
2365
2366
                $item[$k] = (int) $value;
2367
            }
2368 287
        } elseif (is_bool($item)) {
2369 287
            $item = (int) $item;
2370
        }
2371
2372 287
        return $item;
2373
    }
2374
2375
    /**
2376
     * Some platforms have boolean literals that needs to be correctly converted
2377
     *
2378
     * The default conversion tries to convert value into bool "(bool)$item"
2379
     *
2380
     * @param mixed $item
2381
     */
2382 308
    public function convertFromBoolean($item) : ?bool
2383
    {
2384 308
        if ($item === null) {
2385
            return null;
2386
        }
2387
2388 308
        return (bool) $item;
2389
    }
2390
2391
    /**
2392
     * This method should handle the prepared statements case. When there is no
2393
     * distinction, it's OK to use the same method.
2394
     *
2395
     * Note: if the input is not a boolean the original input might be returned.
2396
     *
2397
     * @param mixed $item A boolean or an array of them.
2398
     *
2399
     * @return mixed A boolean database value or an array of them.
2400
     */
2401 78
    public function convertBooleansToDatabaseValue($item)
2402
    {
2403 78
        return $this->convertBooleans($item);
2404
    }
2405
2406
    /**
2407
     * Returns the SQL specific for the platform to get the current date.
2408
     */
2409 207
    public function getCurrentDateSQL() : string
2410
    {
2411 207
        return 'CURRENT_DATE';
2412
    }
2413
2414
    /**
2415
     * Returns the SQL specific for the platform to get the current time.
2416
     */
2417 18
    public function getCurrentTimeSQL() : string
2418
    {
2419 18
        return 'CURRENT_TIME';
2420
    }
2421
2422
    /**
2423
     * Returns the SQL specific for the platform to get the current timestamp
2424
     */
2425 263
    public function getCurrentTimestampSQL() : string
2426
    {
2427 263
        return 'CURRENT_TIMESTAMP';
2428
    }
2429
2430
    /**
2431
     * Returns the SQL for a given transaction isolation level Connection constant.
2432
     *
2433
     * @throws InvalidArgumentException
2434
     */
2435 132
    protected function _getTransactionIsolationLevelSQL(int $level) : string
2436
    {
2437
        switch ($level) {
2438 132
            case TransactionIsolationLevel::READ_UNCOMMITTED:
2439 132
                return 'READ UNCOMMITTED';
2440
2441 132
            case TransactionIsolationLevel::READ_COMMITTED:
2442 132
                return 'READ COMMITTED';
2443
2444 132
            case TransactionIsolationLevel::REPEATABLE_READ:
2445 132
                return 'REPEATABLE READ';
2446
2447 132
            case TransactionIsolationLevel::SERIALIZABLE:
2448 132
                return 'SERIALIZABLE';
2449
2450
            default:
2451
                throw new InvalidArgumentException(sprintf('Invalid isolation level "%s".', $level));
2452
        }
2453
    }
2454
2455
    /**
2456
     * @throws DBALException If not supported on this platform.
2457
     */
2458 1
    public function getListDatabasesSQL() : string
2459
    {
2460 1
        throw NotSupported::new(__METHOD__);
2461
    }
2462
2463
    /**
2464
     * Returns the SQL statement for retrieving the namespaces defined in the database.
2465
     *
2466
     * @throws DBALException If not supported on this platform.
2467
     */
2468
    public function getListNamespacesSQL() : string
2469
    {
2470
        throw NotSupported::new(__METHOD__);
2471
    }
2472
2473
    /**
2474
     * @throws DBALException If not supported on this platform.
2475
     */
2476
    public function getListSequencesSQL(string $database) : string
2477
    {
2478
        throw NotSupported::new(__METHOD__);
2479
    }
2480
2481
    /**
2482
     * @throws DBALException If not supported on this platform.
2483
     */
2484
    public function getListTableConstraintsSQL(string $table) : string
2485
    {
2486
        throw NotSupported::new(__METHOD__);
2487
    }
2488
2489
    /**
2490
     * @throws DBALException If not supported on this platform.
2491
     */
2492
    public function getListTableColumnsSQL(string $table, ?string $database = null) : string
2493
    {
2494
        throw NotSupported::new(__METHOD__);
2495
    }
2496
2497
    /**
2498
     * @throws DBALException If not supported on this platform.
2499
     */
2500
    public function getListTablesSQL() : string
2501
    {
2502
        throw NotSupported::new(__METHOD__);
2503
    }
2504
2505
    /**
2506
     * @throws DBALException If not supported on this platform.
2507
     */
2508
    public function getListUsersSQL() : string
2509
    {
2510
        throw NotSupported::new(__METHOD__);
2511
    }
2512
2513
    /**
2514
     * Returns the SQL to list all views of a database or user.
2515
     *
2516
     * @throws DBALException If not supported on this platform.
2517
     */
2518
    public function getListViewsSQL(string $database) : string
2519
    {
2520
        throw NotSupported::new(__METHOD__);
2521
    }
2522
2523
    /**
2524
     * Returns the list of indexes for the current database.
2525
     *
2526
     * The current database parameter is optional but will always be passed
2527
     * when using the SchemaManager API and is the database the given table is in.
2528
     *
2529
     * Attention: Some platforms only support currentDatabase when they
2530
     * are connected with that database. Cross-database information schema
2531
     * requests may be impossible.
2532
     *
2533
     * @throws DBALException If not supported on this platform.
2534
     */
2535
    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

2535
    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...
2536
    {
2537
        throw NotSupported::new(__METHOD__);
2538
    }
2539
2540
    /**
2541
     * @throws DBALException If not supported on this platform.
2542
     */
2543
    public function getListTableForeignKeysSQL(string $table, ?string $database = null) : string
2544
    {
2545
        throw NotSupported::new(__METHOD__);
2546
    }
2547
2548
    /**
2549
     * @throws DBALException If not supported on this platform.
2550
     */
2551
    public function getCreateViewSQL(string $name, string $sql) : string
2552
    {
2553
        throw NotSupported::new(__METHOD__);
2554
    }
2555
2556
    /**
2557
     * @throws DBALException If not supported on this platform.
2558
     */
2559
    public function getDropViewSQL(string $name) : string
2560
    {
2561
        throw NotSupported::new(__METHOD__);
2562
    }
2563
2564
    /**
2565
     * Returns the SQL snippet to drop an existing sequence.
2566
     *
2567
     * @param Sequence|string $sequence
2568
     *
2569
     * @throws DBALException If not supported on this platform.
2570
     */
2571
    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

2571
    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...
2572
    {
2573
        throw NotSupported::new(__METHOD__);
2574
    }
2575
2576
    /**
2577
     * @throws DBALException If not supported on this platform.
2578
     */
2579
    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

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

3059
    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...
3060
    {
3061 174
        $tableIdentifier = new Identifier($tableName);
3062
3063 174
        return 'TRUNCATE ' . $tableIdentifier->getQuotedName($this);
3064
    }
3065
3066
    /**
3067
     * This is for test reasons, many vendors have special requirements for dummy statements.
3068
     */
3069 2021
    public function getDummySelectSQL(string $expression = '1') : string
3070
    {
3071 2021
        return sprintf('SELECT %s', $expression);
3072
    }
3073
3074
    /**
3075
     * Returns the SQL to create a new savepoint.
3076
     */
3077 19
    public function createSavePoint(string $savepoint) : string
3078
    {
3079 19
        return 'SAVEPOINT ' . $savepoint;
3080
    }
3081
3082
    /**
3083
     * Returns the SQL to release a savepoint.
3084
     */
3085 18
    public function releaseSavePoint(string $savepoint) : string
3086
    {
3087 18
        return 'RELEASE SAVEPOINT ' . $savepoint;
3088
    }
3089
3090
    /**
3091
     * Returns the SQL to rollback a savepoint.
3092
     */
3093 19
    public function rollbackSavePoint(string $savepoint) : string
3094
    {
3095 19
        return 'ROLLBACK TO SAVEPOINT ' . $savepoint;
3096
    }
3097
3098
    /**
3099
     * Returns the keyword list instance of this platform.
3100
     *
3101
     * @throws DBALException If no keyword list is specified.
3102
     */
3103 15665
    final public function getReservedKeywordsList() : KeywordList
3104
    {
3105
        // Check for an existing instantiation of the keywords class.
3106 15665
        if ($this->_keywords !== null) {
3107 14609
            return $this->_keywords;
3108
        }
3109
3110 11699
        $class    = $this->getReservedKeywordsClass();
3111 11699
        $keywords = new $class();
3112 11699
        if (! $keywords instanceof KeywordList) {
3113
            throw NotSupported::new(__METHOD__);
3114
        }
3115
3116
        // Store the instance so it doesn't need to be generated on every request.
3117 11699
        $this->_keywords = $keywords;
3118
3119 11699
        return $keywords;
3120
    }
3121
3122
    /**
3123
     * Returns the class name of the reserved keywords list.
3124
     *
3125
     * @throws DBALException If not supported on this platform.
3126
     */
3127
    protected function getReservedKeywordsClass() : string
3128
    {
3129
        throw NotSupported::new(__METHOD__);
3130
    }
3131
3132
    /**
3133
     * Quotes a literal string.
3134
     * This method is NOT meant to fix SQL injections!
3135
     * It is only meant to escape this platform's string literal
3136
     * quote character inside the given literal string.
3137
     *
3138
     * @param string $str The literal string to be quoted.
3139
     *
3140
     * @return string The quoted literal string.
3141
     */
3142 6743
    public function quoteStringLiteral(string $str) : string
3143
    {
3144 6743
        $c = $this->getStringLiteralQuoteCharacter();
3145
3146 6743
        return $c . str_replace($c, $c . $c, $str) . $c;
3147
    }
3148
3149
    /**
3150
     * Gets the character used for string literal quoting.
3151
     */
3152 6963
    public function getStringLiteralQuoteCharacter() : string
3153
    {
3154 6963
        return "'";
3155
    }
3156
3157
    /**
3158
     * Escapes metacharacters in a string intended to be used with a LIKE
3159
     * operator.
3160
     *
3161
     * @param string $inputString a literal, unquoted string
3162
     * @param string $escapeChar  should be reused by the caller in the LIKE
3163
     *                            expression.
3164
     */
3165 242
    final public function escapeStringForLike(string $inputString, string $escapeChar) : string
3166
    {
3167 242
        $sql = preg_replace(
3168 242
            '~([' . preg_quote($this->getLikeWildcardCharacters() . $escapeChar, '~') . '])~u',
3169 242
            addcslashes($escapeChar, '\\') . '$1',
3170 242
            $inputString
3171
        );
3172
3173 242
        assert(is_string($sql));
3174
3175 242
        return $sql;
3176
    }
3177
3178 242
    protected function getLikeWildcardCharacters() : string
3179
    {
3180 242
        return '%_';
3181
    }
3182
}
3183