Completed
Pull Request — master (#3610)
by Sergei
03:03
created

AbstractPlatform::getCreateConstraintSQL()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 31
ccs 8
cts 8
cp 1
rs 8.8017
c 0
b 0
f 0
cc 6
nc 10
nop 2
crap 6
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
    public function __construct()
97
    {
98
    }
99
100
    /**
101
     * Sets the EventManager used by the Platform.
102
     */
103
    public function setEventManager(EventManager $eventManager) : void
104
    {
105
        $this->_eventManager = $eventManager;
106
    }
107
108
    /**
109
     * Gets the EventManager used by the Platform.
110
     */
111
    public function getEventManager() : ?EventManager
112
    {
113
        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 73047
     */
154
    abstract protected function initializeDoctrineTypeMappings() : void;
155 73047
156
    /**
157
     * Initializes Doctrine Type Mappings with the platform defaults
158
     * and with all additional type mappings.
159
     */
160 66223
    private function initializeAllDoctrineTypeMappings() : void
161
    {
162 66223
        $this->initializeDoctrineTypeMappings();
163 66223
164
        foreach (Type::getTypesMap() as $typeName => $className) {
165
            foreach (Type::getType($typeName)->getMappedDatabaseTypes($this) as $dbType) {
166
                $this->doctrineTypeMapping[$dbType] = $typeName;
167
            }
168
        }
169
    }
170 63393
171
    /**
172 63393
     * 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
    public function getStringTypeDeclarationSQL(array $column) : string
179
    {
180
        $length = $column['length'] ?? null;
181
182
        if (empty($column['fixed'])) {
183
            return $this->getVarcharTypeDeclarationSQLSnippet($length);
184
        }
185
186
        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
    public function getBinaryTypeDeclarationSQL(array $column) : string
197
    {
198
        $length = $column['length'] ?? null;
199
200
        if (empty($column['fixed'])) {
201
            return $this->getVarbinaryTypeDeclarationSQLSnippet($length);
202
        }
203
204
        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
    public function getGuidTypeDeclarationSQL(array $column) : string
218
    {
219
        $column['length'] = 36;
220
        $column['fixed']  = true;
221
222
        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 63471
    public function getJsonTypeDeclarationSQL(array $field) : string
234
    {
235 63471
        return $this->getClobTypeDeclarationSQL($field);
236
    }
237 63471
238 63471
    /**
239 35327
     * @param int|null $length The length of the column in characters
240
     *                         or NULL if the length should be omitted.
241
     *
242 63471
     * @throws ColumnLengthRequired
243
     */
244
    protected function getCharTypeDeclarationSQLSnippet(?int $length) : string
245
    {
246
        $sql = 'CHAR';
247
248
        if ($length !== null) {
249
            $sql .= sprintf('(%d)', $length);
250
        }
251 65546
252
        return $sql;
253 65546
    }
254 61730
255
    /**
256
     * @param int|null $length The length of the column in characters
257 65546
     *                         or NULL if the length should be omitted.
258
     *
259 65546
     * @throws ColumnLengthRequired
260 63529
     */
261 65546
    protected function getVarcharTypeDeclarationSQLSnippet(?int $length) : string
262
    {
263 65546
        if ($length === null) {
264
            throw ColumnLengthRequired::new($this, 'VARCHAR');
265
        }
266
267 65546
        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 61895
     */
278
    protected function getBinaryTypeDeclarationSQLSnippet(?int $length) : string
279 61895
    {
280 61840
        $sql = 'BINARY';
281
282
        if ($length !== null) {
283 61895
            $sql .= sprintf('(%d)', $length);
284
        }
285 61895
286
        return $sql;
287 61895
    }
288 59559
289 59299
    /**
290 24
     * Returns the SQL snippet used to declare a variable length binary column type.
291 59299
     *
292 59299
     * @param int|null $length The length of the column in bytes
293 59299
     *                         or NULL if the length should be omitted.
294
     *
295
     * @throws ColumnLengthRequired
296 59559
     */
297
    protected function getVarbinaryTypeDeclarationSQLSnippet(?int $length) : string
298
    {
299 61871
        if ($length === null) {
300
            throw ColumnLengthRequired::new($this, 'VARBINARY');
301
        }
302
303
        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 61047
313
    /**
314 61047
     * Returns the SQL Snippet used to declare a BLOB column type.
315 61047
     *
316
     * @param mixed[] $field
317 61047
     */
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 59409
    public function registerDoctrineTypeMapping(string $dbType, string $doctrineType) : void
331
    {
332 59409
        if ($this->doctrineTypeMapping === null) {
333
            $this->initializeAllDoctrineTypeMappings();
334
        }
335
336
        if (! Types\Type::hasType($doctrineType)) {
337
            throw TypeNotFound::new($doctrineType);
338
        }
339
340
        $dbType                             = strtolower($dbType);
341
        $this->doctrineTypeMapping[$dbType] = $doctrineType;
342
343
        $doctrineType = Type::getType($doctrineType);
344
345
        if (! $doctrineType->requiresSQLCommentHint($this)) {
346
            return;
347
        }
348
349
        $this->markDoctrineTypeCommented($doctrineType);
350
    }
351
352
    /**
353
     * Gets the Doctrine type that is mapped for the given database column type.
354
     *
355
     * @throws DBALException
356
     */
357
    public function getDoctrineTypeMapping(string $dbType) : string
358
    {
359
        if ($this->doctrineTypeMapping === null) {
360
            $this->initializeAllDoctrineTypeMappings();
361
        }
362
363
        $dbType = strtolower($dbType);
364
365
        if (! isset($this->doctrineTypeMapping[$dbType])) {
366
            throw new DBALException(sprintf(
367
                'Unknown database type "%s" requested, %s may not support it.',
368
                $dbType,
369
                static::class
370
            ));
371
        }
372
373
        return $this->doctrineTypeMapping[$dbType];
374
    }
375
376
    /**
377
     * Checks if a database type is currently supported by this platform.
378
     */
379
    public function hasDoctrineTypeMappingFor(string $dbType) : bool
380
    {
381
        if ($this->doctrineTypeMapping === null) {
382
            $this->initializeAllDoctrineTypeMappings();
383
        }
384
385
        $dbType = strtolower($dbType);
386
387
        return isset($this->doctrineTypeMapping[$dbType]);
388
    }
389
390
    /**
391
     * Initializes the Doctrine Type comments instance variable for in_array() checks.
392
     */
393
    protected function initializeCommentedDoctrineTypes() : void
394
    {
395
        $this->doctrineTypeComments = [];
396 61244
397
        foreach (Type::getTypesMap() as $typeName => $className) {
398 61244
            $type = Type::getType($typeName);
399 60563
400
            if (! $type->requiresSQLCommentHint($this)) {
401
                continue;
402 61244
            }
403 58661
404
            $this->doctrineTypeComments[] = $typeName;
405
        }
406 61208
    }
407 61208
408
    /**
409 61208
     * Is it necessary for the platform to add a parsable type comment to allow reverse engineering the given type?
410
     */
411 61208
    public function isCommentedDoctrineType(Type $doctrineType) : bool
412 61172
    {
413
        if ($this->doctrineTypeComments === null) {
414
            $this->initializeCommentedDoctrineTypes();
415 58636
        }
416 58636
417
        assert(is_array($this->doctrineTypeComments));
418
419
        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 63505
    public function markDoctrineTypeCommented($doctrineType) : void
428
    {
429 63505
        if ($this->doctrineTypeComments === null) {
430 63315
            $this->initializeCommentedDoctrineTypes();
431
        }
432
433 63505
        assert(is_array($this->doctrineTypeComments));
434
435 63505
        $this->doctrineTypeComments[] = $doctrineType instanceof Type ? $doctrineType->getName() : $doctrineType;
436 58711
    }
437
438
    /**
439 63469
     * Gets the comment to append to a column comment that helps parsing this type in reverse engineering.
440
     */
441
    public function getDoctrineTypeComment(Type $doctrineType) : string
442
    {
443
        return '(DC2Type:' . $doctrineType->getName() . ')';
444
    }
445
446
    /**
447
     * Gets the comment of a passed column modified by potential doctrine type comment hints.
448
     */
449 60482
    protected function getColumnComment(Column $column) : ?string
450
    {
451 60482
        $comment = $column->getComment();
452 57046
453
        if ($this->isCommentedDoctrineType($column->getType())) {
454
            $comment .= $this->getDoctrineTypeComment($column->getType());
455 60482
        }
456
457 60482
        return $comment;
458
    }
459
460
    /**
461
     * Gets the character used for identifier quoting.
462
     */
463
    public function getIdentifierQuoteCharacter() : string
464
    {
465 67056
        return '"';
466
    }
467 67056
468
    /**
469 67056
     * Gets the string portion that starts an SQL comment.
470 67056
     */
471
    public function getSqlCommentStartString() : string
472 67056
    {
473 67056
        return '--';
474
    }
475
476 67056
    /**
477
     * Gets the string portion that ends an SQL comment.
478 67056
     */
479
    public function getSqlCommentEndString() : string
480
    {
481
        return "\n";
482
    }
483
484
    /**
485 67311
     * Gets all SQL wildcard characters of the platform.
486
     *
487 67311
     * @return string[]
488 67020
     */
489
    public function getWildcards() : array
490
    {
491 67311
        return ['%', '_'];
492
    }
493 67311
494
    /**
495
     * Returns the regular expression operator.
496
     *
497
     * @throws DBALException If not supported on this platform.
498
     */
499
    public function getRegexpExpression() : string
500
    {
501
        throw NotSupported::new(__METHOD__);
502
    }
503 58636
504
    /**
505 58636
     * Returns the SQL snippet to get the average value of a column.
506 58636
     *
507
     * @param string $value SQL expression producing the value.
508
     */
509 58636
    public function getAvgExpression(string $value) : string
510
    {
511 58636
        return 'AVG(' . $value . ')';
512 58636
    }
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 62457
     * @param string $expression The expression to count.
520
     */
521 62457
    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 66377
     * @param string $value SQL expression producing the value.
530
     */
531 66377
    public function getMaxExpression(string $value) : string
532
    {
533 66377
        return 'MAX(' . $value . ')';
534 62457
    }
535
536
    /**
537 66377
     * 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 61706
546
    /**
547 61706
     * 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 63283
     * @param string $string SQL expression producing the string.
574
     */
575 63283
    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 60610
     * @param string $number SQL expression producing the number.
584
     */
585 60610
    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 61706
     * @param string $number   SQL expression producing the number to round.
594
     * @param string $decimals SQL expression producing the number of decimals.
595 61706
     */
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 59718
     * Returns the SQL snippet to trim a string.
614
     *
615 59718
     * @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
    public function getTrimExpression(string $str, int $mode = TrimMode::UNSPECIFIED, ?string $char = null) : string
622
    {
623
        $tokens = [];
624
625
        switch ($mode) {
626
            case TrimMode::UNSPECIFIED:
627
                break;
628
629
            case TrimMode::LEADING:
630
                $tokens[] = 'LEADING';
631
                break;
632
633
            case TrimMode::TRAILING:
634
                $tokens[] = 'TRAILING';
635 47910
                break;
636
637 47910
            case TrimMode::BOTH:
638
                $tokens[] = 'BOTH';
639
                break;
640
641
            default:
642
                throw new InvalidArgumentException(
643
                    sprintf(
644
                        'The value of $mode is expected to be one of the TrimMode constants, %d given.',
645
                        $mode
646
                    )
647
                );
648
        }
649
650
        if ($char !== null) {
651
            $tokens[] = $char;
652
        }
653
654
        if (count($tokens) > 0) {
655
            $tokens[] = 'FROM';
656
        }
657
658
        $tokens[] = $str;
659
660
        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
    public function getRtrimExpression(string $string) : string
669
    {
670
        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
    public function getLtrimExpression(string $string) : string
679
    {
680
        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
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
    public function getSubstringExpression(string $string, string $start, ?string $length = null) : string
739
    {
740
        if ($length === null) {
741
            return sprintf('SUBSTRING(%s FROM %s)', $string, $start);
742
        }
743
744
        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
    public function getConcatExpression(string ...$string) : string
753
    {
754
        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
    public function getIsNullExpression(string $value) : string
773
    {
774
        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 57083
     *
792
     * Note: There is a slight difference in the way BETWEEN works on some databases.
793 57083
     * http://www.w3schools.com/sql/sql_between.asp. If you want complete database
794
     * independence you should avoid using between().
795 57083
     *
796
     * @param string $value SQL expression producing the value to compare.
797 57007
     * @param string $min   SQL expression producing the lower value to compare with.
798 57007
     * @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 56985
    {
802 56985
        return $value . ' BETWEEN ' . $min . ' AND ' . $max;
803
    }
804
805 56963
    /**
806 56963
     * Returns the SQL to get the arccosine of a value.
807
     *
808
     * @param string $number SQL expression producing the number.
809 57083
     */
810 56979
    public function getAcosExpression(string $number) : string
811
    {
812
        return 'ACOS(' . $number . ')';
813 57083
    }
814 57057
815
    /**
816
     * Returns the SQL to get the sine of a value.
817 57083
     *
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 28233
     */
828
    public function getPiExpression() : string
829 28233
    {
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 28233
    {
840
        return 'COS(' . $number . ')';
841 28233
    }
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
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
    public function getDateAddSecondsExpression(string $date, string $seconds) : string
864
    {
865
        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
    public function getDateSubSecondsExpression(string $date, string $seconds) : string
877
    {
878
        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
    public function getDateAddMinutesExpression(string $date, string $minutes) : string
890
    {
891
        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
    public function getDateSubMinutesExpression(string $date, string $minutes) : string
903
    {
904
        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
    public function getDateAddHourExpression(string $date, string $hours) : string
916
    {
917
        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 47887
     *
926
     * @throws DBALException If not supported on this platform.
927 47887
     */
928
    public function getDateSubHourExpression(string $date, string $hours) : string
929
    {
930
        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
    public function getDateAddDaysExpression(string $date, string $days) : string
942
    {
943
        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
    public function getDateSubDaysExpression(string $date, string $days) : string
955
    {
956
        return $this->getDateArithmeticIntervalExpression($date, '-', $days, DateIntervalUnit::DAY);
957 66111
    }
958
959 66111
    /**
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
    public function getDateAddWeeksExpression(string $date, string $weeks) : string
968
    {
969
        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
    public function getDateSubWeeksExpression(string $date, string $weeks) : string
981
    {
982
        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
    public function getDateAddMonthExpression(string $date, string $months) : string
994
    {
995
        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
    public function getDateSubMonthExpression(string $date, string $months) : string
1007
    {
1008
        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
    public function getDateAddQuartersExpression(string $date, string $quarters) : string
1020
    {
1021
        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
    public function getDateSubQuartersExpression(string $date, string $quarters) : string
1033
    {
1034
        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
    public function getDateAddYearsExpression(string $date, string $years) : string
1046
    {
1047
        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
    public function getDateSubYearsExpression(string $date, string $years) : string
1059
    {
1060
        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 64297
     * @param string $operator The arithmetic operator (+ or -).
1068
     * @param string $interval SQL expression representing the value of the interval that shall be calculated
1069 64297
     *                         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
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 64297
     *
1083
     * @param string $interval   SQL expression describing the interval value
1084 64297
     * @param int    $multiplier Interval multiplier
1085
     *
1086
     * @throws DBALException
1087
     */
1088
    protected function multiplyInterval(string $interval, int $multiplier) : string
1089
    {
1090
        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 64297
     * @param string $value2 SQL expression producing the second value.
1098
     */
1099 64297
    public function getBitAndComparisonExpression(string $value1, string $value2) : string
1100
    {
1101
        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
    public function getBitOrComparisonExpression(string $value1, string $value2) : string
1111
    {
1112 64297
        return '(' . $value1 . ' | ' . $value2 . ')';
1113
    }
1114 64297
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
    public function getForUpdateSQL() : string
1124
    {
1125
        return 'FOR UPDATE';
1126
    }
1127 64297
1128
    /**
1129 64297
     * 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
    public function appendLockHint(string $fromClause, ?int $lockMode) : string
1136
    {
1137
        return $fromClause;
1138
    }
1139
1140
    /**
1141
     * Returns the SQL snippet to append to any SELECT statement which locks rows in shared read lock.
1142 64297
     *
1143
     * This defaults to the ANSI SQL "FOR UPDATE", which is an exclusive lock (Write). Some database
1144 64297
     * 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
    public function getWriteLockSQL() : string
1157 64301
    {
1158
        return $this->getForUpdateSQL();
1159 64301
    }
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
    public function getDropDatabaseSQL(string $database) : string
1167
    {
1168
        return 'DROP DATABASE ' . $database;
1169
    }
1170
1171
    /**
1172 64297
     * Returns the SQL snippet to drop an existing table.
1173
     *
1174 64297
     * @param Table|string $table
1175
     *
1176
     * @throws InvalidArgumentException
1177
     */
1178
    public function getDropTableSQL($table) : string
1179
    {
1180
        $tableArg = $table;
1181
1182
        if ($table instanceof Table) {
1183
            $table = $table->getQuotedName($this);
1184
        }
1185
1186
        if (! is_string($table)) {
1187 64297
            throw new InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
1188
        }
1189 64297
1190
        if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaDropTable)) {
1191
            $eventArgs = new SchemaDropTableEventArgs($tableArg, $this);
1192
            $this->_eventManager->dispatchEvent(Events::onSchemaDropTable, $eventArgs);
1193
1194
            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 64297
            }
1203
        }
1204 64297
1205
        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
    public function getDropTemporaryTableSQL($table) : string
1214
    {
1215
        return $this->getDropTableSQL($table);
1216
    }
1217 64297
1218
    /**
1219 64297
     * 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
    public function getDropIndexSQL($index, $table = null) : string
1227
    {
1228
        if ($index instanceof Index) {
1229
            $index = $index->getQuotedName($this);
1230
        } elseif (! is_string($index)) {
1231
            throw new InvalidArgumentException('AbstractPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
1232 64297
        }
1233
1234 64297
        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
    public function getDropConstraintSQL($constraint, $table) : string
1244
    {
1245
        if (! $constraint instanceof Constraint) {
1246
            $constraint = new Identifier($constraint);
1247 64297
        }
1248
1249 64297
        if (! $table instanceof Table) {
1250
            $table = new Identifier($table);
1251
        }
1252
1253
        $constraint = $constraint->getQuotedName($this);
1254
        $table      = $table->getQuotedName($this);
1255
1256
        return 'ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $constraint;
1257
    }
1258
1259
    /**
1260
     * Returns the SQL to drop a foreign key.
1261
     *
1262 64297
     * @param ForeignKeyConstraint|string $foreignKey
1263
     * @param Table|string                $table
1264 64297
     */
1265
    public function getDropForeignKeySQL($foreignKey, $table) : string
1266
    {
1267
        if (! $foreignKey instanceof ForeignKeyConstraint) {
1268
            $foreignKey = new Identifier($foreignKey);
1269
        }
1270
1271
        if (! $table instanceof Table) {
1272
            $table = new Identifier($table);
1273
        }
1274
1275
        $foreignKey = $foreignKey->getQuotedName($this);
1276
        $table      = $table->getQuotedName($this);
1277 64297
1278
        return 'ALTER TABLE ' . $table . ' DROP FOREIGN KEY ' . $foreignKey;
1279 64297
    }
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.
0 ignored issues
show
Documentation introduced by
The doc-type array<int, could not be parsed: Expected ">" at position 5, but found "end of type". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1286
     *
1287
     * @throws DBALException
1288
     */
1289
    public function getCreateTableSQL(Table $table, int $createFlags = self::CREATE_INDEXES) : array
1290
    {
1291
        if (count($table->getColumns()) === 0) {
1292 64297
            throw NoColumnsSpecifiedForTable::new($table->getName());
1293
        }
1294 64297
1295
        $tableName                    = $table->getQuotedName($this);
1296
        $options                      = $table->getOptions();
1297
        $options['uniqueConstraints'] = [];
1298
        $options['indexes']           = [];
1299
        $options['primary']           = [];
1300
1301
        if (($createFlags & self::CREATE_INDEXES) > 0) {
1302
            foreach ($table->getIndexes() as $index) {
1303
                /** @var $index Index */
1304
                if (! $index->isPrimary()) {
1305
                    $options['indexes'][$index->getQuotedName($this)] = $index;
1306
1307
                    continue;
1308
                }
1309
1310
                $options['primary']       = $index->getQuotedColumns($this);
1311
                $options['primary_index'] = $index;
1312
            }
1313
1314
            foreach ($table->getUniqueConstraints() as $uniqueConstraint) {
1315
                /** @var UniqueConstraint $uniqueConstraint */
1316
                $options['uniqueConstraints'][$uniqueConstraint->getQuotedName($this)] = $uniqueConstraint;
1317
            }
1318
        }
1319
1320
        if (($createFlags & self::CREATE_FOREIGNKEYS) > 0) {
1321
            $options['foreignKeys'] = [];
1322
1323 63980
            foreach ($table->getForeignKeys() as $fkConstraint) {
1324
                $options['foreignKeys'][] = $fkConstraint;
1325 63980
            }
1326
        }
1327
1328
        $columnSql = [];
1329
        $columns   = [];
1330
1331
        foreach ($table->getColumns() as $column) {
1332
            if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaCreateTableColumn)) {
1333
                $eventArgs = new SchemaCreateTableColumnEventArgs($column, $table, $this);
1334
                $this->_eventManager->dispatchEvent(Events::onSchemaCreateTableColumn, $eventArgs);
1335
1336 61765
                $columnSql = array_merge($columnSql, $eventArgs->getSql());
1337
1338 61765
                if ($eventArgs->isDefaultPrevented()) {
1339
                    continue;
1340
                }
1341
            }
1342
1343
            $columnData            = $column->toArray();
1344
            $columnData['name']    = $column->getQuotedName($this);
1345
            $columnData['version'] = $column->hasPlatformOption('version') ? $column->getPlatformOption('version') : false;
1346 50874
            $columnData['comment'] = $this->getColumnComment($column);
1347
1348 50874
            if (in_array($column->getName(), $options['primary'])) {
1349
                $columnData['primary'] = true;
1350
            }
1351
1352
            $columns[] = $columnData;
1353
        }
1354
1355
        if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaCreateTable)) {
1356
            $eventArgs = new SchemaCreateTableEventArgs($table, $columns, $options, $this);
1357
            $this->_eventManager->dispatchEvent(Events::onSchemaCreateTable, $eventArgs);
1358
1359
            if ($eventArgs->isDefaultPrevented()) {
1360 53296
                return array_merge($eventArgs->getSql(), $columnSql);
1361
            }
1362 53296
        }
1363
1364
        $sql = $this->_getCreateTableSQL($tableName, $columns, $options);
1365
        if ($this->supportsCommentOnStatement()) {
1366
            if ($table->hasOption('comment')) {
1367
                $sql[] = $this->getCommentOnTableSQL($tableName, $table->getOption('comment'));
1368
            }
1369
            foreach ($table->getColumns() as $column) {
1370
                $comment = $this->getColumnComment($column);
1371
1372
                if ($comment === null || $comment === '') {
1373
                    continue;
1374
                }
1375
1376
                $sql[] = $this->getCommentOnColumnSQL($tableName, $column->getQuotedName($this), $comment);
1377
            }
1378
        }
1379
1380
        return array_merge($sql, $columnSql);
1381
    }
1382
1383
    protected function getCommentOnTableSQL(string $tableName, ?string $comment) : string
1384
    {
1385 58141
        $tableName = new Identifier($tableName);
1386
1387 58141
        return sprintf(
1388
            'COMMENT ON TABLE %s IS %s',
1389
            $tableName->getQuotedName($this),
1390
            $this->quoteStringLiteral((string) $comment)
1391
        );
1392
    }
1393
1394
    public function getCommentOnColumnSQL(string $tableName, string $columnName, ?string $comment) : string
1395
    {
1396
        $tableName  = new Identifier($tableName);
1397 50697
        $columnName = new Identifier($columnName);
1398
1399 50697
        return sprintf(
1400
            'COMMENT ON COLUMN %s.%s IS %s',
1401
            $tableName->getQuotedName($this),
1402
            $columnName->getQuotedName($this),
1403
            $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 65555
     */
1412
    public function getInlineColumnCommentSQL(?string $comment) : string
1413 65555
    {
1414
        if (! $this->supportsInlineColumnComments()) {
1415 65555
            throw NotSupported::new(__METHOD__);
1416 7175
        }
1417
1418
        return 'COMMENT ' . $this->quoteStringLiteral((string) $comment);
1419 65555
    }
1420
1421
    /**
1422
     * Returns the SQL used to create a table.
1423 65555
     *
1424 58236
     * @param mixed[][] $columns
1425 58236
     * @param mixed[]   $options
1426
     *
1427 58236
     * @return array<int, string>
0 ignored issues
show
Documentation introduced by
The doc-type array<int, could not be parsed: Expected ">" at position 5, but found "end of type". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1428
     */
1429
    protected function _getCreateTableSQL(string $tableName, array $columns, array $options = []) : array
1430
    {
1431
        $columnListSql = $this->getColumnDeclarationListSQL($columns);
1432
1433
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
1434
            foreach ($options['uniqueConstraints'] as $name => $definition) {
1435
                $columnListSql .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
1436
            }
1437
        }
1438 65555
1439
        if (isset($options['primary']) && ! empty($options['primary'])) {
1440
            $columnListSql .= ', PRIMARY KEY(' . implode(', ', array_unique(array_values($options['primary']))) . ')';
1441
        }
1442
1443
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
1444
            foreach ($options['indexes'] as $index => $definition) {
1445
                $columnListSql .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
1446
            }
1447
        }
1448 26634
1449
        $query = 'CREATE TABLE ' . $tableName . ' (' . $columnListSql;
1450 26634
1451
        $check = $this->getCheckDeclarationSQL($columns);
1452
        if (! empty($check)) {
1453
            $query .= ', ' . $check;
1454
        }
1455
        $query .= ')';
1456
1457
        $sql = [$query];
1458
1459
        if (isset($options['foreignKeys'])) {
1460
            foreach ((array) $options['foreignKeys'] as $definition) {
1461
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
1462
            }
1463 50522
        }
1464
1465 50522
        return $sql;
1466 50493
    }
1467 22326
1468
    public function getCreateTemporaryTableSnippetSQL() : string
1469
    {
1470
        return 'CREATE TEMPORARY TABLE';
1471 50522
    }
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
1479
    {
1480
        throw NotSupported::new(__METHOD__);
1481
    }
1482 58979
1483
    /**
1484 58979
     * Returns the SQL to change a sequence on this platform.
1485 57730
     *
1486
     * @throws DBALException If not supported on this platform.
1487
     */
1488 58979
    public function getAlterSequenceSQL(Sequence $sequence) : string
1489 58979
    {
1490
        throw NotSupported::new(__METHOD__);
1491
    }
1492 58979
1493 58979
    /**
1494
     * Returns the SQL to create a constraint on a table on this platform.
1495 58979
     *
1496
     * @param Table|string $table
1497
     *
1498
     * @throws InvalidArgumentException
1499
     */
1500
    public function getCreateConstraintSQL(Constraint $constraint, $table) : string
1501
    {
1502
        if ($table instanceof Table) {
1503
            $table = $table->getQuotedName($this);
1504
        }
1505
1506 60105
        $query = 'ALTER TABLE ' . $table . ' ADD CONSTRAINT ' . $constraint->getQuotedName($this);
1507
1508 60105
        $columnList = '(' . implode(', ', $constraint->getQuotedColumns($this)) . ')';
1509 57491
1510
        $referencesClause = '';
1511
        if ($constraint instanceof Index) {
1512 60105
            if ($constraint->isPrimary()) {
1513 60105
                $query .= ' PRIMARY KEY';
1514
            } elseif ($constraint->isUnique()) {
1515
                $query .= ' UNIQUE';
1516 60105
            } else {
1517 60105
                throw new InvalidArgumentException(
1518
                    'Can only create primary or unique constraints, no common indexes with getCreateConstraintSQL().'
1519 60105
                );
1520
            }
1521
        } elseif ($constraint instanceof ForeignKeyConstraint) {
1522
            $query .= ' FOREIGN KEY';
1523
1524
            $referencesClause = ' REFERENCES ' . $constraint->getQuotedForeignTableName($this) .
1525
                ' (' . implode(', ', $constraint->getQuotedForeignColumns($this)) . ')';
1526
        }
1527
        $query .= ' ' . $columnList . $referencesClause;
1528
1529
        return $query;
1530
    }
1531
1532
    /**
1533 66091
     * Returns the SQL to create an index on a table on this platform.
1534
     *
1535 66091
     * @param Table|string $table The name of the table on which the index is to be created.
1536
     *
1537
     * @throws InvalidArgumentException
1538
     */
1539 66091
    public function getCreateIndexSQL(Index $index, $table) : string
1540 58536
    {
1541
        if ($table instanceof Table) {
1542
            $table = $table->getQuotedName($this);
1543 66055
        }
1544 66055
        $name    = $index->getQuotedName($this);
1545 66055
        $columns = $index->getColumns();
1546 66055
1547 66055
        if (count($columns) === 0) {
1548
            throw new InvalidArgumentException('Incomplete definition. "columns" required.');
1549 66055
        }
1550 66009
1551
        if ($index->isPrimary()) {
1552 65753
            return $this->getCreatePrimaryKeySQL($index, $table);
1553 65621
        }
1554 65621
1555
        $query  = 'CREATE ' . $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name . ' ON ' . $table;
1556 64548
        $query .= ' (' . $this->getIndexFieldDeclarationListSQL($index) . ')' . $this->getPartialIndexSQL($index);
1557
1558
        return $query;
1559
    }
1560
1561 66055
    /**
1562 66055
     * Adds condition for partial index.
1563
     */
1564 66055
    protected function getPartialIndexSQL(Index $index) : string
1565 66055
    {
1566 58261
        if ($this->supportsPartialIndexes() && $index->hasOption('where')) {
1567 58261
            return ' WHERE ' . $index->getOption('where');
1568
        }
1569 58261
1570
        return '';
1571 58261
    }
1572
1573
    /**
1574
     * Adds additional flags for index generation.
1575
     */
1576 66055
    protected function getCreateIndexSQLFlags(Index $index) : string
1577 66055
    {
1578 66055
        return $index->isUnique() ? 'UNIQUE ' : '';
1579 66055
    }
1580
1581 66055
    /**
1582 65164
     * Returns the SQL to create an unnamed primary key constraint.
1583
     *
1584
     * @param Table|string $table
1585 66055
     */
1586 65581
    public function getCreatePrimaryKeySQL(Index $index, $table) : string
1587
    {
1588
        if ($table instanceof Table) {
1589 66055
            $table = $table->getQuotedName($this);
1590
        }
1591
1592 66055
        return 'ALTER TABLE ' . $table . ' ADD PRIMARY KEY (' . $this->getIndexFieldDeclarationListSQL($index) . ')';
1593 65601
    }
1594 65601
1595 64034
    /**
1596
     * Returns the SQL to create a named schema.
1597
     *
1598
     * @throws DBALException If not supported on this platform.
1599 66055
     */
1600 58261
    public function getCreateSchemaSQL(string $schemaName) : string
1601 58261
    {
1602
        throw NotSupported::new(__METHOD__);
1603 58261
    }
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 66055
     * chains separated by dot and quotes them independently.
1609 66055
     *
1610 61969
     * NOTE: Just because you CAN use quoted identifiers doesn't mean
1611 41444
     * you SHOULD use them. In general, they end up causing way more
1612
     * problems than they solve.
1613 61969
     *
1614 61969
     * @param string $identifier The identifier name to be quoted.
1615
     *
1616 61969
     * @return string The quoted identifier string.
1617 61935
     */
1618
    public function quoteIdentifier(string $identifier) : string
1619
    {
1620 59593
        if (strpos($identifier, '.') !== false) {
1621
            $parts = array_map([$this, 'quoteSingleIdentifier'], explode('.', $identifier));
1622
1623
            return implode('.', $parts);
1624 66055
        }
1625
1626
        return $this->quoteSingleIdentifier($identifier);
1627 41444
    }
1628
1629 41444
    /**
1630
     * Quotes a single identifier (no dot chain separation).
1631 41444
     *
1632 4
     * @param string $str The identifier name to be quoted.
1633 41444
     *
1634 41444
     * @return string The quoted identifier string.
1635
     */
1636
    public function quoteSingleIdentifier(string $str) : string
1637
    {
1638
        $c = $this->getIdentifierQuoteCharacter();
1639
1640
        return $c . str_replace($c, $c . $c, $str) . $c;
1641
    }
1642
1643
    /**
1644
     * Returns the SQL to create a new foreign key.
1645 58448
     *
1646
     * @param ForeignKeyConstraint $foreignKey The foreign key constraint.
1647 58448
     * @param Table|string         $table      The name of the table on which the foreign key is to be created.
1648 58448
     */
1649
    public function getCreateForeignKeySQL(ForeignKeyConstraint $foreignKey, $table) : string
1650 58448
    {
1651 131
        if ($table instanceof Table) {
1652 58448
            $table = $table->getQuotedName($this);
1653 58448
        }
1654 58448
1655
        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>
0 ignored issues
show
Documentation introduced by
The doc-type array<int, could not be parsed: Expected ">" at position 5, but found "end of type". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1664
     *
1665
     * @throws DBALException If not supported on this platform.
1666
     */
1667 60281
    public function getAlterTableSQL(TableDiff $diff) : array
1668
    {
1669 60281
        throw NotSupported::new(__METHOD__);
1670 57378
    }
1671
1672
    /**
1673 59318
     * @param mixed[] $columnSql
1674
     */
1675
    protected function onSchemaAlterTableAddColumn(Column $column, TableDiff $diff, array &$columnSql) : bool
1676
    {
1677
        if ($this->_eventManager === null) {
1678
            return false;
1679
        }
1680
1681
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableAddColumn)) {
1682
            return false;
1683
        }
1684
1685 60084
        $eventArgs = new SchemaAlterTableAddColumnEventArgs($column, $diff, $this);
1686
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableAddColumn, $eventArgs);
1687 60084
1688
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
1689 60084
1690
        return $eventArgs->isDefaultPrevented();
1691
    }
1692
1693
    /**
1694
     * @param string[] $columnSql
1695 60084
     */
1696 59956
    protected function onSchemaAlterTableRemoveColumn(Column $column, TableDiff $diff, array &$columnSql) : bool
1697
    {
1698
        if ($this->_eventManager === null) {
1699 60084
            return false;
1700
        }
1701
1702
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableRemoveColumn)) {
1703
            return false;
1704
        }
1705 60084
1706
        $eventArgs = new SchemaAlterTableRemoveColumnEventArgs($column, $diff, $this);
1707 60084
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableRemoveColumn, $eventArgs);
1708 60084
1709 59527
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
1710
1711 60084
        return $eventArgs->isDefaultPrevented();
1712
    }
1713 60084
1714
    /**
1715 60084
     * @param string[] $columnSql
1716 60002
     */
1717 59675
    protected function onSchemaAlterTableChangeColumn(ColumnDiff $columnDiff, TableDiff $diff, array &$columnSql) : bool
1718
    {
1719
        if ($this->_eventManager === null) {
1720
            return false;
1721 60084
        }
1722
1723
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableChangeColumn)) {
1724
            return false;
1725
        }
1726
1727 53249
        $eventArgs = new SchemaAlterTableChangeColumnEventArgs($columnDiff, $diff, $this);
1728
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableChangeColumn, $eventArgs);
1729 53249
1730
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
1731
1732
        return $eventArgs->isDefaultPrevented();
1733
    }
1734
1735
    /**
1736
     * @param string[] $columnSql
1737
     */
1738
    protected function onSchemaAlterTableRenameColumn(string $oldColumnName, Column $column, TableDiff $diff, array &$columnSql) : bool
1739
    {
1740
        if ($this->_eventManager === null) {
1741
            return false;
1742
        }
1743
1744
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableRenameColumn)) {
1745
            return false;
1746
        }
1747
1748
        $eventArgs = new SchemaAlterTableRenameColumnEventArgs($oldColumnName, $column, $diff, $this);
1749
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableRenameColumn, $eventArgs);
1750
1751
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
1752
1753
        return $eventArgs->isDefaultPrevented();
1754
    }
1755
1756
    /**
1757
     * @param string[] $sql
1758
     */
1759
    protected function onSchemaAlterTable(TableDiff $diff, array &$sql) : bool
1760
    {
1761
        if ($this->_eventManager === null) {
1762
            return false;
1763
        }
1764
1765 58426
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTable)) {
1766
            return false;
1767 58426
        }
1768
1769
        $eventArgs = new SchemaAlterTableEventArgs($diff, $this);
1770
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTable, $eventArgs);
1771 58426
1772
        $sql = array_merge($sql, $eventArgs->getSql());
1773 58426
1774
        return $eventArgs->isDefaultPrevented();
1775 58426
    }
1776 58426
1777 58426
    /**
1778 58426
     * @return string[]
1779 58376
     */
1780 58376
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) : array
1781
    {
1782
        $tableName = $diff->getName($this)->getQuotedName($this);
1783 58426
1784
        $sql = [];
1785
        if ($this->supportsForeignKeyConstraints()) {
1786 58376
            foreach ($diff->removedForeignKeys as $foreignKey) {
1787 58376
                $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
1788
            }
1789 58376
            foreach ($diff->changedForeignKeys as $foreignKey) {
1790 58376
                $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
1791
            }
1792 58426
        }
1793
1794 58426
        foreach ($diff->removedIndexes as $index) {
1795
            $sql[] = $this->getDropIndexSQL($index, $tableName);
1796
        }
1797
        foreach ($diff->changedIndexes as $index) {
1798
            $sql[] = $this->getDropIndexSQL($index, $tableName);
1799
        }
1800
1801
        return $sql;
1802
    }
