Failed Conditions
Pull Request — develop (#3348)
by Sergei
67:43 queued 02:19
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
     * @throws InvalidArgumentException
669
     */
670
    public function getTrimExpression(string $str, int $mode = TrimMode::UNSPECIFIED, ?string $char = null) : string
671
    {
672
        $tokens = [];
673
674
        switch ($mode) {
675
            case TrimMode::UNSPECIFIED:
676
                break;
677
678
            case TrimMode::LEADING:
679
                $tokens[] = 'LEADING';
680
                break;
681
682
            case TrimMode::TRAILING:
683
                $tokens[] = 'TRAILING';
684
                break;
685
686
            case TrimMode::BOTH:
687
                $tokens[] = 'BOTH';
688
                break;
689
690
            default:
691
                throw new InvalidArgumentException(
692
                    sprintf(
693
                        'The value of $mode is expected to be one of the TrimMode constants, %d given',
694
                        $mode
695
                    )
696
                );
697
        }
698
699
        if ($char !== null) {
700
            $tokens[] = $char;
701
        }
702
703
        if (count($tokens) > 0) {
704
            $tokens[] = 'FROM';
705
        }
706
707
        $tokens[] = $str;
708
709
        return sprintf('TRIM(%s)', implode(' ', $tokens));
710
    }
711
712
    /**
713
     * Returns the SQL snippet to trim trailing space characters from the expression.
714
     *
715
     * @param string $expression Literal string or column name.
716
     */
717
    public function getRtrimExpression(string $expression) : string
718
    {
719
        return 'RTRIM(' . $expression . ')';
720
    }
721
722
    /**
723
     * Returns the SQL snippet to trim leading space characters from the expression.
724
     *
725
     * @param string $expression Literal string or column name.
726
     */
727
    public function getLtrimExpression(string $expression) : string
728
    {
729
        return 'LTRIM(' . $expression . ')';
730
    }
731
732
    /**
733
     * Returns the SQL snippet to change all characters from the expression to uppercase,
734
     * according to the current character set mapping.
735
     *
736
     * @param string $expression Literal string or column name.
737
     */
738
    public function getUpperExpression(string $expression) : string
739
    {
740
        return 'UPPER(' . $expression . ')';
741
    }
742
743
    /**
744
     * Returns the SQL snippet to change all characters from the expression to lowercase,
745
     * according to the current character set mapping.
746
     *
747
     * @param string $expression Literal string or column name.
748
     */
749
    public function getLowerExpression(string $expression) : string
750
    {
751
        return 'LOWER(' . $expression . ')';
752
    }
753
754
    /**
755
     * Returns the SQL snippet to get the position of the first occurrence of substring $substr in string $str.
756
     *
757
     * @param string $str      Literal string.
758
     * @param string $substr   Literal string to find.
759
     * @param int    $startPos Position to start at, beginning of string by default.
760 44305
     */
761
    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

761
    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

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

905
    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

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

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

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

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

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

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

1468
    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...
1469
    {
1470
        throw DBALException::notSupported(__METHOD__);
1471
    }
1472
1473
    /**
1474
     * Returns the SQL to change a sequence on this platform.
1475 46041
     *
1476
     * @throws DBALException If not supported on this platform.
1477 46041
     */
1478 43250
    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

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

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

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

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

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

2553
    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...
2554
    {
2555
        throw DBALException::notSupported(__METHOD__);
2556
    }
2557
2558
    /**
2559
     * @throws DBALException If not supported on this platform.
2560
     */
2561
    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

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

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