Failed Conditions
Pull Request — develop (#3348)
by Sergei
65:06
created

AbstractPlatform::convertNonNativeInterval()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

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

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

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

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

Loading history...
300 47064
    {
301
        throw DBALException::notSupported('VARCHARs not supported by Platform.');
302
    }
303
304
    /**
305
     * Returns the SQL snippet used to declare a BINARY/VARBINARY column type.
306
     *
307
     * @param int|null $length The length of the column.
308
     * @param bool     $fixed  Whether the column length is fixed.
309
     *
310
     * @throws DBALException If not supported on this platform.
311
     */
312
    protected function getBinaryTypeDeclarationSQLSnippet(?int $length, bool $fixed) : string
0 ignored issues
show
Unused Code introduced by
The parameter $fixed is not used and could be removed. ( Ignorable by Annotation )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
1454 43354
    {
1455
        throw DBALException::notSupported(__METHOD__);
1456
    }
1457 44490
1458 44490
    /**
1459
     * Returns the SQL to change a sequence on this platform.
1460
     *
1461 44490
     * @throws DBALException If not supported on this platform.
1462 44490
     */
1463
    public function getAlterSequenceSQL(Sequence $sequence) : string
0 ignored issues
show
Unused Code introduced by
The parameter $sequence is not used and could be removed. ( Ignorable by Annotation )

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
2503 2088
    {
2504 1943
        throw DBALException::notSupported(__METHOD__);
2505 1930
    }
2506 1919
2507 1909
    /**
2508 47975
     * @throws DBALException If not supported on this platform.
2509
     */
2510 44768
    public function getListTableForeignKeysSQL(string $table, ?string $database = null) : string
2511
    {
2512
        throw DBALException::notSupported(__METHOD__);
2513
    }
2514
2515
    /**
2516
     * @throws DBALException If not supported on this platform.
2517
     */
2518
    public function getCreateViewSQL(string $name, string $sql) : string
2519
    {
2520
        throw DBALException::notSupported(__METHOD__);
2521
    }
2522 49597
2523
    /**
2524 49597
     * @throws DBALException If not supported on this platform.
2525 49597
     */
2526 49502
    public function getDropViewSQL(string $name) : string
2527
    {
2528 49597
        throw DBALException::notSupported(__METHOD__);
2529
    }
2530 49597
2531
    /**
2532
     * Returns the SQL snippet to drop an existing sequence.
2533 49597
     *
2534
     * @param Sequence|string $sequence
2535
     *
2536 49597
     * @throws DBALException If not supported on this platform.
2537
     */
2538
    public function getDropSequenceSQL($sequence) : string
0 ignored issues
show
Unused Code introduced by
The parameter $sequence is not used and could be removed. ( Ignorable by Annotation )

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

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

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

Loading history...
2539
    {
2540 49597
        throw DBALException::notSupported(__METHOD__);
2541 49597
    }
2542 49597
2543 49597
    /**
2544
     * @throws DBALException If not supported on this platform.
2545
     */
2546
    public function getSequenceNextValSQL(string $sequenceName) : string
0 ignored issues
show
Unused Code introduced by
The parameter $sequenceName is not used and could be removed. ( Ignorable by Annotation )

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

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

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

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

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

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

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

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