1803
1804
    /**
1805
     * @return string[]
1806 63036
     */
1807
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff) : array
1808 63036
    {
1809 62002
        $sql     = [];
1810
        $newName = $diff->getNewName();
1811 63036
1812 63036
        if ($newName !== null) {
1813
            $tableName = $newName->getQuotedName($this);
1814 63036
        } else {
1815
            $tableName = $diff->getName($this)->getQuotedName($this);
1816
        }
1817
1818 63036
        if ($this->supportsForeignKeyConstraints()) {
1819 56592
            foreach ($diff->addedForeignKeys as $foreignKey) {
1820
                $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
1821
            }
1822 62998
1823 62998
            foreach ($diff->changedForeignKeys as $foreignKey) {
1824
                $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
1825 62998
            }
1826
        }
1827
1828
        foreach ($diff->addedIndexes as $index) {
1829
            $sql[] = $this->getCreateIndexSQL($index, $tableName);
1830
        }
1831
1832
        foreach ($diff->changedIndexes as $index) {
1833 64420
            $sql[] = $this->getCreateIndexSQL($index, $tableName);
1834
        }
1835 64420
1836 48545
        foreach ($diff->renamedIndexes as $oldIndexName => $index) {
1837
            $oldIndexName = new Identifier($oldIndexName);
1838
            $sql          = array_merge(
1839 64410
                $sql,
1840
                $this->getRenameIndexSQL($oldIndexName->getQuotedName($this), $index, $tableName)
1841
            );
1842
        }
1843
1844
        return $sql;
1845
    }
