Completed
Push — master ( e26ed0...acc468 )
by Sergei
113:25 queued 48:22
created

getColumnsFieldDeclarationListSQL()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 13
rs 10
ccs 5
cts 6
cp 0.8333
cc 3
nc 3
nop 1
crap 3.0416
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 51989
    public function __construct()
97
    {
98 51989
    }
99
100
    /**
101
     * Sets the EventManager used by the Platform.
102
     */
103 1570
    public function setEventManager(EventManager $eventManager) : void
104
    {
105 1570
        $this->_eventManager = $eventManager;
106 1570
    }
107
108
    /**
109
     * Gets the EventManager used by the Platform.
110
     */
111 1993
    public function getEventManager() : ?EventManager
112
    {
113 1993
        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 1556
    private function initializeAllDoctrineTypeMappings() : void
161
    {
162 1556
        $this->initializeDoctrineTypeMappings();
163
164 1556
        foreach (Type::getTypesMap() as $typeName => $className) {
165 1556
            foreach (Type::getType($typeName)->getMappedDatabaseTypes($this) as $dbType) {
166 969
                $this->doctrineTypeMapping[$dbType] = $typeName;
167
            }
168
        }
169 1556
    }
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 7112
    public function getStringTypeDeclarationSQL(array $column) : string
179
    {
180 7112
        $length = $column['length'] ?? null;
181
182 7112
        if (empty($column['fixed'])) {
183 6042
            return $this->getVarcharTypeDeclarationSQLSnippet($length);
184
        }
185
186 1232
        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 1214
    public function getBinaryTypeDeclarationSQL(array $column) : string
197
    {
198 1214
        $length = $column['length'] ?? null;
199
200 1214
        if (empty($column['fixed'])) {
201 620
            return $this->getVarbinaryTypeDeclarationSQLSnippet($length);
202
        }
203
204 647
        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 179
    public function getGuidTypeDeclarationSQL(array $column) : string
218
    {
219 179
        $column['length'] = 36;
220 179
        $column['fixed']  = true;
221
222 179
        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 268
    public function getJsonTypeDeclarationSQL(array $field) : string
234
    {
235 268
        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 1164
    protected function getCharTypeDeclarationSQLSnippet(?int $length) : string
245
    {
246 1164
        $sql = 'CHAR';
247
248 1164
        if ($length !== null) {
249 894
            $sql .= sprintf('(%d)', $length);
250
        }
251
252 1164
        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 3255
    protected function getVarcharTypeDeclarationSQLSnippet(?int $length) : string
262
    {
263 3255
        if ($length === null) {
264 162
            throw ColumnLengthRequired::new($this, 'VARCHAR');
265
        }
266
267 3093
        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 362
    protected function getBinaryTypeDeclarationSQLSnippet(?int $length) : string
279
    {
280 362
        $sql = 'BINARY';
281
282 362
        if ($length !== null) {
283 181
            $sql .= sprintf('(%d)', $length);
284
        }
285
286 362
        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 335
    protected function getVarbinaryTypeDeclarationSQLSnippet(?int $length) : string
298
    {
299 335
        if ($length === null) {
300 135
            throw ColumnLengthRequired::new($this, 'VARBINARY');
301
        }
302
303 200
        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 842
    public function registerDoctrineTypeMapping(string $dbType, string $doctrineType) : void
331
    {
332 842
        if ($this->doctrineTypeMapping === null) {
333 837
            $this->initializeAllDoctrineTypeMappings();
334
        }
335
336 842
        if (! Types\Type::hasType($doctrineType)) {
337 270
            throw TypeNotFound::new($doctrineType);
338
        }
339
340 572
        $dbType                             = strtolower($dbType);
341 572
        $this->doctrineTypeMapping[$dbType] = $doctrineType;
342
343 572
        $doctrineType = Type::getType($doctrineType);
344
345 572
        if (! $doctrineType->requiresSQLCommentHint($this)) {
346 302
            return;
347
        }
348
349 270
        $this->markDoctrineTypeCommented($doctrineType);
350 270
    }
351
352
    /**
353
     * Gets the Doctrine type that is mapped for the given database column type.
354
     *
355
     * @throws DBALException
356
     */
357 2735
    public function getDoctrineTypeMapping(string $dbType) : string
358
    {
359 2735
        if ($this->doctrineTypeMapping === null) {
360 368
            $this->initializeAllDoctrineTypeMappings();
361
        }
362
363 2735
        $dbType = strtolower($dbType);
364
365 2735
        if (! isset($this->doctrineTypeMapping[$dbType])) {
366 270
            throw new DBALException(sprintf(
367 20
                'Unknown database type "%s" requested, %s may not support it.',
368 270
                $dbType,
369 270
                static::class
370
            ));
371
        }
372
373 2465
        return $this->doctrineTypeMapping[$dbType];
374
    }
375
376
    /**
377
     * Checks if a database type is currently supported by this platform.
378
     */
379 398
    public function hasDoctrineTypeMappingFor(string $dbType) : bool
380
    {
381 398
        if ($this->doctrineTypeMapping === null) {
382 351
            $this->initializeAllDoctrineTypeMappings();
383
        }
384
385 398
        $dbType = strtolower($dbType);
386
387 398
        return isset($this->doctrineTypeMapping[$dbType]);
388
    }
389
390
    /**
391
     * Initializes the Doctrine Type comments instance variable for in_array() checks.
392
     */
393 13390
    protected function initializeCommentedDoctrineTypes() : void
394
    {
395 13390
        $this->doctrineTypeComments = [];
396
397 13390
        foreach (Type::getTypesMap() as $typeName => $className) {
398 13390
            $type = Type::getType($typeName);
399
400 13390
            if (! $type->requiresSQLCommentHint($this)) {
401 13390
                continue;
402
            }
403
404 13390
            $this->doctrineTypeComments[] = $typeName;
405
        }
406 13390
    }
407
408
    /**
409
     * Is it necessary for the platform to add a parsable type comment to allow reverse engineering the given type?
410
     */
411 17505
    public function isCommentedDoctrineType(Type $doctrineType) : bool
412
    {
413 17505
        if ($this->doctrineTypeComments === null) {
414 13120
            $this->initializeCommentedDoctrineTypes();
415
        }
416
417 17505
        assert(is_array($this->doctrineTypeComments));
418
419 17505
        return in_array($doctrineType->getName(), $this->doctrineTypeComments);
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 270
    public function markDoctrineTypeCommented($doctrineType) : void
428
    {
429 270
        if ($this->doctrineTypeComments === null) {
430 270
            $this->initializeCommentedDoctrineTypes();
431
        }
432
433 270
        assert(is_array($this->doctrineTypeComments));
434
435 270
        $this->doctrineTypeComments[] = $doctrineType instanceof Type ? $doctrineType->getName() : $doctrineType;
436 270
    }
437
438
    /**
439
     * Gets the comment to append to a column comment that helps parsing this type in reverse engineering.
440
     */
441 834
    public function getDoctrineTypeComment(Type $doctrineType) : string
442
    {
443 834
        return '(DC2Type:' . $doctrineType->getName() . ')';
444
    }
445
446
    /**
447
     * Gets the comment of a passed column modified by potential doctrine type comment hints.
448
     */
449 10782
    protected function getColumnComment(Column $column) : ?string
450
    {
451 10782
        $comment = $column->getComment();
452
453 10782
        if ($this->isCommentedDoctrineType($column->getType())) {
454 834
            $comment .= $this->getDoctrineTypeComment($column->getType());
455
        }
456
457 10782
        return $comment;
458
    }
459
460
    /**
461
     * Gets the character used for identifier quoting.
462
     */
463 4711
    public function getIdentifierQuoteCharacter() : string
464
    {
465 4711
        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 54
    public function getRegexpExpression() : string
500
    {
501 54
        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 888
    public function getTrimExpression(string $str, int $mode = TrimMode::UNSPECIFIED, ?string $char = null) : string
622
    {
623 888
        $tokens = [];
624
625 888
        switch ($mode) {
626
            case TrimMode::UNSPECIFIED:
627 216
                break;
628
629
            case TrimMode::LEADING:
630 216
                $tokens[] = 'LEADING';
631 216
                break;
632
633
            case TrimMode::TRAILING:
634 216
                $tokens[] = 'TRAILING';
635 216
                break;
636
637
            case TrimMode::BOTH:
638 216
                $tokens[] = 'BOTH';
639 216
                break;
640
641
            default:
642 24
                throw new InvalidArgumentException(
643 24
                    sprintf(
644 2
                        'The value of $mode is expected to be one of the TrimMode constants, %d given.',
645 24
                        $mode
646
                    )
647
                );
648
        }
649
650 864
        if ($char !== null) {
651 672
            $tokens[] = $char;
652
        }
653
654 864
        if (count($tokens) > 0) {
655 816
            $tokens[] = 'FROM';
656
        }
657
658 864
        $tokens[] = $str;
659
660 864
        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 27
    public function getRtrimExpression(string $string) : string
669
    {
670 27
        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 27
    public function getLtrimExpression(string $string) : string
679
    {
680 27
        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 125
    public function getSubstringExpression(string $string, string $start, ?string $length = null) : string
739
    {
740 125
        if ($length === null) {
741 81
            return sprintf('SUBSTRING(%s FROM %s)', $string, $start);
742
        }
743
744 98
        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 184
    public function getConcatExpression(string ...$string) : string
753
    {
754 184
        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 108
    public function getIsNullExpression(string $value) : string
773
    {
774 108
        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 135
    public function getDateAddSecondsExpression(string $date, string $seconds) : string
864
    {
865 135
        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 135
    public function getDateSubSecondsExpression(string $date, string $seconds) : string
877
    {
878 135
        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 135
    public function getDateAddMinutesExpression(string $date, string $minutes) : string
890
    {
891 135
        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 135
    public function getDateSubMinutesExpression(string $date, string $minutes) : string
903
    {
904 135
        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 135
    public function getDateAddHourExpression(string $date, string $hours) : string
916
    {
917 135
        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 135
    public function getDateSubHourExpression(string $date, string $hours) : string
929
    {
930 135
        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 189
    public function getDateAddDaysExpression(string $date, string $days) : string
942
    {
943 189
        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 136
    public function getDateSubDaysExpression(string $date, string $days) : string
955
    {
956 136
        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 135
    public function getDateAddWeeksExpression(string $date, string $weeks) : string
968
    {
969 135
        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 135
    public function getDateSubWeeksExpression(string $date, string $weeks) : string
981
    {
982 135
        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 135
    public function getDateAddMonthExpression(string $date, string $months) : string
994
    {
995 135
        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 135
    public function getDateSubMonthExpression(string $date, string $months) : string
1007
    {
1008 135
        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 135
    public function getDateAddQuartersExpression(string $date, string $quarters) : string
1020
    {
1021 135
        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 135
    public function getDateSubQuartersExpression(string $date, string $quarters) : string
1033
    {
1034 135
        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 135
    public function getDateAddYearsExpression(string $date, string $years) : string
1046
    {
1047 135
        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 135
    public function getDateSubYearsExpression(string $date, string $years) : string
1059
    {
1060 135
        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 93
    protected function multiplyInterval(string $interval, int $multiplier) : string
1089
    {
1090 93
        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 241
    public function getBitAndComparisonExpression(string $value1, string $value2) : string
1100
    {
1101 241
        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 241
    public function getBitOrComparisonExpression(string $value1, string $value2) : string
1111
    {
1112 241
        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 48
    public function getForUpdateSQL() : string
1124
    {
1125 48
        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 48
    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 48
        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 52
    public function getWriteLockSQL() : string
1157
    {
1158 52
        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 64
    public function getDropDatabaseSQL(string $database) : string
1167
    {
1168 64
        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 5072
    public function getDropTableSQL($table) : string
1179
    {
1180 5072
        $tableArg = $table;
1181
1182 5072
        if ($table instanceof Table) {
1183 391
            $table = $table->getQuotedName($this);
1184
        }
1185
1186 5072
        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 5072
        if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaDropTable)) {
1191 270
            $eventArgs = new SchemaDropTableEventArgs($tableArg, $this);
1192 270
            $this->_eventManager->dispatchEvent(Events::onSchemaDropTable, $eventArgs);
1193
1194 270
            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 5072
        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 16
    public function getDropTemporaryTableSQL($table) : string
1214
    {
1215 16
        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 158
    public function getDropIndexSQL($index, $table = null) : string
1227
    {
1228 158
        if ($index instanceof Index) {
1229 150
            $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 158
        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 781
    public function getDropConstraintSQL($constraint, $table) : string
1244
    {
1245 781
        if (! $constraint instanceof Constraint) {
1246 668
            $constraint = new Identifier($constraint);
1247
        }
1248
1249 781
        if (! $table instanceof Table) {
1250 781
            $table = new Identifier($table);
1251
        }
1252
1253 781
        $constraint = $constraint->getQuotedName($this);
1254 781
        $table      = $table->getQuotedName($this);
1255
1256 781
        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 428
    public function getDropForeignKeySQL($foreignKey, $table) : string
1266
    {
1267 428
        if (! $foreignKey instanceof ForeignKeyConstraint) {
1268 135
            $foreignKey = new Identifier($foreignKey);
1269
        }
1270
1271 428
        if (! $table instanceof Table) {
1272 428
            $table = new Identifier($table);
1273
        }
1274
1275 428
        $foreignKey = $foreignKey->getQuotedName($this);
1276 428
        $table      = $table->getQuotedName($this);
1277
1278 428
        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 8794
    public function getCreateTableSQL(Table $table, int $createFlags = self::CREATE_INDEXES) : array
1290
    {
1291 8794
        if (count($table->getColumns()) === 0) {
1292 270
            throw NoColumnsSpecifiedForTable::new($table->getName());
1293
        }
1294
1295 8524
        $tableName                    = $table->getQuotedName($this);
1296 8524
        $options                      = $table->getOptions();
1297 8524
        $options['uniqueConstraints'] = [];
1298 8524
        $options['indexes']           = [];
1299 8524
        $options['primary']           = [];
1300
1301 8524
        if (($createFlags & self::CREATE_INDEXES) > 0) {
1302 8200
            foreach ($table->getIndexes() as $index) {
1303
                /** @var $index Index */
1304 5514
                if (! $index->isPrimary()) {
1305 1692
                    $options['indexes'][$index->getQuotedName($this)] = $index;
1306
1307 1692
                    continue;
1308
                }
1309
1310 4317
                $options['primary']       = $index->getQuotedColumns($this);
1311 4317
                $options['primary_index'] = $index;
1312
            }
1313
1314 8200
            foreach ($table->getUniqueConstraints() as $uniqueConstraint) {
1315
                /** @var UniqueConstraint $uniqueConstraint */
1316
                $options['uniqueConstraints'][$uniqueConstraint->getQuotedName($this)] = $uniqueConstraint;
1317
            }
1318
        }
1319
1320 8524
        if (($createFlags & self::CREATE_FOREIGNKEYS) > 0) {
1321 5216
            $options['foreignKeys'] = [];
1322
1323 5216
            foreach ($table->getForeignKeys() as $fkConstraint) {
1324 738
                $options['foreignKeys'][] = $fkConstraint;
1325
            }
1326
        }
1327
1328 8524
        $columnSql = [];
1329 8524
        $columns   = [];
1330
1331 8524
        foreach ($table->getColumns() as $column) {
1332 8524
            if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaCreateTableColumn)) {
1333 270
                $eventArgs = new SchemaCreateTableColumnEventArgs($column, $table, $this);
1334 270
                $this->_eventManager->dispatchEvent(Events::onSchemaCreateTableColumn, $eventArgs);
1335
1336 270
                $columnSql = array_merge($columnSql, $eventArgs->getSql());
1337
1338 270
                if ($eventArgs->isDefaultPrevented()) {
1339
                    continue;
1340
                }
1341
            }
1342
1343 8524
            $columnData            = $column->toArray();
1344 8524
            $columnData['name']    = $column->getQuotedName($this);
1345 8524
            $columnData['version'] = $column->hasPlatformOption('version') ? $column->getPlatformOption('version') : false;
1346 8524
            $columnData['comment'] = $this->getColumnComment($column);
1347
1348 8524
            if (in_array($column->getName(), $options['primary'])) {
1349 3993
                $columnData['primary'] = true;
1350
            }
1351
1352 8524
            $columns[] = $columnData;
1353
        }
1354
1355 8524
        if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaCreateTable)) {
1356 270
            $eventArgs = new SchemaCreateTableEventArgs($table, $columns, $options, $this);
1357 270
            $this->_eventManager->dispatchEvent(Events::onSchemaCreateTable, $eventArgs);
1358
1359 270
            if ($eventArgs->isDefaultPrevented()) {
1360
                return array_merge($eventArgs->getSql(), $columnSql);
1361
            }
1362
        }
1363
1364 8524
        $sql = $this->_getCreateTableSQL($tableName, $columns, $options);
1365 8524
        if ($this->supportsCommentOnStatement()) {
1366 2843
            if ($table->hasOption('comment')) {
1367 61
                $sql[] = $this->getCommentOnTableSQL($tableName, $table->getOption('comment'));
1368
            }
1369 2843
            foreach ($table->getColumns() as $column) {
1370 2843
                $comment = $this->getColumnComment($column);
1371
1372 2843
                if ($comment === null || $comment === '') {
1373 2680
                    continue;
1374
                }
1375
1376 474
                $sql[] = $this->getCommentOnColumnSQL($tableName, $column->getQuotedName($this), $comment);
1377
            }
1378
        }
1379
1380 8524
        return array_merge($sql, $columnSql);
1381
    }
1382
1383 61
    protected function getCommentOnTableSQL(string $tableName, ?string $comment) : string
1384
    {
1385 61
        $tableName = new Identifier($tableName);
1386
1387 61
        return sprintf(
1388 6
            'COMMENT ON TABLE %s IS %s',
1389 61
            $tableName->getQuotedName($this),
1390 61
            $this->quoteStringLiteral((string) $comment)
1391
        );
1392
    }
1393
1394 815
    public function getCommentOnColumnSQL(string $tableName, string $columnName, ?string $comment) : string
1395
    {
1396 815
        $tableName  = new Identifier($tableName);
1397 815
        $columnName = new Identifier($columnName);
1398
1399 815
        return sprintf(
1400 115
            'COMMENT ON COLUMN %s.%s IS %s',
1401 815
            $tableName->getQuotedName($this),
1402 815
            $columnName->getQuotedName($this),
1403 815
            $this->quoteStringLiteral((string) $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 1424
    public function getInlineColumnCommentSQL(?string $comment) : string
1413
    {
1414 1424
        if (! $this->supportsInlineColumnComments()) {
1415 162
            throw NotSupported::new(__METHOD__);
1416
        }
1417
1418 1262
        return 'COMMENT ' . $this->quoteStringLiteral((string) $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 894
    protected function _getCreateTableSQL(string $tableName, array $columns, array $options = []) : array
1430
    {
1431 894
        $columnListSql = $this->getColumnDeclarationListSQL($columns);
1432
1433 894
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
1434
            foreach ($options['uniqueConstraints'] as $name => $definition) {
1435
                $columnListSql .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
1436
            }
1437
        }
1438
1439 894
        if (isset($options['primary']) && ! empty($options['primary'])) {
1440 446
            $columnListSql .= ', PRIMARY KEY(' . implode(', ', array_unique(array_values($options['primary']))) . ')';
1441
        }
1442
1443 894
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
1444
            foreach ($options['indexes'] as $index => $definition) {
1445
                $columnListSql .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
1446
            }
1447
        }
1448
1449 894
        $query = 'CREATE TABLE ' . $tableName . ' (' . $columnListSql;
1450
1451 894
        $check = $this->getCheckDeclarationSQL($columns);
1452 894
        if (! empty($check)) {
1453 27
            $query .= ', ' . $check;
1454
        }
1455 894
        $query .= ')';
1456
1457 894
        $sql = [$query];
1458
1459 894
        if (isset($options['foreignKeys'])) {
1460 336
            foreach ((array) $options['foreignKeys'] as $definition) {
1461 99
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
1462
            }
1463
        }
1464
1465 894
        return $sql;
1466
    }
1467
1468 46
    public function getCreateTemporaryTableSnippetSQL() : string
1469
    {
1470 46
        return 'CREATE TEMPORARY TABLE';
1471
    }
1472
1473
    /**
1474
     * Returns the SQL to create a sequence on this platform.
1475
     *
1476
     * @throws DBALException If not supported on this platform.
1477
     */
1478
    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

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

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

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

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

2522
    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...
2523
    {
2524
        throw NotSupported::new(__METHOD__);
2525
    }
2526
2527
    /**
2528
     * @throws DBALException If not supported on this platform.
2529
     */
2530
    public function getListTableForeignKeysSQL(string $table, ?string $database = null) : string
2531
    {
2532
        throw NotSupported::new(__METHOD__);
2533
    }
2534
2535
    /**
2536
     * @throws DBALException If not supported on this platform.
2537
     */
2538
    public function getCreateViewSQL(string $name, string $sql) : string
2539
    {
2540
        throw NotSupported::new(__METHOD__);
2541
    }
2542
2543
    /**
2544
     * @throws DBALException If not supported on this platform.
2545
     */
2546
    public function getDropViewSQL(string $name) : string
2547
    {
2548
        throw NotSupported::new(__METHOD__);
2549
    }
2550
2551
    /**
2552
     * Returns the SQL snippet to drop an existing sequence.
2553
     *
2554
     * @param Sequence|string $sequence
2555
     *
2556
     * @throws DBALException If not supported on this platform.
2557
     */
2558
    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

2558
    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...
2559
    {
2560
        throw NotSupported::new(__METHOD__);
2561
    }
2562
2563
    /**
2564
     * @throws DBALException If not supported on this platform.
2565
     */
2566
    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

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

3036
    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...
3037 234
    {
3038
        $tableIdentifier = new Identifier($tableName);
3039 234
3040
        return 'TRUNCATE ' . $tableIdentifier->getQuotedName($this);
3041
    }
3042
3043
    /**
3044
     * This is for test reasons, many vendors have special requirements for dummy statements.
3045 2481
     */
3046
    public function getDummySelectSQL(string $expression = '1') : string
3047 2481
    {
3048
        return sprintf('SELECT %s', $expression);
3049
    }
3050
3051
    /**
3052
     * Returns the SQL to create a new savepoint.
3053 25
     */
3054
    public function createSavePoint(string $savepoint) : string
3055 25
    {
3056
        return 'SAVEPOINT ' . $savepoint;
3057
    }
3058
3059
    /**
3060
     * Returns the SQL to release a savepoint.
3061 23
     */
3062
    public function releaseSavePoint(string $savepoint) : string
3063 23
    {
3064
        return 'RELEASE SAVEPOINT ' . $savepoint;
3065
    }
3066
3067
    /**
3068
     * Returns the SQL to rollback a savepoint.
3069 25
     */
3070
    public function rollbackSavePoint(string $savepoint) : string
3071 25
    {
3072
        return 'ROLLBACK TO SAVEPOINT ' . $savepoint;
3073
    }
3074
3075
    /**
3076
     * Returns the keyword list instance of this platform.
3077
     *
3078
     * @throws DBALException If no keyword list is specified.
3079 19450
     */
3080
    final public function getReservedKeywordsList() : KeywordList
3081
    {
3082 19450
        // Check for an existing instantiation of the keywords class.
3083 18154
        if ($this->_keywords) {
3084
            return $this->_keywords;
3085
        }
3086 14605
3087 14605
        $class    = $this->getReservedKeywordsClass();
3088 14605
        $keywords = new $class();
3089
        if (! $keywords instanceof KeywordList) {
3090
            throw NotSupported::new(__METHOD__);
3091
        }
3092
3093 14605
        // Store the instance so it doesn't need to be generated on every request.
3094
        $this->_keywords = $keywords;
3095 14605
3096
        return $keywords;
3097
    }
3098
3099
    /**
3100
     * Returns the class name of the reserved keywords list.
3101
     *
3102
     * @throws DBALException If not supported on this platform.
3103
     */
3104
    protected function getReservedKeywordsClass() : string
3105
    {
3106
        throw NotSupported::new(__METHOD__);
3107
    }
3108
3109
    /**
3110
     * Quotes a literal string.
3111
     * This method is NOT meant to fix SQL injections!
3112
     * It is only meant to escape this platform's string literal
3113
     * quote character inside the given literal string.
3114
     *
3115
     * @param string $str The literal string to be quoted.
3116
     *
3117
     * @return string The quoted literal string.
3118 8173
     */
3119
    public function quoteStringLiteral(string $str) : string
3120 8173
    {
3121
        $c = $this->getStringLiteralQuoteCharacter();
3122 8173
3123
        return $c . str_replace($c, $c . $c, $str) . $c;
3124
    }
3125
3126
    /**
3127
     * Gets the character used for string literal quoting.
3128 8443
     */
3129
    public function getStringLiteralQuoteCharacter() : string
3130 8443
    {
3131
        return "'";
3132
    }
3133
3134
    /**
3135
     * Escapes metacharacters in a string intended to be used with a LIKE
3136
     * operator.
3137
     *
3138
     * @param string $inputString a literal, unquoted string
3139
     * @param string $escapeChar  should be reused by the caller in the LIKE
3140
     *                            expression.
3141 297
     */
3142
    final public function escapeStringForLike(string $inputString, string $escapeChar) : string
3143 297
    {
3144 297
        return preg_replace(
3145 297
            '~([' . preg_quote($this->getLikeWildcardCharacters() . $escapeChar, '~') . '])~u',
3146 297
            addcslashes($escapeChar, '\\') . '$1',
3147
            $inputString
3148
        );
3149
    }
3150 297
3151
    protected function getLikeWildcardCharacters() : string
3152 297
    {
3153
        return '%_';
3154
    }
3155
}
3156