1846
1847 61306
    /**
1848
     * Returns the SQL for renaming an index on a table.
1849 61306
     *
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
    protected function getRenameIndexSQL(string $oldIndexName, Index $index, string $tableName) : array
1857
    {
1858
        return [
1859 59459
            $this->getDropIndexSQL($oldIndexName, $tableName),
1860
            $this->getCreateIndexSQL($index, $tableName),
1861 59459
        ];
1862
    }
1863
1864
    /**
1865 59459
     * 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 57770
     *
1878
     *      default
1879 57770
     *          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
    public function getColumnDeclarationListSQL(array $fields) : string
1892
    {
1893
        $queryFields = [];
1894
1895 65722
        foreach ($fields as $field) {
1896
            $queryFields[] = $this->getColumnDeclarationSQL($field['name'], $field);
1897 65722
        }
1898 59619
1899
        return implode(', ', $queryFields);
1900 59619
    }
1901
1902
    /**
1903 65722
     * 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 65594
     *          field. If this argument is missing the field should be
1914
     *          declared to have the longest length allowed by the DBMS.
1915 65594
     *
1916
     *      default
1917 65594
     *          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 64051
     *      check
1929
     *          column check constraint
1930 64051
     *      columnDefinition
1931 2927
     *          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 64051
     */
1935
    public function getColumnDeclarationSQL(string $name, array $field) : string
1936
    {
1937
        if (isset($field['columnDefinition'])) {
1938
            $columnDef = $this->getCustomTypeDeclarationSQL($field);
1939
        } else {
1940
            $default = $this->getDefaultValueDeclarationSQL($field);
1941
1942
            $charset = isset($field['charset']) && $field['charset'] ?
1943
                ' ' . $this->getColumnCharsetDeclarationSQL($field['charset']) : '';
1944
1945
            $collation = isset($field['collation']) && $field['collation'] ?
1946
                ' ' . $this->getColumnCollationDeclarationSQL($field['collation']) : '';
1947
1948
            $notnull = isset($field['notnull']) && $field['notnull'] ? ' NOT NULL' : '';
1949
1950
            $unique = isset($field['unique']) && $field['unique'] ?
1951
                ' ' . $this->getUniqueFieldDeclarationSQL() : '';
1952
1953
            $check = isset($field['check']) && $field['check'] ?
1954
                ' ' . $field['check'] : '';
1955
1956 63065
            $typeDecl  = $field['type']->getSQLDeclaration($field, $this);
1957
            $columnDef = $typeDecl . $charset . $default . $notnull . $unique . $check . $collation;
1958 63065
1959 58435
            if ($this->supportsInlineColumnComments() && isset($field['comment']) && $field['comment'] !== '') {
1960
                $columnDef .= ' ' . $this->getInlineColumnCommentSQL($field['comment']);
1961
            }
1962 62905
        }
1963 62869
1964
        return $name . ' ' . $columnDef;
1965
    }
1966 58211
1967 58211
    /**
1968
     * Returns the SQL snippet that declares a floating point column of arbitrary precision.
1969 58211
     *
1970
     * @param mixed[] $columnDef
1971 58211
     */
1972
    public function getDecimalTypeDeclarationSQL(array $columnDef) : string
1973
    {
1974
        $columnDef['precision'] = ! isset($columnDef['precision']) || empty($columnDef['precision'])
1975
            ? 10 : $columnDef['precision'];
1976
        $columnDef['scale']     = ! isset($columnDef['scale']) || empty($columnDef['scale'])
1977
            ? 0 : $columnDef['scale'];
1978
1979 62103
        return 'NUMERIC(' . $columnDef['precision'] . ', ' . $columnDef['scale'] . ')';
1980
    }
1981 62103
1982 58389
    /**
1983
     * Obtains DBMS specific SQL code portion needed to set a default value
1984
     * declaration to be used in statements like CREATE TABLE.
1985 61989
     *
1986 61953
     * @param mixed[] $field The field definition array.
1987
     *
1988
     * @return string DBMS specific SQL code portion needed to set a default value.
1989 58211
     */
1990 58211
    public function getDefaultValueDeclarationSQL(array $field) : string
1991
    {
1992 58211
        if (! isset($field['default'])) {
1993
            return empty($field['notnull']) ? ' DEFAULT NULL' : '';
1994 58211
        }
1995
1996
        $default = $field['default'];
1997
1998
        if (! isset($field['type'])) {
1999
            return " DEFAULT '" . $default . "'";
2000
        }
2001
2002 62967
        $type = $field['type'];
2003
2004 62967
        if ($type instanceof Types\PhpIntegerMappingType) {
2005 59557
            return ' DEFAULT ' . $default;
2006
        }
2007
2008 62635
        if ($type instanceof Types\PhpDateTimeMappingType && $default === $this->getCurrentTimestampSQL()) {
2009 62599
            return ' DEFAULT ' . $this->getCurrentTimestampSQL();
2010
        }
2011
2012 58211
        if ($type instanceof Types\TimeType && $default === $this->getCurrentTimeSQL()) {
2013 58211
            return ' DEFAULT ' . $this->getCurrentTimeSQL();
2014
        }
2015 58211
2016
        if ($type instanceof Types\DateType && $default === $this->getCurrentDateSQL()) {
2017 58211
            return ' DEFAULT ' . $this->getCurrentDateSQL();
2018
        }
2019
2020
        if ($type instanceof Types\BooleanType) {
2021
            return " DEFAULT '" . $this->convertBooleans($default) . "'";
2022
        }
2023
2024
        if (is_int($default) || is_float($default)) {
2025
            return ' DEFAULT ' . $default;
2026 61866
        }
2027
2028 61866
        return ' DEFAULT ' . $this->quoteStringLiteral($default);
2029 57666
    }
2030
2031
    /**
2032 61750
     * Obtains DBMS specific SQL code portion needed to set a CHECK constraint
2033 59387
     * declaration to be used in statements like CREATE TABLE.
2034
     *
2035
     * @param string[]|mixed[][] $definition The check definition.
2036 58211
     *
2037 58211
     * @return string DBMS specific SQL code portion needed to set a CHECK constraint.
2038
     */
2039 58211
    public function getCheckDeclarationSQL(array $definition) : string
2040
    {
2041 58211
        $constraints = [];
2042
        foreach ($definition as $def) {
2043
            if (is_string($def)) {
2044
                $constraints[] = 'CHECK (' . $def . ')';
2045
            } else {
2046
                if (isset($def['min'])) {
2047
                    $constraints[] = 'CHECK (' . $def['name'] . ' >= ' . $def['min'] . ')';
2048
                }
2049 63883
2050
                if (! isset($def['max'])) {
2051 63883
                    continue;
2052 59895
                }
2053
2054
                $constraints[] = 'CHECK (' . $def['name'] . ' <= ' . $def['max'] . ')';
2055 63213
            }
2056 63177
        }
2057
2058
        return implode(', ', $constraints);
2059 58211
    }
2060 58211
2061
    /**
2062 58211
     * Obtains DBMS specific SQL code portion needed to set a unique
2063
     * constraint declaration to be used in statements like CREATE TABLE.
2064 58211
     *
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 63737
     * @throws InvalidArgumentException
2071
     */
2072 63737
    public function getUniqueConstraintDeclarationSQL(string $name, UniqueConstraint $constraint) : string
2073
    {
2074 63737
        $columns = $constraint->getColumns();
2075 63737
2076 63737
        if (count($columns) === 0) {
2077 61680
            throw new InvalidArgumentException('Incomplete definition. "columns" required.');
2078
        }
2079 63737
2080 57315
        $chunks = ['CONSTRAINT'];
2081
2082
        if ($name !== '') {
2083
            $chunks[] = (new Identifier($name))->getQuotedName($this);
2084 63737
        }
2085 62149
2086
        $chunks[] = 'UNIQUE';
2087 63737
2088 61740
        if ($constraint->hasFlag('clustered')) {
2089
            $chunks[] = 'CLUSTERED';
2090
        }
2091 63737
2092
        $chunks[] = sprintf('(%s)', $this->getIndexFieldDeclarationListSQL($columns));
2093
2094
        return implode(' ', $chunks);
2095
    }
2096
2097 63737
    /**
2098
     * Obtains DBMS specific SQL code portion needed to set an index
2099 63737
     * declaration to be used in statements like CREATE TABLE.
2100 63737
     *
2101
     * @param string $name  The name of the index.
2102 63737
     * @param Index  $index The index definition.
2103 58680
     *
2104
     * @return string DBMS specific SQL code portion needed to set an index.
2105 63667
     *
2106
     * @throws InvalidArgumentException
2107
     */
2108 63737
    public function getIndexDeclarationSQL(string $name, Index $index) : string
2109 63737
    {
2110 61777
        $columns = $index->getColumns();
2111
        $name    = new Identifier($name);
2112
2113 63737
        if (count($columns) === 0) {
2114 57315
            throw new InvalidArgumentException('Incomplete definition. "columns" required.');
2115
        }
2116
2117
        return $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name->getQuotedName($this) . ' ('
2118 63737
            . $this->getIndexFieldDeclarationListSQL($index)
2119 61721
            . ')' . $this->getPartialIndexSQL($index);
2120
    }
2121
2122 63737
    /**
2123 61740
     * 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 63737
     *
2127 61920
     * @param mixed[] $columnDef
2128 61920
     */
2129 61920
    public function getCustomTypeDeclarationSQL(array $columnDef) : string
2130 61920
    {
2131
        return $columnDef['columnDefinition'];
2132
    }
2133
2134 63737
    /**
2135
     * Obtains DBMS specific SQL code portion needed to set an index
2136
     * declaration to be used in statements like CREATE TABLE.
2137
     *
2138
     * @param mixed[]|Index $columnsOrIndex array declaration is deprecated, prefer passing Index to this method
2139
     */
2140
    public function getIndexFieldDeclarationListSQL($columnsOrIndex) : string
2141
    {
2142
        if ($columnsOrIndex instanceof Index) {
2143
            return implode(', ', $columnsOrIndex->getQuotedColumns($this));
2144
        }
2145
2146 57588
        if (! is_array($columnsOrIndex)) {
2147
            throw new InvalidArgumentException('Fields argument should be an Index or array.');
2148
        }
2149 57588
2150 57588
        $ret = [];
2151
2152
        foreach ($columnsOrIndex as $column => $definition) {
2153
            if (is_array($definition)) {
2154
                $ret[] = $column;
2155
            } else {
2156
                $ret[] = $definition;
2157
            }
2158
        }
2159
2160
        return implode(', ', $ret);
2161
    }
2162
2163
    /**
2164
     * Returns the required SQL string that fits between CREATE ... TABLE
2165
     * to create the table as a temporary table.
2166
     *
2167
     * Should be overridden in driver classes to return the correct string for the
2168
     * specific database type.
2169
     *
2170
     * The default is to return the string "TEMPORARY" - this will result in a
2171
     * SQL error for any database that does not support temporary tables, or that
2172
     * requires a different SQL command from "CREATE TEMPORARY TABLE".
2173
     *
2174
     * @return string The string required to be placed between "CREATE" and "TABLE"
2175
     *                to generate a temporary table, if possible.
2176
     */
2177
    public function getTemporaryTableSQL() : string
2178
    {
2179
        return 'TEMPORARY';
2180
    }
2181
2182
    /**
2183
     * Some vendors require temporary table names to be qualified specially.
2184
     */
2185
    public function getTemporaryTableName(string $tableName) : string
2186
    {
2187
        return $tableName;
2188
    }
2189
2190
    /**
2191
     * Obtain DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
2192
     * of a field declaration to be used in statements like CREATE TABLE.
2193
     *
2194
     * @return string DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
2195 66055
     *                of a field declaration.
2196
     */
2197 66055
    public function getForeignKeyDeclarationSQL(ForeignKeyConstraint $foreignKey) : string
2198
    {
2199 66055
        $sql  = $this->getForeignKeyBaseDeclarationSQL($foreignKey);
2200 66055
        $sql .= $this->getAdvancedForeignKeyOptionsSQL($foreignKey);
2201
2202
        return $sql;
2203 66055
    }
2204
2205
    /**
2206
     * Returns the FOREIGN KEY query section dealing with non-standard options
2207
     * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
2208
     *
2209
     * @param ForeignKeyConstraint $foreignKey The foreign key definition.
2210
     */
2211
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey) : string
2212
    {
2213
        $query = '';
2214
        if ($this->supportsForeignKeyOnUpdate() && $foreignKey->hasOption('onUpdate')) {
2215
            $query .= ' ON UPDATE ' . $this->getForeignKeyReferentialActionSQL($foreignKey->getOption('onUpdate'));
2216
        }
2217
        if ($foreignKey->hasOption('onDelete')) {
2218
            $query .= ' ON DELETE ' . $this->getForeignKeyReferentialActionSQL($foreignKey->getOption('onDelete'));
2219
        }
2220
2221
        return $query;
2222
    }
2223
2224
    /**
2225
     * Returns the given referential action in uppercase if valid, otherwise throws an exception.
2226
     *
2227
     * @param string $action The foreign key referential action.
2228
     *
2229
     * @throws InvalidArgumentException If unknown referential action given.
2230
     */
2231
    public function getForeignKeyReferentialActionSQL(string $action) : string
2232
    {
2233
        $upper = strtoupper($action);
2234
        switch ($upper) {
2235
            case 'CASCADE':
2236
            case 'SET NULL':
2237
            case 'NO ACTION':
2238
            case 'RESTRICT':
2239 65510
            case 'SET DEFAULT':
2240
                return $upper;
2241 65510
            default:
2242 60227
                throw new InvalidArgumentException(sprintf('Invalid foreign key action "%s".', $upper));
2243
        }
2244 65482
    }
2245
2246 65482
    /**
2247 65482
     * Obtains DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
2248
     * of a field declaration to be used in statements like CREATE TABLE.
2249 65482
     *
2250 65482
     * @throws InvalidArgumentException
2251
     */
2252 65482
    public function getForeignKeyBaseDeclarationSQL(ForeignKeyConstraint $foreignKey) : string
2253
    {
2254 65482
        $sql = '';
2255 65482
        if ($foreignKey->getName() !== '') {
2256
            $sql .= 'CONSTRAINT ' . $foreignKey->getQuotedName($this) . ' ';
2257 65482
        }
2258 65482
        $sql .= 'FOREIGN KEY (';
2259
2260 65482
        if (count($foreignKey->getLocalColumns()) === 0) {
2261 65482
            throw new InvalidArgumentException('Incomplete definition. "local" required.');
2262
        }
2263 65482
        if (count($foreignKey->getForeignColumns()) === 0) {
2264 59560
            throw new InvalidArgumentException('Incomplete definition. "foreign" required.');
2265
        }
2266
        if (strlen($foreignKey->getForeignTableName()) === 0) {
2267
            throw new InvalidArgumentException('Incomplete definition. "foreignTable" required.');
2268 65510
        }
2269
2270
        return $sql . implode(', ', $foreignKey->getQuotedLocalColumns($this))
2271
            . ') REFERENCES '
2272
            . $foreignKey->getQuotedForeignTableName($this) . ' ('
2273
            . implode(', ', $foreignKey->getQuotedForeignColumns($this)) . ')';
2274
    }
2275
2276
    /**
2277
     * Obtains DBMS specific SQL code portion needed to set the UNIQUE constraint
2278 62686
     * of a field declaration to be used in statements like CREATE TABLE.
2279
     *
2280 62686
     * @return string DBMS specific SQL code portion needed to set the UNIQUE constraint
2281 62686
     *                of a field declaration.
2282 62686
     */
2283 62686
    public function getUniqueFieldDeclarationSQL() : string
2284
    {
2285 62686
        return 'UNIQUE';
2286
    }
2287
2288
    /**
2289
     * Obtains DBMS specific SQL code portion needed to set the CHARACTER SET
2290
     * of a field declaration to be used in statements like CREATE TABLE.
2291
     *
2292
     * @param string $charset The name of the charset.
2293
     *
2294
     * @return string DBMS specific SQL code portion needed to set the CHARACTER SET
2295
     *                of a field declaration.
2296 66272
     */
2297
    public function getColumnCharsetDeclarationSQL(string $charset) : string
2298 66272
    {
2299 65734
        return '';
2300
    }
2301
2302 63819
    /**
2303
     * Obtains DBMS specific SQL code portion needed to set the COLLATION
2304 63819
     * of a field declaration to be used in statements like CREATE TABLE.
2305 14549
     *
2306
     * @param string $collation The name of the collation.
2307
     *
2308 63795
     * @return string DBMS specific SQL code portion needed to set the COLLATION
2309
     *                of a field declaration.
2310 63795
     */
2311 63083
    public function getColumnCollationDeclarationSQL(string $collation) : string
2312
    {
2313
        return $this->supportsColumnCollation() ? 'COLLATE ' . $collation : '';
2314 63737
    }
2315 63533
2316
    /**
2317
     * Whether the platform prefers sequences for ID generation.
2318 63413
     * Subclasses should override this method to return TRUE if they prefer sequences.
2319 37883
     */
2320
    public function prefersSequences() : bool
2321
    {
2322 63413
        return false;
2323 61132
    }
2324
2325
    /**
2326 63134
     * Whether the platform prefers identity columns (eg. autoincrement) for ID generation.
2327 63028
     * Subclasses should override this method to return TRUE if they prefer identity columns.
2328
     */
2329
    public function prefersIdentityColumns() : bool
2330 63105
    {
2331
        return false;
2332
    }
2333
2334
    /**
2335
     * Some platforms need the boolean values to be converted.
2336
     *
2337
     * The default conversion in this implementation converts to integers (false => 0, true => 1).
2338
     *
2339
     * Note: if the input is not a boolean the original input might be returned.
2340
     *
2341 60639
     * There are two contexts when converting booleans: Literals and Prepared Statements.
2342
     * This method should handle the literal case
2343 60639
     *
2344 60639
     * @param mixed $item A boolean or an array of them.
2345 60639
     *
2346
     * @return mixed A boolean database value or an array of them.
2347
     */
2348 60639
    public function convertBooleans($item)
2349 59535
    {
2350
        if (is_array($item)) {
2351
            foreach ($item as $k => $value) {
2352 60639
                if (! is_bool($value)) {
2353 60051
                    continue;
2354
                }
2355
2356
                $item[$k] = (int) $value;
2357
            }
2358 60639
        } elseif (is_bool($item)) {
2359
            $item = (int) $item;
2360
        }
2361
2362
        return $item;
2363
    }
2364
2365
    /**
2366
     * Some platforms have boolean literals that needs to be correctly converted
2367
     *
2368
     * The default conversion tries to convert value into bool "(bool)$item"
2369
     *
2370
     * @param mixed $item
2371
     */
2372 58456
    public function convertFromBoolean($item) : ?bool
2373
    {
2374 58456
        if ($item === null) {
2375 58456
            return null;
2376
        }
2377 58456
2378
        return (bool) $item;
2379
    }
2380
2381 58456
    /**
2382 58456
     * This method should handle the prepared statements case. When there is no
2383 58456
     * distinction, it's OK to use the same method.
2384
     *
2385
     * Note: if the input is not a boolean the original input might be returned.
2386
     *
2387
     * @param mixed $item A boolean or an array of them.
2388
     *
2389
     * @return mixed A boolean database value or an array of them.
2390
     */
2391
    public function convertBooleansToDatabaseValue($item)
2392
    {
2393
        return $this->convertBooleans($item);
2394
    }
2395
2396
    /**
2397 61055
     * Returns the SQL specific for the platform to get the current date.
2398
     */
2399 61055
    public function getCurrentDateSQL() : string
2400 61055
    {
2401
        return 'CURRENT_DATE';
2402 61055
    }
2403
2404
    /**
2405
     * Returns the SQL specific for the platform to get the current time.
2406 61055
     */
2407 61055
    public function getCurrentTimeSQL() : string
2408 61055
    {
2409
        return 'CURRENT_TIME';
2410
    }
2411
2412
    /**
2413
     * Returns the SQL specific for the platform to get the current timestamp
2414
     */
2415
    public function getCurrentTimestampSQL() : string
2416
    {
2417
        return 'CURRENT_TIMESTAMP';
2418
    }
2419
2420 60235
    /**
2421
     * Returns the SQL for a given transaction isolation level Connection constant.
2422 60235
     *
2423
     * @throws InvalidArgumentException
2424
     */
2425
    protected function _getTransactionIsolationLevelSQL(int $level) : string
2426
    {
2427
        switch ($level) {
2428
            case TransactionIsolationLevel::READ_UNCOMMITTED:
2429
                return 'READ UNCOMMITTED';
2430
            case TransactionIsolationLevel::READ_COMMITTED:
2431 64560
                return 'READ COMMITTED';
2432
            case TransactionIsolationLevel::REPEATABLE_READ:
2433 64560
                return 'REPEATABLE READ';
2434 64472
            case TransactionIsolationLevel::SERIALIZABLE:
2435
                return 'SERIALIZABLE';
2436
            default:
2437 29100
                throw new InvalidArgumentException(sprintf('Invalid isolation level "%s".', $level));
2438
        }
2439
    }
2440
2441 29100
    /**
2442
     * @throws DBALException If not supported on this platform.
2443 29100
     */
2444 29100
    public function getListDatabasesSQL() : string
2445
    {
2446
        throw NotSupported::new(__METHOD__);
2447 29100
    }
2448
2449
    /**
2450
     * Returns the SQL statement for retrieving the namespaces defined in the database.
2451 29100
     *
2452
     * @throws DBALException If not supported on this platform.
2453
     */
2454
    public function getListNamespacesSQL() : string
2455
    {
2456
        throw NotSupported::new(__METHOD__);
2457
    }
2458
2459
    /**
2460
     * @throws DBALException If not supported on this platform.
2461
     */
2462
    public function getListSequencesSQL(string $database) : string
2463
    {
2464
        throw NotSupported::new(__METHOD__);
2465
    }
2466
2467
    /**
2468
     * @throws DBALException If not supported on this platform.
2469
     */
2470
    public function getListTableConstraintsSQL(string $table) : string
2471
    {
2472
        throw NotSupported::new(__METHOD__);
2473
    }
2474
2475
    /**
2476
     * @throws DBALException If not supported on this platform.
2477
     */
2478
    public function getListTableColumnsSQL(string $table, ?string $database = null) : string
2479
    {
2480 50828
        throw NotSupported::new(__METHOD__);
2481
    }
2482 50828
2483
    /**
2484
     * @throws DBALException If not supported on this platform.
2485
     */
2486
    public function getListTablesSQL() : string
2487
    {
2488
        throw NotSupported::new(__METHOD__);
2489
    }
2490
2491
    /**
2492 64204
     * @throws DBALException If not supported on this platform.
2493
     */
2494 64204
    public function getListUsersSQL() : string
2495 64180
    {
2496
        throw NotSupported::new(__METHOD__);
2497 64180
    }
2498
2499
    /**
2500
     * Returns the SQL to list all views of a database or user.
2501
     *
2502
     * @throws DBALException If not supported on this platform.
2503
     */
2504
    public function getListViewsSQL(string $database) : string
2505
    {
2506
        throw NotSupported::new(__METHOD__);
2507
    }
2508 64148
2509
    /**
2510 64148
     * Returns the list of indexes for the current database.
2511 64148
     *
2512 28558
     * The current database parameter is optional but will always be passed
2513
     * when using the SchemaManager API and is the database the given table is in.
2514 64148
     *
2515 61502
     * Attention: Some platforms only support currentDatabase when they
2516
     * are connected with that database. Cross-database information schema
2517
     * requests may be impossible.
2518 64148
     *
2519
     * @throws DBALException If not supported on this platform.
2520
     */
2521
    public function getListTableIndexesSQL(string $table, ?string $currentDatabase = null) : string
2522
    {
2523
        throw NotSupported::new(__METHOD__);
2524
    }
2525
2526
    /**
2527
     * @throws DBALException If not supported on this platform.
2528
     */
2529
    public function getListTableForeignKeysSQL(string $table, ?string $database = null) : string
2530 62285
    {
2531
        throw NotSupported::new(__METHOD__);
2532 62285
    }
2533 242
2534 62285
    /**
2535 60081
     * @throws DBALException If not supported on this platform.
2536 60021
     */
2537 59977
    public function getCreateViewSQL(string $name, string $sql) : string
2538 59931
    {
2539 62251
        throw NotSupported::new(__METHOD__);
2540
    }
2541 58734
2542
    /**
2543
     * @throws DBALException If not supported on this platform.
2544
     */
2545
    public function getDropViewSQL(string $name) : string
2546
    {
2547
        throw NotSupported::new(__METHOD__);
2548
    }
2549
2550
    /**
2551
     * Returns the SQL snippet to drop an existing sequence.
2552
     *
2553 64124
     * @param Sequence|string $sequence
2554
     *
2555 64124
     * @throws DBALException If not supported on this platform.
2556 64124
     */
2557 64011
    public function getDropSequenceSQL($sequence) : string
2558
    {
2559 64124
        throw NotSupported::new(__METHOD__);
2560
    }
2561 64124
2562
    /**
2563
     * @throws DBALException If not supported on this platform.
2564 64124
     */
2565
    public function getSequenceNextValSQL(string $sequenceName) : string
2566
    {
2567 64124
        throw NotSupported::new(__METHOD__);
2568
    }
2569
2570
    /**
2571 64124
     * Returns the SQL to create a new database.
2572 64124
     *
2573 64124
     * @param string $database The name of the database that should be created.
2574 64124
     *
2575
     * @throws DBALException If not supported on this platform.
2576
     */
2577
    public function getCreateDatabaseSQL(string $database) : string
2578
    {
2579
        throw NotSupported::new(__METHOD__);
2580
    }
2581
2582
    /**
2583
     * Returns the SQL to set the transaction isolation level.
2584
     *
2585
     * @throws DBALException If not supported on this platform.
2586
     */
2587
    public function getSetTransactionIsolationSQL(int $level) : string
2588
    {
2589
        throw NotSupported::new(__METHOD__);
2590
    }
2591
2592
    /**
2593
     * Obtains DBMS specific SQL to be used to create datetime fields in
2594
     * statements like CREATE TABLE.
2595
     *
2596
     * @param mixed[] $fieldDeclaration
2597
     *
2598
     * @throws DBALException If not supported on this platform.
2599
     */
2600
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration) : string
2601
    {
2602
        throw NotSupported::new(__METHOD__);
2603
    }
2604
2605
    /**
2606
     * Obtains DBMS specific SQL to be used to create datetime with timezone offset fields.
2607
     *
2608
     * @param mixed[] $fieldDeclaration
2609
     */
2610
    public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration) : string
2611
    {
2612 19800
        return $this->getDateTimeTypeDeclarationSQL($fieldDeclaration);
2613
    }
2614 19800
2615
    /**
2616
     * Obtains DBMS specific SQL to be used to create date fields in statements
2617
     * like CREATE TABLE.
2618
     *
2619
     * @param mixed[] $fieldDeclaration
2620
     *
2621
     * @throws DBALException If not supported on this platform.
2622
     */
2623 10
    public function getDateTypeDeclarationSQL(array $fieldDeclaration) : string
0 ignored issues
show
Unused Code introduced by
The parameter $fieldDeclaration is not used and could be removed.

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

Loading history...
2624
    {
2625 10
        throw NotSupported::new(__METHOD__);
2626
    }
2627
2628
    /**
2629
     * Obtains DBMS specific SQL to be used to create time fields in statements
2630
     * like CREATE TABLE.
2631
     *
2632
     * @param mixed[] $fieldDeclaration
2633
     *
2634 51093
     * @throws DBALException If not supported on this platform.
2635
     */
2636 51093
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration) : string
0 ignored issues
show
Unused Code introduced by
The parameter $fieldDeclaration is not used and could be removed.

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

Loading history...
2637
    {
2638
        throw NotSupported::new(__METHOD__);
2639
    }
2640
2641
    /**
2642
     * @param mixed[] $fieldDeclaration
2643
     */
2644
    public function getFloatDeclarationSQL(array $fieldDeclaration) : string
2645
    {
2646
        return 'DOUBLE PRECISION';
2647
    }
2648
2649
    /**
2650
     * Gets the default transaction isolation level of the platform.
2651
     *
2652
     * @see TransactionIsolationLevel
2653 61318
     *
2654
     * @return int The default isolation level.
2655 61318
     */
2656
    public function getDefaultTransactionIsolationLevel() : int
2657
    {
2658
        return TransactionIsolationLevel::READ_COMMITTED;
2659
    }
2660
2661
    /* supports*() methods */
2662
2663 61318
    /**
2664 61316
     * Whether the platform supports sequences.
2665
     */
2666
    public function supportsSequences() : bool
2667 61318
    {
2668
        return false;
2669
    }
2670
2671
    /**
2672
     * Whether the platform supports identity columns.
2673
     *
2674
     * Identity columns are columns that receive an auto-generated value from the
2675
     * database on insert of a row.
2676
     */
2677
    public function supportsIdentityColumns() : bool
2678
    {
2679 60518
        return false;
2680
    }
2681 60518
2682
    /**
2683
     * Whether the platform emulates identity columns through sequences.
2684
     *
2685
     * Some platforms that do not support identity columns natively
2686
     * but support sequences can emulate identity columns by using
2687
     * sequences.
2688
     */
2689
    public function usesSequenceEmulatedIdentityColumns() : bool
2690
    {
2691
        return false;
2692
    }
2693
2694 55895
    /**
2695
     * Gets the sequence name prefix based on table information.
2696 55895
     */
2697
    public function getSequencePrefix(string $tableName, ?string $schemaName = null) : string
2698
    {
2699
        if (! $schemaName) {
2700
            return $tableName;
2701
        }
2702
2703
        // Prepend the schema name to the table name if there is one
2704 61887
        return ! $this->supportsSchemas() && $this->canEmulateSchemas()
2705
            ? $schemaName . '__' . $tableName
2706 61887
            : $schemaName . '.' . $tableName;
2707
    }
2708
2709
    /**
2710
     * Returns the name of the sequence for a particular identity column in a particular table.
2711
     *
2712
     * @see    usesSequenceEmulatedIdentityColumns
2713
     *
2714 30317
     * @param string $tableName  The name of the table to return the sequence name for.
2715
     * @param string $columnName The name of the identity column in the table to return the sequence name for.
2716 30317
     *
2717
     * @throws DBALException If not supported on this platform.
2718
     */
2719
    public function getIdentitySequenceName(string $tableName, string $columnName) : string
2720
    {
2721
        throw NotSupported::new(__METHOD__);
2722
    }
2723
2724 63221
    /**
2725
     * Whether the platform supports indexes.
2726 63221
     */
2727
    public function supportsIndexes() : bool
2728
    {
2729
        return true;
2730
    }
2731
2732
    /**
2733
     * Whether the platform supports partial indexes.
2734
     */
2735
    public function supportsPartialIndexes() : bool
2736
    {
2737
        return false;
2738 56922
    }
2739
2740 22
    /**
2741 56900
     * Whether the platform supports indexes with column length definitions.
2742 56922
     */
2743 56900
    public function supportsColumnLengthIndexes() : bool
2744 56922
    {
2745 56900
        return false;
2746 56922
    }
2747 56900
2748 56922
    /**
2749
     * Whether the platform supports altering tables.
2750
     */
2751
    public function supportsAlterTable() : bool
2752
    {
2753
        return true;
2754
    }
2755
2756
    /**
2757
     * Whether the platform supports transactions.
2758
     */
2759 2492
    public function supportsTransactions() : bool
2760
    {
2761 2492
        return true;
2762
    }
2763
2764
    /**
2765
     * Whether the platform supports savepoints.
2766
     */
2767
    public function supportsSavepoints() : bool
2768
    {
2769
        return true;
2770
    }
2771
2772
    /**
2773
     * Whether the platform supports releasing savepoints.
2774
     */
2775
    public function supportsReleaseSavepoints() : bool
2776
    {
2777
        return $this->supportsSavepoints();
2778
    }
2779
2780
    /**
2781
     * Whether the platform supports primary key constraints.
2782
     */
2783
    public function supportsPrimaryConstraints() : bool
2784
    {
2785
        return true;
2786
    }
2787
2788
    /**
2789
     * Whether the platform supports foreign key constraints.
2790
     */
2791
    public function supportsForeignKeyConstraints() : bool
2792
    {
2793
        return true;
2794
    }
2795
2796
    /**
2797
     * Whether this platform supports onUpdate in foreign key constraints.
2798
     */
2799
    public function supportsForeignKeyOnUpdate() : bool
2800
    {
2801
        return $this->supportsForeignKeyConstraints();
2802
    }
2803
2804
    /**
2805
     * Whether the platform supports database schemas.
2806
     */
2807
    public function supportsSchemas() : bool
2808
    {
2809
        return false;
2810
    }
2811
2812
    /**
2813
     * Whether this platform can emulate schemas.
2814
     *
2815
     * Platforms that either support or emulate schemas don't automatically
2816
     * filter a schema for the namespaced elements in {@link
2817
     * AbstractManager#createSchema}.
2818
     */
2819
    public function canEmulateSchemas() : bool
2820
    {
2821
        return false;
2822
    }
2823
2824
    /**
2825
     * Returns the default schema name.
2826
     *
2827
     * @throws DBALException If not supported on this platform.
2828
     */
2829
    public function getDefaultSchemaName() : string
2830
    {
2831
        throw NotSupported::new(__METHOD__);
2832
    }
2833
2834
    /**
2835
     * Whether this platform supports create database.
2836
     *
2837
     * Some databases don't allow to create and drop databases at all or only with certain tools.
2838
     */
2839
    public function supportsCreateDropDatabase() : bool
2840
    {
2841
        return true;
2842
    }
2843
2844
    /**
2845
     * Whether the platform supports getting the affected rows of a recent update/delete type query.
2846
     */
2847
    public function supportsGettingAffectedRows() : bool
2848
    {
2849
        return true;
2850
    }
2851
2852
    /**
2853
     * Whether this platform support to add inline column comments as postfix.
2854
     */
2855
    public function supportsInlineColumnComments() : bool
2856
    {
2857
        return false;
2858
    }
2859
2860
    /**
2861
     * Whether this platform support the proprietary syntax "COMMENT ON asset".
2862
     */
2863
    public function supportsCommentOnStatement() : bool
2864
    {
2865
        return false;
2866
    }
2867
2868
    /**
2869
     * Does this platform have native guid type.
2870
     */
2871
    public function hasNativeGuidType() : bool
2872
    {
2873
        return false;
2874
    }
2875
2876
    /**
2877
     * Does this platform have native JSON type.
2878
     */
2879
    public function hasNativeJsonType() : bool
2880
    {
2881
        return false;
2882
    }
2883
2884
    /**
2885
     * Whether this platform supports views.
2886
     */
2887
    public function supportsViews() : bool
2888
    {
2889
        return true;
2890
    }
2891
2892
    /**
2893
     * Does this platform support column collation?
2894
     */
2895
    public function supportsColumnCollation() : bool
2896
    {
2897
        return false;
2898
    }
2899
2900
    /**
2901
     * Gets the format string, as accepted by the date() function, that describes
2902
     * the format of a stored datetime value of this platform.
2903
     *
2904
     * @return string The format string.
2905
     */
2906
    public function getDateTimeFormatString() : string
2907
    {
2908
        return 'Y-m-d H:i:s';
2909
    }
2910
2911
    /**
2912
     * Gets the format string, as accepted by the date() function, that describes
2913
     * the format of a stored datetime with timezone value of this platform.
2914
     *
2915
     * @return string The format string.
2916
     */
2917
    public function getDateTimeTzFormatString() : string
2918
    {
2919
        return 'Y-m-d H:i:s';
2920
    }
2921
2922
    /**
2923
     * Gets the format string, as accepted by the date() function, that describes
2924
     * the format of a stored date value of this platform.
2925
     *
2926
     * @return string The format string.
2927
     */
2928
    public function getDateFormatString() : string
2929
    {
2930
        return 'Y-m-d';
2931
    }
2932
2933
    /**
2934
     * Gets the format string, as accepted by the date() function, that describes
2935
     * the format of a stored time value of this platform.
2936
     *
2937
     * @return string The format string.
2938
     */
2939
    public function getTimeFormatString() : string
2940
    {
2941 47827
        return 'H:i:s';
2942
    }
2943 47827
2944
    /**
2945
     * Adds an driver-specific LIMIT clause to the query.
2946
     *
2947
     * @throws DBALException
2948
     */
2949
    final public function modifyLimitQuery(string $query, ?int $limit, int $offset = 0) : string
2950
    {
2951
        if ($offset < 0) {
2952
            throw new DBALException(sprintf(
2953
                'Offset must be a positive integer or zero, %d given.',
2954
                $offset
2955
            ));
2956
        }
2957
2958
        if ($offset > 0 && ! $this->supportsLimitOffset()) {
2959
            throw new DBALException(sprintf(
2960
                'Platform "%s" does not support offset values in limit queries.',
2961
                $this->getName()
2962
            ));
2963
        }
2964
2965
        return $this->doModifyLimitQuery($query, $limit, $offset);
2966
    }
2967
2968
    /**
2969
     * Adds an platform-specific LIMIT clause to the query.
2970
     */
2971
    protected function doModifyLimitQuery(string $query, ?int $limit, int $offset) : string
2972
    {
2973
        if ($limit !== null) {
2974
            $query .= sprintf(' LIMIT %d', $limit);
2975
        }
2976
2977
        if ($offset > 0) {
2978
            $query .= sprintf(' OFFSET %d', $offset);
2979
        }
2980
2981
        return $query;
2982 38668
    }
2983
2984 38668
    /**
2985
     * Whether the database platform support offsets in modify limit clauses.
2986
     */
2987
    public function supportsLimitOffset() : bool
2988
    {
2989
        return true;
2990
    }
2991
2992
    /**
2993
     * Gets the character casing of a column in an SQL result set of this platform.
2994
     *
2995
     * @param string $column The column name for which to get the correct character casing.
2996
     *
2997
     * @return string The column name in the character casing used in SQL result sets.
2998
     */
2999
    public function getSQLResultCasing(string $column) : string
3000
    {
3001
        return $column;
3002
    }
3003
3004
    /**
3005
     * Makes any fixes to a name of a schema element (table, sequence, ...) that are required
3006
     * by restrictions of the platform, like a maximum length.
3007
     */
3008
    public function fixSchemaElementName(string $schemaElementName) : string
3009
    {
3010
        return $schemaElementName;
3011
    }
3012
3013
    /**
3014
     * Maximum length of any given database identifier, like tables or column names.
3015
     */
3016
    public function getMaxIdentifierLength() : int
3017
    {
3018
        return 63;
3019
    }
3020
3021
    /**
3022 59372
     * Returns the insert SQL for an empty insert statement.
3023
     */
3024 59372
    public function getEmptyIdentityInsertSQL(string $tableName, string $identifierColumnName) : string
3025
    {
3026
        return 'INSERT INTO ' . $tableName . ' (' . $identifierColumnName . ') VALUES (null)';
3027
    }
3028
3029
    /**
3030
     * Generates a Truncate Table SQL statement for a given table.
3031
     *
3032
     * Cascade is not supported on many platforms but would optionally cascade the truncate by
3033
     * following the foreign keys.
3034
     */
3035
    public function getTruncateTableSQL(string $tableName, bool $cascade = false) : string
3036
    {
3037
        $tableIdentifier = new Identifier($tableName);
3038
3039
        return 'TRUNCATE ' . $tableIdentifier->getQuotedName($this);
3040
    }
3041
3042
    /**
3043
     * This is for test reasons, many vendors have special requirements for dummy statements.
3044
     */
3045
    public function getDummySelectSQL(string $expression = '1') : string
3046 41407
    {
3047
        return sprintf('SELECT %s', $expression);
3048 41407
    }
3049
3050
    /**
3051
     * Returns the SQL to create a new savepoint.
3052
     */
3053
    public function createSavePoint(string $savepoint) : string
3054
    {
3055
        return 'SAVEPOINT ' . $savepoint;
3056
    }
3057
3058
    /**
3059 4
     * Returns the SQL to release a savepoint.
3060
     */
3061 4
    public function releaseSavePoint(string $savepoint) : string
3062
    {
3063
        return 'RELEASE SAVEPOINT ' . $savepoint;
3064
    }
3065
3066
    /**
3067
     * Returns the SQL to rollback a savepoint.
3068
     */
3069
    public function rollbackSavePoint(string $savepoint) : string
3070
    {
3071
        return 'ROLLBACK TO SAVEPOINT ' . $savepoint;
3072
    }
3073 59146
3074
    /**
3075 59146
     * Returns the keyword list instance of this platform.
3076
     *
3077
     * @throws DBALException If no keyword list is specified.
3078
     */
3079
    final public function getReservedKeywordsList() : KeywordList
3080
    {
3081
        // Check for an existing instantiation of the keywords class.
3082
        if ($this->_keywords) {
3083
            return $this->_keywords;
3084
        }
3085
3086
        $class    = $this->getReservedKeywordsClass();
3087
        $keywords = new $class();
3088
        if (! $keywords instanceof KeywordList) {
3089
            throw NotSupported::new(__METHOD__);
3090 57699
        }
3091
3092 57699
        // Store the instance so it doesn't need to be generated on every request.
3093
        $this->_keywords = $keywords;
3094
3095
        return $keywords;
3096
    }
3097
3098
    /**
3099
     * Returns the class name of the reserved keywords list.
3100 8
     *
3101
     * @throws DBALException If not supported on this platform.
3102 8
     */
3103
    protected function getReservedKeywordsClass() : string
3104
    {
3105
        throw NotSupported::new(__METHOD__);
3106
    }
3107
3108
    /**
3109
     * Quotes a literal string.
3110 63017
     * This method is NOT meant to fix SQL injections!
3111
     * It is only meant to escape this platform's string literal
3112 63017
     * quote character inside the given literal string.
3113
     *
3114
     * @param string $str The literal string to be quoted.
3115
     *
3116
     * @return string The quoted literal string.
3117
     */
3118 62634
    public function quoteStringLiteral(string $str) : string
3119
    {
3120 62634
        $c = $this->getStringLiteralQuoteCharacter();
3121
3122
        return $c . str_replace($c, $c . $c, $str) . $c;
3123
    }
3124
3125
    /**
3126
     * Gets the character used for string literal quoting.
3127
     */
3128 61919
    public function getStringLiteralQuoteCharacter() : string
3129
    {
3130 61919
        return "'";
3131
    }
3132
3133
    /**
3134
     * Escapes metacharacters in a string intended to be used with a LIKE
3135
     * operator.
3136
     *
3137
     * @param string $inputString a literal, unquoted string
3138 8
     * @param string $escapeChar  should be reused by the caller in the LIKE
3139
     *                            expression.
3140 8
     */
3141
    final public function escapeStringForLike(string $inputString, string $escapeChar) : string
3142
    {
3143
        return preg_replace(
3144
            '~([' . preg_quote($this->getLikeWildcardCharacters() . $escapeChar, '~') . '])~u',
3145
            addcslashes($escapeChar, '\\') . '$1',
3146
            $inputString
3147
        );
3148 63665
    }
3149
3150 63665
    protected function getLikeWildcardCharacters() : string
3151
    {
3152
        return '%_';
3153
    }
3154
}
3155