Failed Conditions
Pull Request — 3.0.x (#3980)
by Guilherme
07:55
created

AbstractPlatform::getSequencePrefix()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 5
nc 5
nop 2
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 4
rs 10
c 0
b 0
f 0
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 func_get_arg;
41
use function func_get_args;
42
use function func_num_args;
43
use function implode;
44
use function in_array;
45
use function is_array;
46
use function is_bool;
47
use function is_int;
48
use function is_string;
49
use function preg_quote;
50
use function preg_replace;
51
use function sprintf;
52
use function str_replace;
53
use function strlen;
54
use function strpos;
55
use function strtolower;
56
use function strtoupper;
57
use function trigger_error;
58
use const E_USER_DEPRECATED;
59
60
/**
61
 * Base class for all DatabasePlatforms. The DatabasePlatforms are the central
62
 * point of abstraction of platform-specific behaviors, features and SQL dialects.
63
 * They are a passive source of information.
64
 *
65
 * @todo Remove any unnecessary methods.
66
 */
67
abstract class AbstractPlatform
68
{
69
    public const CREATE_INDEXES = 1;
70
71
    public const CREATE_FOREIGNKEYS = 2;
72
73
    /**
74
     * @deprecated Use DateIntervalUnit::INTERVAL_UNIT_SECOND.
75
     */
76
    public const DATE_INTERVAL_UNIT_SECOND = DateIntervalUnit::SECOND;
77
78
    /**
79
     * @deprecated Use DateIntervalUnit::MINUTE.
80
     */
81
    public const DATE_INTERVAL_UNIT_MINUTE = DateIntervalUnit::MINUTE;
82
83
    /**
84
     * @deprecated Use DateIntervalUnit::HOUR.
85
     */
86
    public const DATE_INTERVAL_UNIT_HOUR = DateIntervalUnit::HOUR;
87
88
    /**
89
     * @deprecated Use DateIntervalUnit::DAY.
90
     */
91
    public const DATE_INTERVAL_UNIT_DAY = DateIntervalUnit::DAY;
92
93
    /**
94
     * @deprecated Use DateIntervalUnit::WEEK.
95
     */
96
    public const DATE_INTERVAL_UNIT_WEEK = DateIntervalUnit::WEEK;
97
98
    /**
99
     * @deprecated Use DateIntervalUnit::MONTH.
100
     */
101
    public const DATE_INTERVAL_UNIT_MONTH = DateIntervalUnit::MONTH;
102
103
    /**
104
     * @deprecated Use DateIntervalUnit::QUARTER.
105
     */
106
    public const DATE_INTERVAL_UNIT_QUARTER = DateIntervalUnit::QUARTER;
107
108
    /**
109
     * @deprecated Use DateIntervalUnit::QUARTER.
110
     */
111
    public const DATE_INTERVAL_UNIT_YEAR = DateIntervalUnit::YEAR;
112
113
    /**
114
     * @deprecated Use TrimMode::UNSPECIFIED.
115
     */
116
    public const TRIM_UNSPECIFIED = TrimMode::UNSPECIFIED;
117
118
    /**
119
     * @deprecated Use TrimMode::LEADING.
120
     */
121
    public const TRIM_LEADING = TrimMode::LEADING;
122
123
    /**
124
     * @deprecated Use TrimMode::TRAILING.
125
     */
126
    public const TRIM_TRAILING = TrimMode::TRAILING;
127
128
    /**
129
     * @deprecated Use TrimMode::BOTH.
130
     */
131
    public const TRIM_BOTH = TrimMode::BOTH;
132
133
    /** @var string[]|null */
134
    protected $doctrineTypeMapping = null;
135
136
    /**
137
     * Contains a list of all columns that should generate parseable column comments for type-detection
138
     * in reverse engineering scenarios.
139
     *
140
     * @var string[]|null
141
     */
142
    protected $doctrineTypeComments = null;
143
144
    /** @var EventManager|null */
145
    protected $_eventManager;
146
147
    /**
148
     * Holds the KeywordList instance for the current platform.
149
     *
150
     * @var KeywordList|null
151
     */
152
    protected $_keywords;
153
154 42762
    public function __construct()
155
    {
156 42762
    }
157
158
    /**
159
     * Sets the EventManager used by the Platform.
160
     *
161
     * @return void
162
     */
163 1270
    public function setEventManager(EventManager $eventManager)
164
    {
165 1270
        $this->_eventManager = $eventManager;
166 1270
    }
167
168
    /**
169
     * Gets the EventManager used by the Platform.
170
     *
171
     * @return EventManager|null
172
     */
173 1727
    public function getEventManager()
174
    {
175 1727
        return $this->_eventManager;
176
    }
177
178
    /**
179
     * Returns the SQL snippet that declares a boolean column.
180
     *
181
     * @param mixed[] $columnDef
182
     *
183
     * @return string
184
     */
185
    abstract public function getBooleanTypeDeclarationSQL(array $columnDef);
186
187
    /**
188
     * Returns the SQL snippet that declares a 4 byte integer column.
189
     *
190
     * @param mixed[] $columnDef
191
     *
192
     * @return string
193
     */
194
    abstract public function getIntegerTypeDeclarationSQL(array $columnDef);
195
196
    /**
197
     * Returns the SQL snippet that declares an 8 byte integer column.
198
     *
199
     * @param mixed[] $columnDef
200
     *
201
     * @return string
202
     */
203
    abstract public function getBigIntTypeDeclarationSQL(array $columnDef);
204
205
    /**
206
     * Returns the SQL snippet that declares a 2 byte integer column.
207
     *
208
     * @param mixed[] $columnDef
209
     *
210
     * @return string
211
     */
212
    abstract public function getSmallIntTypeDeclarationSQL(array $columnDef);
213
214
    /**
215
     * Returns the SQL snippet that declares common properties of an integer column.
216
     *
217
     * @param mixed[] $columnDef
218
     *
219
     * @return string
220
     */
221
    abstract protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef);
222
223
    /**
224
     * Lazy load Doctrine Type Mappings.
225
     *
226
     * @return void
227
     */
228
    abstract protected function initializeDoctrineTypeMappings();
229
230
    /**
231
     * Initializes Doctrine Type Mappings with the platform defaults
232
     * and with all additional type mappings.
233
     *
234
     * @return void
235
     */
236 1266
    private function initializeAllDoctrineTypeMappings()
237
    {
238 1266
        $this->initializeDoctrineTypeMappings();
239
240 1266
        foreach (Type::getTypesMap() as $typeName => $className) {
241 1266
            foreach (Type::getType($typeName)->getMappedDatabaseTypes($this) as $dbType) {
242 684
                $this->doctrineTypeMapping[$dbType] = $typeName;
243
            }
244
        }
245 1266
    }
246
247
    /**
248
     * Returns the SQL snippet used to declare a VARCHAR column type.
249
     *
250
     * @param mixed[] $field
251
     *
252
     * @return string
253
     */
254 5140
    public function getVarcharTypeDeclarationSQL(array $field)
255
    {
256 5140
        if (! isset($field['length'])) {
257 983
            $field['length'] = $this->getVarcharDefaultLength();
258
        }
259
260 5140
        $fixed = $field['fixed'] ?? false;
261
262 5140
        $maxLength = $fixed
263 760
            ? $this->getCharMaxLength()
264 5140
            : $this->getVarcharMaxLength();
265
266 5140
        if ($field['length'] > $maxLength) {
267
            return $this->getClobTypeDeclarationSQL($field);
268
        }
269
270 5140
        return $this->getVarcharTypeDeclarationSQLSnippet($field['length'], $fixed);
271
    }
272
273
    /**
274
     * Returns the SQL snippet used to declare a BINARY/VARBINARY column type.
275
     *
276
     * @param mixed[] $field The column definition.
277
     *
278
     * @return string
279
     */
280 418
    public function getBinaryTypeDeclarationSQL(array $field)
281
    {
282 418
        if (! isset($field['length'])) {
283 242
            $field['length'] = $this->getBinaryDefaultLength();
284
        }
285
286 418
        $fixed = $field['fixed'] ?? false;
287
288 418
        $maxLength = $this->getBinaryMaxLength();
289
290 418
        if ($field['length'] > $maxLength) {
291 227
            if ($maxLength > 0) {
292 154
                @trigger_error(sprintf(
293 14
                    'Binary field length %d is greater than supported by the platform (%d). Reduce the field length or use a BLOB field instead.',
294 154
                    $field['length'],
295 154
                    $maxLength
296 154
                ), E_USER_DEPRECATED);
297
            }
298
299 227
            return $this->getBlobTypeDeclarationSQL($field);
300
        }
301
302 257
        return $this->getBinaryTypeDeclarationSQLSnippet($field['length'], $fixed);
303
    }
304
305
    /**
306
     * Returns the SQL snippet to declare a GUID/UUID field.
307
     *
308
     * By default this maps directly to a CHAR(36) and only maps to more
309
     * special datatypes when the underlying databases support this datatype.
310
     *
311
     * @param mixed[] $field
312
     *
313
     * @return string
314
     */
315 144
    public function getGuidTypeDeclarationSQL(array $field)
316
    {
317 144
        $field['length'] = 36;
318 144
        $field['fixed']  = true;
319
320 144
        return $this->getVarcharTypeDeclarationSQL($field);
321
    }
322
323
    /**
324
     * Returns the SQL snippet to declare a JSON field.
325
     *
326
     * By default this maps directly to a CLOB and only maps to more
327
     * special datatypes when the underlying databases support this datatype.
328
     *
329
     * @param mixed[] $field
330
     *
331
     * @return string
332
     */
333 289
    public function getJsonTypeDeclarationSQL(array $field)
334
    {
335 289
        return $this->getClobTypeDeclarationSQL($field);
336
    }
337
338
    /**
339
     * @param int|false $length
340
     * @param bool      $fixed
341
     *
342
     * @return string
343
     *
344
     * @throws DBALException If not supported on this platform.
345
     */
346
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
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

346
    protected function getVarcharTypeDeclarationSQLSnippet($length, /** @scrutinizer ignore-unused */ $fixed)

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...
347
    {
348
        throw DBALException::notSupported('VARCHARs not supported by Platform.');
349
    }
350
351
    /**
352
     * Returns the SQL snippet used to declare a BINARY/VARBINARY column type.
353
     *
354
     * @param int|false $length The length of the column.
355
     * @param bool      $fixed  Whether the column length is fixed.
356
     *
357
     * @return string
358
     *
359
     * @throws DBALException If not supported on this platform.
360
     */
361
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
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

361
    protected function getBinaryTypeDeclarationSQLSnippet($length, /** @scrutinizer ignore-unused */ $fixed)

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...
362
    {
363
        throw DBALException::notSupported('BINARY/VARBINARY column types are not supported by this platform.');
364
    }
365
366
    /**
367
     * Returns the SQL snippet used to declare a CLOB column type.
368
     *
369
     * @param mixed[] $field
370
     *
371
     * @return string
372
     */
373
    abstract public function getClobTypeDeclarationSQL(array $field);
374
375
    /**
376
     * Returns the SQL Snippet used to declare a BLOB column type.
377
     *
378
     * @param mixed[] $field
379
     *
380
     * @return string
381
     */
382
    abstract public function getBlobTypeDeclarationSQL(array $field);
383
384
    /**
385
     * Gets the name of the platform.
386
     *
387
     * @return string
388
     */
389
    abstract public function getName();
390
391
    /**
392
     * Registers a doctrine type to be used in conjunction with a column type of this platform.
393
     *
394
     * @param string $dbType
395
     * @param string $doctrineType
396
     *
397
     * @return void
398
     *
399
     * @throws DBALException If the type is not found.
400
     */
401 687
    public function registerDoctrineTypeMapping($dbType, $doctrineType)
402
    {
403 687
        if ($this->doctrineTypeMapping === null) {
404 682
            $this->initializeAllDoctrineTypeMappings();
405
        }
406
407 687
        if (! Types\Type::hasType($doctrineType)) {
408 220
            throw DBALException::typeNotFound($doctrineType);
409
        }
410
411 467
        $dbType                             = strtolower($dbType);
412 467
        $this->doctrineTypeMapping[$dbType] = $doctrineType;
413
414 467
        $doctrineType = Type::getType($doctrineType);
415
416 467
        if (! $doctrineType->requiresSQLCommentHint($this)) {
417 247
            return;
418
        }
419
420 220
        $this->markDoctrineTypeCommented($doctrineType);
421 220
    }
422
423
    /**
424
     * Gets the Doctrine type that is mapped for the given database column type.
425
     *
426
     * @param string $dbType
427
     *
428
     * @return string
429
     *
430
     * @throws DBALException
431
     */
432 2356
    public function getDoctrineTypeMapping($dbType)
433
    {
434 2356
        if ($this->doctrineTypeMapping === null) {
435 298
            $this->initializeAllDoctrineTypeMappings();
436
        }
437
438 2356
        $dbType = strtolower($dbType);
439
440 2356
        if (! isset($this->doctrineTypeMapping[$dbType])) {
441 220
            throw new DBALException('Unknown database type ' . $dbType . ' requested, ' . static::class . ' may not support it.');
442
        }
443
444 2136
        return $this->doctrineTypeMapping[$dbType];
445
    }
446
447
    /**
448
     * Checks if a database type is currently supported by this platform.
449
     *
450
     * @param string $dbType
451
     *
452
     * @return bool
453
     */
454 328
    public function hasDoctrineTypeMappingFor($dbType)
455
    {
456 328
        if ($this->doctrineTypeMapping === null) {
457 286
            $this->initializeAllDoctrineTypeMappings();
458
        }
459
460 328
        $dbType = strtolower($dbType);
461
462 328
        return isset($this->doctrineTypeMapping[$dbType]);
463
    }
464
465
    /**
466
     * Initializes the Doctrine Type comments instance variable for in_array() checks.
467
     *
468
     * @return void
469
     */
470 11154
    protected function initializeCommentedDoctrineTypes()
471
    {
472 11154
        $this->doctrineTypeComments = [];
473
474 11154
        foreach (Type::getTypesMap() as $typeName => $className) {
475 11154
            $type = Type::getType($typeName);
476
477 11154
            if (! $type->requiresSQLCommentHint($this)) {
478 11154
                continue;
479
            }
480
481 11154
            $this->doctrineTypeComments[] = $typeName;
482
        }
483 11154
    }
484
485
    /**
486
     * Is it necessary for the platform to add a parsable type comment to allow reverse engineering the given type?
487
     *
488
     * @return bool
489
     */
490 14591
    public function isCommentedDoctrineType(Type $doctrineType)
491
    {
492 14591
        if ($this->doctrineTypeComments === null) {
493 10934
            $this->initializeCommentedDoctrineTypes();
494
        }
495
496 14591
        assert(is_array($this->doctrineTypeComments));
497
498 14591
        return in_array($doctrineType->getName(), $this->doctrineTypeComments, true);
499
    }
500
501
    /**
502
     * Marks this type as to be commented in ALTER TABLE and CREATE TABLE statements.
503
     *
504
     * @param string|Type $doctrineType
505
     *
506
     * @return void
507
     */
508 220
    public function markDoctrineTypeCommented($doctrineType)
509
    {
510 220
        if ($this->doctrineTypeComments === null) {
511 220
            $this->initializeCommentedDoctrineTypes();
512
        }
513
514 220
        assert(is_array($this->doctrineTypeComments));
515
516 220
        $this->doctrineTypeComments[] = $doctrineType instanceof Type ? $doctrineType->getName() : $doctrineType;
517 220
    }
518
519
    /**
520
     * Gets the comment to append to a column comment that helps parsing this type in reverse engineering.
521
     *
522
     * @return string
523
     */
524 721
    public function getDoctrineTypeComment(Type $doctrineType)
525
    {
526 721
        return '(DC2Type:' . $doctrineType->getName() . ')';
527
    }
528
529
    /**
530
     * Gets the comment of a passed column modified by potential doctrine type comment hints.
531
     *
532
     * @return string|null
533
     */
534 8893
    protected function getColumnComment(Column $column)
535
    {
536 8893
        $comment = $column->getComment();
537
538 8893
        if ($this->isCommentedDoctrineType($column->getType())) {
539 721
            $comment .= $this->getDoctrineTypeComment($column->getType());
540
        }
541
542 8893
        return $comment;
543
    }
544
545
    /**
546
     * Gets the character used for identifier quoting.
547
     *
548
     * @return string
549
     */
550 3944
    public function getIdentifierQuoteCharacter()
551
    {
552 3944
        return '"';
553
    }
554
555
    /**
556
     * Gets the string portion that starts an SQL comment.
557
     *
558
     * @return string
559
     */
560
    public function getSqlCommentStartString()
561
    {
562
        return '--';
563
    }
564
565
    /**
566
     * Gets the string portion that ends an SQL comment.
567
     *
568
     * @return string
569
     */
570
    public function getSqlCommentEndString()
571
    {
572
        return "\n";
573
    }
574
575
    /**
576
     * Gets the maximum length of a char field.
577
     */
578 672
    public function getCharMaxLength() : int
579
    {
580 672
        return $this->getVarcharMaxLength();
581
    }
582
583
    /**
584
     * Gets the maximum length of a varchar field.
585
     *
586
     * @return int
587
     */
588 1829
    public function getVarcharMaxLength()
589
    {
590 1829
        return 4000;
591
    }
592
593
    /**
594
     * Gets the default length of a varchar field.
595
     *
596
     * @return int
597
     */
598 917
    public function getVarcharDefaultLength()
599
    {
600 917
        return 255;
601
    }
602
603
    /**
604
     * Gets the maximum length of a binary field.
605
     *
606
     * @return int
607
     */
608
    public function getBinaryMaxLength()
609
    {
610
        return 4000;
611
    }
612
613
    /**
614
     * Gets the default length of a binary field.
615
     *
616
     * @return int
617
     */
618 235
    public function getBinaryDefaultLength()
619
    {
620 235
        return 255;
621
    }
622
623
    /**
624
     * Gets all SQL wildcard characters of the platform.
625
     *
626
     * @return string[]
627
     */
628
    public function getWildcards()
629
    {
630
        return ['%', '_'];
631
    }
632
633
    /**
634
     * Returns the regular expression operator.
635
     *
636
     * @return string
637
     *
638
     * @throws DBALException If not supported on this platform.
639
     */
640 44
    public function getRegexpExpression()
641
    {
642 44
        throw DBALException::notSupported(__METHOD__);
643
    }
644
645
    /**
646
     * Returns the global unique identifier expression.
647
     *
648
     * @deprecated Use application-generated UUIDs instead
649
     *
650
     * @return string
651
     *
652
     * @throws DBALException If not supported on this platform.
653
     */
654
    public function getGuidExpression()
655
    {
656
        throw DBALException::notSupported(__METHOD__);
657
    }
658
659
    /**
660
     * Returns the SQL snippet to get the average value of a column.
661
     *
662
     * @param string $column The column to use.
663
     *
664
     * @return string Generated SQL including an AVG aggregate function.
665
     */
666
    public function getAvgExpression($column)
667
    {
668
        return 'AVG(' . $column . ')';
669
    }
670
671
    /**
672
     * Returns the SQL snippet to get the number of rows (without a NULL value) of a column.
673
     *
674
     * If a '*' is used instead of a column the number of selected rows is returned.
675
     *
676
     * @param string|int $column The column to use.
677
     *
678
     * @return string Generated SQL including a COUNT aggregate function.
679
     */
680
    public function getCountExpression($column)
681
    {
682
        return 'COUNT(' . $column . ')';
683
    }
684
685
    /**
686
     * Returns the SQL snippet to get the highest value of a column.
687
     *
688
     * @param string $column The column to use.
689
     *
690
     * @return string Generated SQL including a MAX aggregate function.
691
     */
692
    public function getMaxExpression($column)
693
    {
694
        return 'MAX(' . $column . ')';
695
    }
696
697
    /**
698
     * Returns the SQL snippet to get the lowest value of a column.
699
     *
700
     * @param string $column The column to use.
701
     *
702
     * @return string Generated SQL including a MIN aggregate function.
703
     */
704
    public function getMinExpression($column)
705
    {
706
        return 'MIN(' . $column . ')';
707
    }
708
709
    /**
710
     * Returns the SQL snippet to get the total sum of a column.
711
     *
712
     * @param string $column The column to use.
713
     *
714
     * @return string Generated SQL including a SUM aggregate function.
715
     */
716
    public function getSumExpression($column)
717
    {
718
        return 'SUM(' . $column . ')';
719
    }
720
721
    // scalar functions
722
723
    /**
724
     * Returns the SQL snippet to get the md5 sum of a field.
725
     *
726
     * Note: Not SQL92, but common functionality.
727
     *
728
     * @param string $column
729
     *
730
     * @return string
731
     */
732
    public function getMd5Expression($column)
733
    {
734
        return 'MD5(' . $column . ')';
735
    }
736
737
    /**
738
     * Returns the SQL snippet to get the length of a text field.
739
     *
740
     * @param string $column
741
     *
742
     * @return string
743
     */
744
    public function getLengthExpression($column)
745
    {
746
        return 'LENGTH(' . $column . ')';
747
    }
748
749
    /**
750
     * Returns the SQL snippet to get the squared value of a column.
751
     *
752
     * @param string $column The column to use.
753
     *
754
     * @return string Generated SQL including an SQRT aggregate function.
755
     */
756
    public function getSqrtExpression($column)
757
    {
758
        return 'SQRT(' . $column . ')';
759
    }
760
761
    /**
762
     * Returns the SQL snippet to round a numeric field to the number of decimals specified.
763
     *
764
     * @param string $column
765
     * @param int    $decimals
766
     *
767
     * @return string
768
     */
769
    public function getRoundExpression($column, $decimals = 0)
770
    {
771
        return 'ROUND(' . $column . ', ' . $decimals . ')';
772
    }
773
774
    /**
775
     * Returns the SQL snippet to get the remainder of the division operation $expression1 / $expression2.
776
     *
777
     * @param string $expression1
778
     * @param string $expression2
779
     *
780
     * @return string
781
     */
782
    public function getModExpression($expression1, $expression2)
783
    {
784
        return 'MOD(' . $expression1 . ', ' . $expression2 . ')';
785
    }
786
787
    /**
788
     * Returns the SQL snippet to trim a string.
789
     *
790
     * @param string      $str  The expression to apply the trim to.
791
     * @param int         $mode The position of the trim (leading/trailing/both).
792
     * @param string|bool $char The char to trim, has to be quoted already. Defaults to space.
793
     *
794
     * @return string
795
     */
796 684
    public function getTrimExpression($str, $mode = TrimMode::UNSPECIFIED, $char = false)
797
    {
798 684
        $expression = '';
799
800 684
        switch ($mode) {
801
            case TrimMode::LEADING:
802 171
                $expression = 'LEADING ';
803 171
                break;
804
805
            case TrimMode::TRAILING:
806 171
                $expression = 'TRAILING ';
807 171
                break;
808
809
            case TrimMode::BOTH:
810 171
                $expression = 'BOTH ';
811 171
                break;
812
        }
813
814 684
        if ($char !== false) {
815 532
            $expression .= $char . ' ';
0 ignored issues
show
Bug introduced by
Are you sure $char of type string|true 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

815
            $expression .= /** @scrutinizer ignore-type */ $char . ' ';
Loading history...
816
        }
817
818 684
        if ($mode !== TrimMode::UNSPECIFIED || $char !== false) {
819 646
            $expression .= 'FROM ';
820
        }
821
822 684
        return 'TRIM(' . $expression . $str . ')';
823
    }
824
825
    /**
826
     * Returns the SQL snippet to trim trailing space characters from the expression.
827
     *
828
     * @param string $str Literal string or column name.
829
     *
830
     * @return string
831
     */
832 22
    public function getRtrimExpression($str)
833
    {
834 22
        return 'RTRIM(' . $str . ')';
835
    }
836
837
    /**
838
     * Returns the SQL snippet to trim leading space characters from the expression.
839
     *
840
     * @param string $str Literal string or column name.
841
     *
842
     * @return string
843
     */
844 22
    public function getLtrimExpression($str)
845
    {
846 22
        return 'LTRIM(' . $str . ')';
847
    }
848
849
    /**
850
     * Returns the SQL snippet to change all characters from the expression to uppercase,
851
     * according to the current character set mapping.
852
     *
853
     * @param string $str Literal string or column name.
854
     *
855
     * @return string
856
     */
857
    public function getUpperExpression($str)
858
    {
859
        return 'UPPER(' . $str . ')';
860
    }
861
862
    /**
863
     * Returns the SQL snippet to change all characters from the expression to lowercase,
864
     * according to the current character set mapping.
865
     *
866
     * @param string $str Literal string or column name.
867
     *
868
     * @return string
869
     */
870
    public function getLowerExpression($str)
871
    {
872
        return 'LOWER(' . $str . ')';
873
    }
874
875
    /**
876
     * Returns the SQL snippet to get the position of the first occurrence of substring $substr in string $str.
877
     *
878
     * @param string    $str      Literal string.
879
     * @param string    $substr   Literal string to find.
880
     * @param int|false $startPos Position to start at, beginning of string by default.
881
     *
882
     * @return string
883
     *
884
     * @throws DBALException If not supported on this platform.
885
     */
886
    public function getLocateExpression($str, $substr, $startPos = false)
0 ignored issues
show
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

886
    public function getLocateExpression($str, /** @scrutinizer ignore-unused */ $substr, $startPos = false)

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 $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

886
    public function getLocateExpression($str, $substr, /** @scrutinizer ignore-unused */ $startPos = false)

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...
887
    {
888
        throw DBALException::notSupported(__METHOD__);
889
    }
890
891
    /**
892
     * Returns the SQL snippet to get the current system date.
893
     *
894
     * @return string
895
     */
896
    public function getNowExpression()
897
    {
898
        return 'NOW()';
899
    }
900
901
    /**
902
     * Returns a SQL snippet to get a substring inside an SQL statement.
903
     *
904
     * Note: Not SQL92, but common functionality.
905
     *
906
     * SQLite only supports the 2 parameter variant of this function.
907
     *
908
     * @param string   $value  An sql string literal or column name/alias.
909
     * @param int      $from   Where to start the substring portion.
910
     * @param int|null $length The substring portion length.
911
     *
912
     * @return string
913
     */
914
    public function getSubstringExpression($value, $from, $length = null)
915
    {
916
        if ($length === null) {
917
            return 'SUBSTRING(' . $value . ' FROM ' . $from . ')';
918
        }
919
920
        return 'SUBSTRING(' . $value . ' FROM ' . $from . ' FOR ' . $length . ')';
921
    }
922
923
    /**
924
     * Returns a SQL snippet to concatenate the given expressions.
925
     *
926
     * Accepts an arbitrary number of string parameters. Each parameter must contain an expression.
927
     *
928
     * @return string
929
     */
930 66
    public function getConcatExpression()
931
    {
932 66
        return implode(' || ', func_get_args());
933
    }
934
935
    /**
936
     * Returns the SQL for a logical not.
937
     *
938
     * Example:
939
     * <code>
940
     * $q = new Doctrine_Query();
941
     * $e = $q->expr;
942
     * $q->select('*')->from('table')
943
     *   ->where($e->eq('id', $e->not('null'));
944
     * </code>
945
     *
946
     * @param string $expression
947
     *
948
     * @return string The logical expression.
949
     */
950
    public function getNotExpression($expression)
951
    {
952
        return 'NOT(' . $expression . ')';
953
    }
954
955
    /**
956
     * Returns the SQL that checks if an expression is null.
957
     *
958
     * @param string $expression The expression that should be compared to null.
959
     *
960
     * @return string The logical expression.
961
     */
962 88
    public function getIsNullExpression($expression)
963
    {
964 88
        return $expression . ' IS NULL';
965
    }
966
967
    /**
968
     * Returns the SQL that checks if an expression is not null.
969
     *
970
     * @param string $expression The expression that should be compared to null.
971
     *
972
     * @return string The logical expression.
973
     */
974
    public function getIsNotNullExpression($expression)
975
    {
976
        return $expression . ' IS NOT NULL';
977
    }
978
979
    /**
980
     * Returns the SQL that checks if an expression evaluates to a value between two values.
981
     *
982
     * The parameter $expression is checked if it is between $value1 and $value2.
983
     *
984
     * Note: There is a slight difference in the way BETWEEN works on some databases.
985
     * http://www.w3schools.com/sql/sql_between.asp. If you want complete database
986
     * independence you should avoid using between().
987
     *
988
     * @param string $expression The value to compare to.
989
     * @param string $value1     The lower value to compare with.
990
     * @param string $value2     The higher value to compare with.
991
     *
992
     * @return string The logical expression.
993
     */
994
    public function getBetweenExpression($expression, $value1, $value2)
995
    {
996
        return $expression . ' BETWEEN ' . $value1 . ' AND ' . $value2;
997
    }
998
999
    /**
1000
     * Returns the SQL to get the arccosine of a value.
1001
     *
1002
     * @param string $value
1003
     *
1004
     * @return string
1005
     */
1006
    public function getAcosExpression($value)
1007
    {
1008
        return 'ACOS(' . $value . ')';
1009
    }
1010
1011
    /**
1012
     * Returns the SQL to get the sine of a value.
1013
     *
1014
     * @param string $value
1015
     *
1016
     * @return string
1017
     */
1018
    public function getSinExpression($value)
1019
    {
1020
        return 'SIN(' . $value . ')';
1021
    }
1022
1023
    /**
1024
     * Returns the SQL to get the PI value.
1025
     *
1026
     * @return string
1027
     */
1028
    public function getPiExpression()
1029
    {
1030
        return 'PI()';
1031
    }
1032
1033
    /**
1034
     * Returns the SQL to get the cosine of a value.
1035
     *
1036
     * @param string $value
1037
     *
1038
     * @return string
1039
     */
1040
    public function getCosExpression($value)
1041
    {
1042
        return 'COS(' . $value . ')';
1043
    }
1044
1045
    /**
1046
     * Returns the SQL to calculate the difference in days between the two passed dates.
1047
     *
1048
     * Computes diff = date1 - date2.
1049
     *
1050
     * @param string $date1
1051
     * @param string $date2
1052
     *
1053
     * @return string
1054
     *
1055
     * @throws DBALException If not supported on this platform.
1056
     */
1057
    public function getDateDiffExpression($date1, $date2)
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

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

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

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

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...
1058
    {
1059
        throw DBALException::notSupported(__METHOD__);
1060
    }
1061
1062
    /**
1063
     * Returns the SQL to add the number of given seconds to a date.
1064
     *
1065
     * @param string $date
1066
     * @param int    $seconds
1067
     *
1068
     * @return string
1069
     *
1070
     * @throws DBALException If not supported on this platform.
1071
     */
1072 66
    public function getDateAddSecondsExpression($date, $seconds)
1073
    {
1074 66
        return $this->getDateArithmeticIntervalExpression($date, '+', $seconds, DateIntervalUnit::SECOND);
1075
    }
1076
1077
    /**
1078
     * Returns the SQL to subtract the number of given seconds from a date.
1079
     *
1080
     * @param string $date
1081
     * @param int    $seconds
1082
     *
1083
     * @return string
1084
     *
1085
     * @throws DBALException If not supported on this platform.
1086
     */
1087 66
    public function getDateSubSecondsExpression($date, $seconds)
1088
    {
1089 66
        return $this->getDateArithmeticIntervalExpression($date, '-', $seconds, DateIntervalUnit::SECOND);
1090
    }
1091
1092
    /**
1093
     * Returns the SQL to add the number of given minutes to a date.
1094
     *
1095
     * @param string $date
1096
     * @param int    $minutes
1097
     *
1098
     * @return string
1099
     *
1100
     * @throws DBALException If not supported on this platform.
1101
     */
1102 66
    public function getDateAddMinutesExpression($date, $minutes)
1103
    {
1104 66
        return $this->getDateArithmeticIntervalExpression($date, '+', $minutes, DateIntervalUnit::MINUTE);
1105
    }
1106
1107
    /**
1108
     * Returns the SQL to subtract the number of given minutes from a date.
1109
     *
1110
     * @param string $date
1111
     * @param int    $minutes
1112
     *
1113
     * @return string
1114
     *
1115
     * @throws DBALException If not supported on this platform.
1116
     */
1117 66
    public function getDateSubMinutesExpression($date, $minutes)
1118
    {
1119 66
        return $this->getDateArithmeticIntervalExpression($date, '-', $minutes, DateIntervalUnit::MINUTE);
1120
    }
1121
1122
    /**
1123
     * Returns the SQL to add the number of given hours to a date.
1124
     *
1125
     * @param string $date
1126
     * @param int    $hours
1127
     *
1128
     * @return string
1129
     *
1130
     * @throws DBALException If not supported on this platform.
1131
     */
1132 66
    public function getDateAddHourExpression($date, $hours)
1133
    {
1134 66
        return $this->getDateArithmeticIntervalExpression($date, '+', $hours, DateIntervalUnit::HOUR);
1135
    }
1136
1137
    /**
1138
     * Returns the SQL to subtract the number of given hours to a date.
1139
     *
1140
     * @param string $date
1141
     * @param int    $hours
1142
     *
1143
     * @return string
1144
     *
1145
     * @throws DBALException If not supported on this platform.
1146
     */
1147 66
    public function getDateSubHourExpression($date, $hours)
1148
    {
1149 66
        return $this->getDateArithmeticIntervalExpression($date, '-', $hours, DateIntervalUnit::HOUR);
1150
    }
1151
1152
    /**
1153
     * Returns the SQL to add the number of given days to a date.
1154
     *
1155
     * @param string $date
1156
     * @param int    $days
1157
     *
1158
     * @return string
1159
     *
1160
     * @throws DBALException If not supported on this platform.
1161
     */
1162 110
    public function getDateAddDaysExpression($date, $days)
1163
    {
1164 110
        return $this->getDateArithmeticIntervalExpression($date, '+', $days, DateIntervalUnit::DAY);
1165
    }
1166
1167
    /**
1168
     * Returns the SQL to subtract the number of given days to a date.
1169
     *
1170
     * @param string $date
1171
     * @param int    $days
1172
     *
1173
     * @return string
1174
     *
1175
     * @throws DBALException If not supported on this platform.
1176
     */
1177 68
    public function getDateSubDaysExpression($date, $days)
1178
    {
1179 68
        return $this->getDateArithmeticIntervalExpression($date, '-', $days, DateIntervalUnit::DAY);
1180
    }
1181
1182
    /**
1183
     * Returns the SQL to add the number of given weeks to a date.
1184
     *
1185
     * @param string $date
1186
     * @param int    $weeks
1187
     *
1188
     * @return string
1189
     *
1190
     * @throws DBALException If not supported on this platform.
1191
     */
1192 66
    public function getDateAddWeeksExpression($date, $weeks)
1193
    {
1194 66
        return $this->getDateArithmeticIntervalExpression($date, '+', $weeks, DateIntervalUnit::WEEK);
1195
    }
1196
1197
    /**
1198
     * Returns the SQL to subtract the number of given weeks from a date.
1199
     *
1200
     * @param string $date
1201
     * @param int    $weeks
1202
     *
1203
     * @return string
1204
     *
1205
     * @throws DBALException If not supported on this platform.
1206
     */
1207 66
    public function getDateSubWeeksExpression($date, $weeks)
1208
    {
1209 66
        return $this->getDateArithmeticIntervalExpression($date, '-', $weeks, DateIntervalUnit::WEEK);
1210
    }
1211
1212
    /**
1213
     * Returns the SQL to add the number of given months to a date.
1214
     *
1215
     * @param string $date
1216
     * @param int    $months
1217
     *
1218
     * @return string
1219
     *
1220
     * @throws DBALException If not supported on this platform.
1221
     */
1222 66
    public function getDateAddMonthExpression($date, $months)
1223
    {
1224 66
        return $this->getDateArithmeticIntervalExpression($date, '+', $months, DateIntervalUnit::MONTH);
1225
    }
1226
1227
    /**
1228
     * Returns the SQL to subtract the number of given months to a date.
1229
     *
1230
     * @param string $date
1231
     * @param int    $months
1232
     *
1233
     * @return string
1234
     *
1235
     * @throws DBALException If not supported on this platform.
1236
     */
1237 66
    public function getDateSubMonthExpression($date, $months)
1238
    {
1239 66
        return $this->getDateArithmeticIntervalExpression($date, '-', $months, DateIntervalUnit::MONTH);
1240
    }
1241
1242
    /**
1243
     * Returns the SQL to add the number of given quarters to a date.
1244
     *
1245
     * @param string $date
1246
     * @param int    $quarters
1247
     *
1248
     * @return string
1249
     *
1250
     * @throws DBALException If not supported on this platform.
1251
     */
1252 66
    public function getDateAddQuartersExpression($date, $quarters)
1253
    {
1254 66
        return $this->getDateArithmeticIntervalExpression($date, '+', $quarters, DateIntervalUnit::QUARTER);
1255
    }
1256
1257
    /**
1258
     * Returns the SQL to subtract the number of given quarters from a date.
1259
     *
1260
     * @param string $date
1261
     * @param int    $quarters
1262
     *
1263
     * @return string
1264
     *
1265
     * @throws DBALException If not supported on this platform.
1266
     */
1267 66
    public function getDateSubQuartersExpression($date, $quarters)
1268
    {
1269 66
        return $this->getDateArithmeticIntervalExpression($date, '-', $quarters, DateIntervalUnit::QUARTER);
1270
    }
1271
1272
    /**
1273
     * Returns the SQL to add the number of given years to a date.
1274
     *
1275
     * @param string $date
1276
     * @param int    $years
1277
     *
1278
     * @return string
1279
     *
1280
     * @throws DBALException If not supported on this platform.
1281
     */
1282 66
    public function getDateAddYearsExpression($date, $years)
1283
    {
1284 66
        return $this->getDateArithmeticIntervalExpression($date, '+', $years, DateIntervalUnit::YEAR);
1285
    }
1286
1287
    /**
1288
     * Returns the SQL to subtract the number of given years from a date.
1289
     *
1290
     * @param string $date
1291
     * @param int    $years
1292
     *
1293
     * @return string
1294
     *
1295
     * @throws DBALException If not supported on this platform.
1296
     */
1297 66
    public function getDateSubYearsExpression($date, $years)
1298
    {
1299 66
        return $this->getDateArithmeticIntervalExpression($date, '-', $years, DateIntervalUnit::YEAR);
1300
    }
1301
1302
    /**
1303
     * Returns the SQL for a date arithmetic expression.
1304
     *
1305
     * @param string $date     The column or literal representing a date to perform the arithmetic operation on.
1306
     * @param string $operator The arithmetic operator (+ or -).
1307
     * @param int    $interval The interval that shall be calculated into the date.
1308
     * @param string $unit     The unit of the interval that shall be calculated into the date.
1309
     *                         One of the DATE_INTERVAL_UNIT_* constants.
1310
     *
1311
     * @return string
1312
     *
1313
     * @throws DBALException If not supported on this platform.
1314
     */
1315
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
0 ignored issues
show
Unused Code introduced by
The parameter $unit is not used and could be removed. ( Ignorable by Annotation )

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

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

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 $interval 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

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

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 $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

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

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...
1316
    {
1317
        throw DBALException::notSupported(__METHOD__);
1318
    }
1319
1320
    /**
1321
     * Returns the SQL bit AND comparison expression.
1322
     *
1323
     * @param string $value1
1324
     * @param string $value2
1325
     *
1326
     * @return string
1327
     */
1328 196
    public function getBitAndComparisonExpression($value1, $value2)
1329
    {
1330 196
        return '(' . $value1 . ' & ' . $value2 . ')';
1331
    }
1332
1333
    /**
1334
     * Returns the SQL bit OR comparison expression.
1335
     *
1336
     * @param string $value1
1337
     * @param string $value2
1338
     *
1339
     * @return string
1340
     */
1341 196
    public function getBitOrComparisonExpression($value1, $value2)
1342
    {
1343 196
        return '(' . $value1 . ' | ' . $value2 . ')';
1344
    }
1345
1346
    /**
1347
     * Returns the FOR UPDATE expression.
1348
     *
1349
     * @return string
1350
     */
1351 38
    public function getForUpdateSQL()
1352
    {
1353 38
        return 'FOR UPDATE';
1354
    }
1355
1356
    /**
1357
     * Honors that some SQL vendors such as MsSql use table hints for locking instead of the ANSI SQL FOR UPDATE specification.
1358
     *
1359
     * @param string   $fromClause The FROM clause to append the hint for the given lock mode to.
1360
     * @param int|null $lockMode   One of the Doctrine\DBAL\LockMode::* constants. If null is given, nothing will
1361
     *                             be appended to the FROM clause.
1362
     *
1363
     * @return string
1364
     */
1365 38
    public function appendLockHint($fromClause, $lockMode)
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

1365
    public function appendLockHint($fromClause, /** @scrutinizer ignore-unused */ $lockMode)

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...
1366
    {
1367 38
        return $fromClause;
1368
    }
1369
1370
    /**
1371
     * Returns the SQL snippet to append to any SELECT statement which locks rows in shared read lock.
1372
     *
1373
     * This defaults to the ANSI SQL "FOR UPDATE", which is an exclusive lock (Write). Some database
1374
     * vendors allow to lighten this constraint up to be a real read lock.
1375
     *
1376
     * @return string
1377
     */
1378
    public function getReadLockSQL()
1379
    {
1380
        return $this->getForUpdateSQL();
1381
    }
1382
1383
    /**
1384
     * Returns the SQL snippet to append to any SELECT statement which obtains an exclusive lock on the rows.
1385
     *
1386
     * The semantics of this lock mode should equal the SELECT .. FOR UPDATE of the ANSI SQL standard.
1387
     *
1388
     * @return string
1389
     */
1390 40
    public function getWriteLockSQL()
1391
    {
1392 40
        return $this->getForUpdateSQL();
1393
    }
1394
1395
    /**
1396
     * Returns the SQL snippet to drop an existing database.
1397
     *
1398
     * @param string $database The name of the database that should be dropped.
1399
     *
1400
     * @return string
1401
     */
1402 54
    public function getDropDatabaseSQL($database)
1403
    {
1404 54
        return 'DROP DATABASE ' . $database;
1405
    }
1406
1407
    /**
1408
     * Returns the SQL snippet to drop an existing table.
1409
     *
1410
     * @param Table|string $table
1411
     *
1412
     * @return string
1413
     *
1414
     * @throws InvalidArgumentException
1415
     */
1416 3798
    public function getDropTableSQL($table)
1417
    {
1418 3798
        $tableArg = $table;
1419
1420 3798
        if ($table instanceof Table) {
1421 342
            $table = $table->getQuotedName($this);
1422
        }
1423
1424 3798
        if (! is_string($table)) {
0 ignored issues
show
introduced by
The condition is_string($table) is always true.
Loading history...
1425
            throw new InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
1426
        }
1427
1428 3798
        if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaDropTable)) {
1429 220
            $eventArgs = new SchemaDropTableEventArgs($tableArg, $this);
1430 220
            $this->_eventManager->dispatchEvent(Events::onSchemaDropTable, $eventArgs);
1431
1432 220
            if ($eventArgs->isDefaultPrevented()) {
1433
                $sql = $eventArgs->getSql();
1434
1435
                if ($sql === null) {
1436
                    throw new UnexpectedValueException('Default implementation of DROP TABLE was overridden with NULL');
1437
                }
1438
1439
                return $sql;
1440
            }
1441
        }
1442
1443 3798
        return 'DROP TABLE ' . $table;
1444
    }
1445
1446
    /**
1447
     * Returns the SQL to safely drop a temporary table WITHOUT implicitly committing an open transaction.
1448
     *
1449
     * @param Table|string $table
1450
     *
1451
     * @return string
1452
     */
1453 16
    public function getDropTemporaryTableSQL($table)
1454
    {
1455 16
        return $this->getDropTableSQL($table);
1456
    }
1457
1458
    /**
1459
     * Returns the SQL to drop an index from a table.
1460
     *
1461
     * @param Index|string $index
1462
     * @param Table|string $table
1463
     *
1464
     * @return string
1465
     *
1466
     * @throws InvalidArgumentException
1467
     */
1468 139
    public function getDropIndexSQL($index, $table = null)
1469
    {
1470 139
        if ($index instanceof Index) {
1471 130
            $index = $index->getQuotedName($this);
1472 9
        } elseif (! is_string($index)) {
0 ignored issues
show
introduced by
The condition is_string($index) is always true.
Loading history...
1473
            throw new InvalidArgumentException('AbstractPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
1474
        }
1475
1476 139
        return 'DROP INDEX ' . $index;
1477
    }
1478
1479
    /**
1480
     * Returns the SQL to drop a constraint.
1481
     *
1482
     * @param Constraint|string $constraint
1483
     * @param Table|string      $table
1484
     *
1485
     * @return string
1486
     */
1487 663
    public function getDropConstraintSQL($constraint, $table)
1488
    {
1489 663
        if (! $constraint instanceof Constraint) {
1490 570
            $constraint = new Identifier($constraint);
1491
        }
1492
1493 663
        if (! $table instanceof Table) {
1494 663
            $table = new Identifier($table);
1495
        }
1496
1497 663
        $constraint = $constraint->getQuotedName($this);
1498 663
        $table      = $table->getQuotedName($this);
1499
1500 663
        return 'ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $constraint;
1501
    }
1502
1503
    /**
1504
     * Returns the SQL to drop a foreign key.
1505
     *
1506
     * @param ForeignKeyConstraint|string $foreignKey
1507
     * @param Table|string                $table
1508
     *
1509
     * @return string
1510
     */
1511 350
    public function getDropForeignKeySQL($foreignKey, $table)
1512
    {
1513 350
        if (! $foreignKey instanceof ForeignKeyConstraint) {
1514 110
            $foreignKey = new Identifier($foreignKey);
1515
        }
1516
1517 350
        if (! $table instanceof Table) {
1518 350
            $table = new Identifier($table);
1519
        }
1520
1521 350
        $foreignKey = $foreignKey->getQuotedName($this);
1522 350
        $table      = $table->getQuotedName($this);
1523
1524 350
        return 'ALTER TABLE ' . $table . ' DROP FOREIGN KEY ' . $foreignKey;
1525
    }
1526
1527
    /**
1528
     * Returns the SQL statement(s) to create a table with the specified name, columns and constraints
1529
     * on this platform.
1530
     *
1531
     * @param int $createFlags
1532
     *
1533
     * @return string[] The sequence of SQL statements.
1534
     *
1535
     * @throws DBALException
1536
     * @throws InvalidArgumentException
1537
     */
1538 7275
    public function getCreateTableSQL(Table $table, $createFlags = self::CREATE_INDEXES)
1539
    {
1540 7275
        if (! is_int($createFlags)) {
0 ignored issues
show
introduced by
The condition is_int($createFlags) is always true.
Loading history...
1541
            throw new InvalidArgumentException('Second argument of AbstractPlatform::getCreateTableSQL() has to be integer.');
1542
        }
1543
1544 7275
        if (count($table->getColumns()) === 0) {
1545 220
            throw DBALException::noColumnsSpecifiedForTable($table->getName());
1546
        }
1547
1548 7055
        $tableName                    = $table->getQuotedName($this);
1549 7055
        $options                      = $table->getOptions();
1550 7055
        $options['uniqueConstraints'] = [];
1551 7055
        $options['indexes']           = [];
1552 7055
        $options['primary']           = [];
1553
1554 7055
        if (($createFlags & self::CREATE_INDEXES) > 0) {
1555 6791
            foreach ($table->getIndexes() as $index) {
1556 4561
                if (! $index->isPrimary()) {
1557 1428
                    $options['indexes'][$index->getQuotedName($this)] = $index;
1558
1559 1428
                    continue;
1560
                }
1561
1562 3593
                $options['primary']       = $index->getQuotedColumns($this);
1563 3593
                $options['primary_index'] = $index;
1564
            }
1565
1566 6791
            foreach ($table->getUniqueConstraints() as $uniqueConstraint) {
1567
                $options['uniqueConstraints'][$uniqueConstraint->getQuotedName($this)] = $uniqueConstraint;
1568
            }
1569
        }
1570
1571 7055
        if (($createFlags & self::CREATE_FOREIGNKEYS) > 0) {
1572 4366
            $options['foreignKeys'] = [];
1573
1574 4366
            foreach ($table->getForeignKeys() as $fkConstraint) {
1575 626
                $options['foreignKeys'][] = $fkConstraint;
1576
            }
1577
        }
1578
1579 7055
        $columnSql = [];
1580 7055
        $columns   = [];
1581
1582 7055
        foreach ($table->getColumns() as $column) {
1583 7055
            if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaCreateTableColumn)) {
1584 220
                $eventArgs = new SchemaCreateTableColumnEventArgs($column, $table, $this);
1585
1586 220
                $this->_eventManager->dispatchEvent(Events::onSchemaCreateTableColumn, $eventArgs);
1587
1588 220
                $columnSql = array_merge($columnSql, $eventArgs->getSql());
1589
1590 220
                if ($eventArgs->isDefaultPrevented()) {
1591
                    continue;
1592
                }
1593
            }
1594
1595 7055
            $columnData            = $column->toArray();
1596 7055
            $columnData['name']    = $column->getQuotedName($this);
1597 7055
            $columnData['version'] = $column->hasPlatformOption('version') ? $column->getPlatformOption('version') : false;
1598 7055
            $columnData['comment'] = $this->getColumnComment($column);
1599
1600 7055
            if ($columnData['type'] instanceof Types\StringType && $columnData['length'] === null) {
1601 2558
                $columnData['length'] = 255;
1602
            }
1603
1604 7055
            if (in_array($column->getName(), $options['primary'], true)) {
1605 3329
                $columnData['primary'] = true;
1606
            }
1607
1608 7055
            $columns[$columnData['name']] = $columnData;
1609
        }
1610
1611 7055
        if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaCreateTable)) {
1612 220
            $eventArgs = new SchemaCreateTableEventArgs($table, $columns, $options, $this);
1613
1614 220
            $this->_eventManager->dispatchEvent(Events::onSchemaCreateTable, $eventArgs);
1615
1616 220
            if ($eventArgs->isDefaultPrevented()) {
1617
                return array_merge($eventArgs->getSql(), $columnSql);
1618
            }
1619
        }
1620
1621 7055
        $sql = $this->_getCreateTableSQL($tableName, $columns, $options);
1622
1623 7055
        if ($this->supportsCommentOnStatement()) {
1624 2564
            if ($table->hasOption('comment')) {
1625 51
                $sql[] = $this->getCommentOnTableSQL($tableName, $table->getOption('comment'));
1626
            }
1627
1628 2564
            foreach ($table->getColumns() as $column) {
1629 2564
                $comment = $this->getColumnComment($column);
1630
1631 2564
                if ($comment === null || $comment === '') {
1632 2412
                    continue;
1633
                }
1634
1635 439
                $sql[] = $this->getCommentOnColumnSQL($tableName, $column->getQuotedName($this), $comment);
1636
            }
1637
        }
1638
1639 7055
        return array_merge($sql, $columnSql);
1640
    }
1641
1642 51
    protected function getCommentOnTableSQL(string $tableName, ?string $comment) : string
1643
    {
1644 51
        $tableName = new Identifier($tableName);
1645
1646 51
        return sprintf(
1647 6
            'COMMENT ON TABLE %s IS %s',
1648 51
            $tableName->getQuotedName($this),
1649 51
            $this->quoteStringLiteral((string) $comment)
1650
        );
1651
    }
1652
1653
    /**
1654
     * @param string      $tableName
1655
     * @param string      $columnName
1656
     * @param string|null $comment
1657
     *
1658
     * @return string
1659
     */
1660 680
    public function getCommentOnColumnSQL($tableName, $columnName, $comment)
1661
    {
1662 680
        $tableName  = new Identifier($tableName);
1663 680
        $columnName = new Identifier($columnName);
1664
1665 680
        return sprintf(
1666 120
            'COMMENT ON COLUMN %s.%s IS %s',
1667 680
            $tableName->getQuotedName($this),
1668 680
            $columnName->getQuotedName($this),
1669 680
            $this->quoteStringLiteral((string) $comment)
1670
        );
1671
    }
1672
1673
    /**
1674
     * Returns the SQL to create inline comment on a column.
1675
     *
1676
     * @param string $comment
1677
     *
1678
     * @return string
1679
     *
1680
     * @throws DBALException If not supported on this platform.
1681
     */
1682 1126
    public function getInlineColumnCommentSQL($comment)
1683
    {
1684 1126
        if (! $this->supportsInlineColumnComments()) {
1685 132
            throw DBALException::notSupported(__METHOD__);
1686
        }
1687
1688 994
        return 'COMMENT ' . $this->quoteStringLiteral($comment);
1689
    }
1690
1691
    /**
1692
     * Returns the SQL used to create a table.
1693
     *
1694
     * @param string    $name
1695
     * @param mixed[][] $columns
1696
     * @param mixed[]   $options
1697
     *
1698
     * @return string[]
1699
     */
1700 800
    protected function _getCreateTableSQL($name, array $columns, array $options = [])
1701
    {
1702 800
        $columnListSql = $this->getColumnDeclarationListSQL($columns);
1703
1704 800
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
1705
            foreach ($options['uniqueConstraints'] as $constraintName => $definition) {
1706
                $columnListSql .= ', ' . $this->getUniqueConstraintDeclarationSQL($constraintName, $definition);
1707
            }
1708
        }
1709
1710 800
        if (isset($options['primary']) && ! empty($options['primary'])) {
1711 408
            $columnListSql .= ', PRIMARY KEY(' . implode(', ', array_unique(array_values($options['primary']))) . ')';
1712
        }
1713
1714 800
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
1715
            foreach ($options['indexes'] as $index => $definition) {
1716
                $columnListSql .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
1717
            }
1718
        }
1719
1720 800
        $query = 'CREATE TABLE ' . $name . ' (' . $columnListSql;
1721 800
        $check = $this->getCheckDeclarationSQL($columns);
1722
1723 800
        if (! empty($check)) {
1724 22
            $query .= ', ' . $check;
1725
        }
1726
1727 800
        $query .= ')';
1728
1729 800
        $sql = [$query];
1730
1731 800
        if (isset($options['foreignKeys'])) {
1732 340
            foreach ((array) $options['foreignKeys'] as $definition) {
1733 84
                $sql[] = $this->getCreateForeignKeySQL($definition, $name);
1734
            }
1735
        }
1736
1737 800
        return $sql;
1738
    }
1739
1740
    /**
1741
     * @return string
1742
     */
1743 38
    public function getCreateTemporaryTableSnippetSQL()
1744
    {
1745 38
        return 'CREATE TEMPORARY TABLE';
1746
    }
1747
1748
    /**
1749
     * Returns the SQL to create a sequence on this platform.
1750
     *
1751
     * @return string
1752
     *
1753
     * @throws DBALException If not supported on this platform.
1754
     */
1755
    public function getCreateSequenceSQL(Sequence $sequence)
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

1755
    public function getCreateSequenceSQL(/** @scrutinizer ignore-unused */ Sequence $sequence)

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...
1756
    {
1757
        throw DBALException::notSupported(__METHOD__);
1758
    }
1759
1760
    /**
1761
     * Returns the SQL to change a sequence on this platform.
1762
     *
1763
     * @return string
1764
     *
1765
     * @throws DBALException If not supported on this platform.
1766
     */
1767
    public function getAlterSequenceSQL(Sequence $sequence)
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

1767
    public function getAlterSequenceSQL(/** @scrutinizer ignore-unused */ Sequence $sequence)

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...
1768
    {
1769
        throw DBALException::notSupported(__METHOD__);
1770
    }
1771
1772
    /**
1773
     * Returns the SQL to create a constraint on a table on this platform.
1774
     *
1775
     * @param Table|string $table
1776
     *
1777
     * @return string
1778
     *
1779
     * @throws InvalidArgumentException
1780
     */
1781 292
    public function getCreateConstraintSQL(Constraint $constraint, $table)
1782
    {
1783 292
        if ($table instanceof Table) {
1784
            $table = $table->getQuotedName($this);
1785
        }
1786
1787 292
        $query = 'ALTER TABLE ' . $table . ' ADD CONSTRAINT ' . $constraint->getQuotedName($this);
1788
1789 292
        $columnList = '(' . implode(', ', $constraint->getQuotedColumns($this)) . ')';
1790
1791 292
        $referencesClause = '';
1792 292
        if ($constraint instanceof Index) {
1793 292
            if ($constraint->isPrimary()) {
1794 292
                $query .= ' PRIMARY KEY';
1795 176
            } elseif ($constraint->isUnique()) {
1796 176
                $query .= ' UNIQUE';
1797
            } else {
1798
                throw new InvalidArgumentException(
1799 292
                    'Can only create primary or unique constraints, no common indexes with getCreateConstraintSQL().'
1800
                );
1801
            }
1802 176
        } elseif ($constraint instanceof ForeignKeyConstraint) {
1803 176
            $query .= ' FOREIGN KEY';
1804
1805 176
            $referencesClause = ' REFERENCES ' . $constraint->getQuotedForeignTableName($this) .
1806 176
                ' (' . implode(', ', $constraint->getQuotedForeignColumns($this)) . ')';
1807
        }
1808
1809 292
        $query .= ' ' . $columnList . $referencesClause;
1810
1811 292
        return $query;
1812
    }
1813
1814
    /**
1815
     * Returns the SQL to create an index on a table on this platform.
1816
     *
1817
     * @param Table|string $table The name of the table on which the index is to be created.
1818
     *
1819
     * @return string
1820
     *
1821
     * @throws InvalidArgumentException
1822
     */
1823 2238
    public function getCreateIndexSQL(Index $index, $table)
1824
    {
1825 2238
        if ($table instanceof Table) {
1826 22
            $table = $table->getQuotedName($this);
1827
        }
1828
1829 2238
        $name    = $index->getQuotedName($this);
1830 2238
        $columns = $index->getColumns();
1831
1832 2238
        if (count($columns) === 0) {
1833
            throw new InvalidArgumentException("Incomplete definition. 'columns' required.");
1834
        }
1835
1836 2238
        if ($index->isPrimary()) {
1837 396
            return $this->getCreatePrimaryKeySQL($index, $table);
1838
        }
1839
1840 1864
        $query  = 'CREATE ' . $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name . ' ON ' . $table;
1841 1864
        $query .= ' (' . $this->getIndexFieldDeclarationListSQL($index) . ')' . $this->getPartialIndexSQL($index);
1842
1843 1864
        return $query;
1844
    }
1845
1846
    /**
1847
     * Adds condition for partial index.
1848
     *
1849
     * @return string
1850
     */
1851 2676
    protected function getPartialIndexSQL(Index $index)
1852
    {
1853 2676
        if ($this->supportsPartialIndexes() && $index->hasOption('where')) {
1854 49
            return ' WHERE ' . $index->getOption('where');
1855
        }
1856
1857 2627
        return '';
1858
    }
1859
1860
    /**
1861
     * Adds additional flags for index generation.
1862
     *
1863
     * @return string
1864
     */
1865 1062
    protected function getCreateIndexSQLFlags(Index $index)
1866
    {
1867 1062
        return $index->isUnique() ? 'UNIQUE ' : '';
1868
    }
1869
1870
    /**
1871
     * Returns the SQL to create an unnamed primary key constraint.
1872
     *
1873
     * @param Table|string $table
1874
     *
1875
     * @return string
1876
     */
1877 374
    public function getCreatePrimaryKeySQL(Index $index, $table)
1878
    {
1879 374
        if ($table instanceof Table) {
1880
            $table = $table->getQuotedName($this);
1881
        }
1882
1883 374
        return 'ALTER TABLE ' . $table . ' ADD PRIMARY KEY (' . $this->getIndexFieldDeclarationListSQL($index) . ')';
1884
    }
1885
1886
    /**
1887
     * Returns the SQL to create a named schema.
1888
     *
1889
     * @param string $schemaName
1890
     *
1891
     * @return string
1892
     *
1893
     * @throws DBALException If not supported on this platform.
1894
     */
1895 154
    public function getCreateSchemaSQL($schemaName)
1896
    {
1897 154
        throw DBALException::notSupported(__METHOD__);
1898
    }
1899
1900
    /**
1901
     * Quotes a string so that it can be safely used as a table or column name,
1902
     * even if it is a reserved word of the platform. This also detects identifier
1903
     * chains separated by dot and quotes them independently.
1904
     *
1905
     * NOTE: Just because you CAN use quoted identifiers doesn't mean
1906
     * you SHOULD use them. In general, they end up causing way more
1907
     * problems than they solve.
1908
     *
1909
     * @param string $str The identifier name to be quoted.
1910
     *
1911
     * @return string The quoted identifier string.
1912
     */
1913 4876
    public function quoteIdentifier($str)
1914
    {
1915 4876
        if (strpos($str, '.') !== false) {
1916 238
            $parts = array_map([$this, 'quoteSingleIdentifier'], explode('.', $str));
1917
1918 238
            return implode('.', $parts);
1919
        }
1920
1921 4876
        return $this->quoteSingleIdentifier($str);
1922
    }
1923
1924
    /**
1925
     * Quotes a single identifier (no dot chain separation).
1926
     *
1927
     * @param string $str The identifier name to be quoted.
1928
     *
1929
     * @return string The quoted identifier string.
1930
     */
1931 8392
    public function quoteSingleIdentifier($str)
1932
    {
1933 8392
        $c = $this->getIdentifierQuoteCharacter();
1934
1935 8392
        return $c . str_replace($c, $c . $c, $str) . $c;
1936
    }
1937
1938
    /**
1939
     * Returns the SQL to create a new foreign key.
1940
     *
1941
     * @param ForeignKeyConstraint $foreignKey The foreign key constraint.
1942
     * @param Table|string         $table      The name of the table on which the foreign key is to be created.
1943
     *
1944
     * @return string
1945
     */
1946 1078
    public function getCreateForeignKeySQL(ForeignKeyConstraint $foreignKey, $table)
1947
    {
1948 1078
        if ($table instanceof Table) {
1949 42
            $table = $table->getQuotedName($this);
1950
        }
1951
1952 1078
        return 'ALTER TABLE ' . $table . ' ADD ' . $this->getForeignKeyDeclarationSQL($foreignKey);
1953
    }
1954
1955
    /**
1956
     * Gets the SQL statements for altering an existing table.
1957
     *
1958
     * This method returns an array of SQL statements, since some platforms need several statements.
1959
     *
1960
     * @return string[]
1961
     *
1962
     * @throws DBALException If not supported on this platform.
1963
     */
1964
    public function getAlterTableSQL(TableDiff $diff)
1965
    {
1966
        throw DBALException::notSupported(__METHOD__);
1967
    }
1968
1969
    /**
1970
     * @param mixed[] $columnSql
1971
     *
1972
     * @return bool
1973
     */
1974 1223
    protected function onSchemaAlterTableAddColumn(Column $column, TableDiff $diff, &$columnSql)
1975
    {
1976 1223
        if ($this->_eventManager === null) {
1977 968
            return false;
1978
        }
1979
1980 255
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableAddColumn)) {
1981 35
            return false;
1982
        }
1983
1984 220
        $eventArgs = new SchemaAlterTableAddColumnEventArgs($column, $diff, $this);
1985 220
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableAddColumn, $eventArgs);
1986
1987 220
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
1988
1989 220
        return $eventArgs->isDefaultPrevented();
1990
    }
1991
1992
    /**
1993
     * @param string[] $columnSql
1994
     *
1995
     * @return bool
1996
     */
1997 861
    protected function onSchemaAlterTableRemoveColumn(Column $column, TableDiff $diff, &$columnSql)
1998
    {
1999 861
        if ($this->_eventManager === null) {
2000 616
            return false;
2001
        }
2002
2003 245
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableRemoveColumn)) {
2004 25
            return false;
2005
        }
2006
2007 220
        $eventArgs = new SchemaAlterTableRemoveColumnEventArgs($column, $diff, $this);
2008 220
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableRemoveColumn, $eventArgs);
2009
2010 220
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
2011
2012 220
        return $eventArgs->isDefaultPrevented();
2013
    }
2014
2015
    /**
2016
     * @param string[] $columnSql
2017
     *
2018
     * @return bool
2019
     */
2020 2498
    protected function onSchemaAlterTableChangeColumn(ColumnDiff $columnDiff, TableDiff $diff, &$columnSql)
2021
    {
2022 2498
        if ($this->_eventManager === null) {
2023 1958
            return false;
2024
        }
2025
2026 540
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableChangeColumn)) {
2027 320
            return false;
2028
        }
2029
2030 220
        $eventArgs = new SchemaAlterTableChangeColumnEventArgs($columnDiff, $diff, $this);
2031 220
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableChangeColumn, $eventArgs);
2032
2033 220
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
2034
2035 220
        return $eventArgs->isDefaultPrevented();
2036
    }
2037
2038
    /**
2039
     * @param string   $oldColumnName
2040
     * @param string[] $columnSql
2041
     *
2042
     * @return bool
2043
     */
2044 948
    protected function onSchemaAlterTableRenameColumn($oldColumnName, Column $column, TableDiff $diff, &$columnSql)
2045
    {
2046 948
        if ($this->_eventManager === null) {
2047 704
            return false;
2048
        }
2049
2050 244
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableRenameColumn)) {
2051 24
            return false;
2052
        }
2053
2054 220
        $eventArgs = new SchemaAlterTableRenameColumnEventArgs($oldColumnName, $column, $diff, $this);
2055 220
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableRenameColumn, $eventArgs);
2056
2057 220
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
2058
2059 220
        return $eventArgs->isDefaultPrevented();
2060
    }
2061
2062
    /**
2063
     * @param string[] $sql
2064
     *
2065
     * @return bool
2066
     */
2067 5007
    protected function onSchemaAlterTable(TableDiff $diff, &$sql)
2068
    {
2069 5007
        if ($this->_eventManager === null) {
2070 4334
            return false;
2071
        }
2072
2073 673
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTable)) {
2074 453
            return false;
2075
        }
2076
2077 220
        $eventArgs = new SchemaAlterTableEventArgs($diff, $this);
2078 220
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTable, $eventArgs);
2079
2080 220
        $sql = array_merge($sql, $eventArgs->getSql());
2081
2082 220
        return $eventArgs->isDefaultPrevented();
2083
    }
2084
2085
    /**
2086
     * @return string[]
2087
     */
2088 4675
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
2089
    {
2090 4675
        $tableName = $diff->getName($this)->getQuotedName($this);
2091
2092 4675
        $sql = [];
2093 4675
        if ($this->supportsForeignKeyConstraints()) {
2094 4675
            foreach ($diff->removedForeignKeys as $foreignKey) {
2095 328
                $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
2096
            }
2097
2098 4675
            foreach ($diff->changedForeignKeys as $foreignKey) {
2099 264
                $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
2100
            }
2101
        }
2102
2103 4675
        foreach ($diff->removedIndexes as $index) {
2104 220
            $sql[] = $this->getDropIndexSQL($index, $tableName);
2105
        }
2106
2107 4675
        foreach ($diff->changedIndexes as $index) {
2108 392
            $sql[] = $this->getDropIndexSQL($index, $tableName);
2109
        }
2110
2111 4675
        return $sql;
2112
    }
2113
2114
    /**
2115
     * @return string[]
2116
     */
2117 4675
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff)
2118
    {
2119 4675
        $sql     = [];
2120 4675
        $newName = $diff->getNewName();
2121
2122 4675
        if ($newName !== false) {
2123 399
            $tableName = $newName->getQuotedName($this);
2124
        } else {
2125 4277
            $tableName = $diff->getName($this)->getQuotedName($this);
2126
        }
2127
2128 4675
        if ($this->supportsForeignKeyConstraints()) {
2129 4675
            foreach ($diff->addedForeignKeys as $foreignKey) {
2130 304
                $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
2131
            }
2132
2133 4675
            foreach ($diff->changedForeignKeys as $foreignKey) {
2134 264
                $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
2135
            }
2136
        }
2137
2138 4675
        foreach ($diff->addedIndexes as $index) {
2139 86
            $sql[] = $this->getCreateIndexSQL($index, $tableName);
2140
        }
2141
2142 4675
        foreach ($diff->changedIndexes as $index) {
2143 392
            $sql[] = $this->getCreateIndexSQL($index, $tableName);
2144
        }
2145
2146 4675
        foreach ($diff->renamedIndexes as $oldIndexName => $index) {
2147 1030
            $oldIndexName = new Identifier($oldIndexName);
2148 1030
            $sql          = array_merge(
2149 1030
                $sql,
2150 1030
                $this->getRenameIndexSQL($oldIndexName->getQuotedName($this), $index, $tableName)
2151
            );
2152
        }
2153
2154 4675
        return $sql;
2155
    }
2156
2157
    /**
2158
     * Returns the SQL for renaming an index on a table.
2159
     *
2160
     * @param string $oldIndexName The name of the index to rename from.
2161
     * @param Index  $index        The definition of the index to rename to.
2162
     * @param string $tableName    The table to rename the given index on.
2163
     *
2164
     * @return string[] The sequence of SQL statements for renaming the given index.
2165
     */
2166 236
    protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
2167
    {
2168
        return [
2169 236
            $this->getDropIndexSQL($oldIndexName, $tableName),
2170 236
            $this->getCreateIndexSQL($index, $tableName),
2171
        ];
2172
    }
2173
2174
    /**
2175
     * Common code for alter table statement generation that updates the changed Index and Foreign Key definitions.
2176
     *
2177
     * @deprecated
2178
     *
2179
     * @return string[]
2180
     */
2181
    protected function _getAlterTableIndexForeignKeySQL(TableDiff $diff)
2182
    {
2183
        return array_merge($this->getPreAlterTableIndexForeignKeySQL($diff), $this->getPostAlterTableIndexForeignKeySQL($diff));
2184
    }
2185
2186
    /**
2187
     * Gets declaration of a number of fields in bulk.
2188
     *
2189
     * @param mixed[][] $fields A multidimensional associative array.
2190
     *                          The first dimension determines the field name, while the second
2191
     *                          dimension is keyed with the name of the properties
2192
     *                          of the field being declared as array indexes. Currently, the types
2193
     *                          of supported field properties are as follows:
2194
     *
2195
     *      length
2196
     *          Integer value that determines the maximum length of the text
2197
     *          field. If this argument is missing the field should be
2198
     *          declared to have the longest length allowed by the DBMS.
2199
     *
2200
     *      default
2201
     *          Text value to be used as default for this field.
2202
     *
2203
     *      notnull
2204
     *          Boolean flag that indicates whether this field is constrained
2205
     *          to not be set to null.
2206
     *      charset
2207
     *          Text value with the default CHARACTER SET for this field.
2208
     *      collation
2209
     *          Text value with the default COLLATION for this field.
2210
     *      unique
2211
     *          unique constraint
2212
     *
2213
     * @return string
2214
     */
2215 7055
    public function getColumnDeclarationListSQL(array $fields)
2216
    {
2217 7055
        $queryFields = [];
2218
2219 7055
        foreach ($fields as $fieldName => $field) {
2220 7055
            $queryFields[] = $this->getColumnDeclarationSQL($fieldName, $field);
2221
        }
2222
2223 7055
        return implode(', ', $queryFields);
2224
    }
2225
2226
    /**
2227
     * Obtains DBMS specific SQL code portion needed to declare a generic type
2228
     * field to be used in statements like CREATE TABLE.
2229
     *
2230
     * @param string  $name  The name the field to be declared.
2231
     * @param mixed[] $field An associative array with the name of the properties
2232
     *                       of the field being declared as array indexes. Currently, the types
2233
     *                       of supported field properties are as follows:
2234
     *
2235
     *      length
2236
     *          Integer value that determines the maximum length of the text
2237
     *          field. If this argument is missing the field should be
2238
     *          declared to have the longest length allowed by the DBMS.
2239
     *
2240
     *      default
2241
     *          Text value to be used as default for this field.
2242
     *
2243
     *      notnull
2244
     *          Boolean flag that indicates whether this field is constrained
2245
     *          to not be set to null.
2246
     *      charset
2247
     *          Text value with the default CHARACTER SET for this field.
2248
     *      collation
2249
     *          Text value with the default COLLATION for this field.
2250
     *      unique
2251
     *          unique constraint
2252
     *      check
2253
     *          column check constraint
2254
     *      columnDefinition
2255
     *          a string that defines the complete column
2256
     *
2257
     * @return string DBMS specific SQL code portion that should be used to declare the column.
2258
     */
2259 7600
    public function getColumnDeclarationSQL($name, array $field)
2260
    {
2261 7600
        if (isset($field['columnDefinition'])) {
2262 190
            $columnDef = $this->getCustomTypeDeclarationSQL($field);
2263
        } else {
2264 7424
            $default = $this->getDefaultValueDeclarationSQL($field);
2265
2266 7424
            $charset = ! empty($field['charset']) ?
2267 7424
                ' ' . $this->getColumnCharsetDeclarationSQL($field['charset']) : '';
2268
2269 7424
            $collation = ! empty($field['collation']) ?
2270 7424
                ' ' . $this->getColumnCollationDeclarationSQL($field['collation']) : '';
2271
2272 7424
            $notnull = ! empty($field['notnull']) ? ' NOT NULL' : '';
2273
2274 7424
            $unique = ! empty($field['unique']) ?
2275 7424
                ' ' . $this->getUniqueFieldDeclarationSQL() : '';
2276
2277 7424
            $check = ! empty($field['check']) ? ' ' . $field['check'] : '';
2278
2279 7424
            $typeDecl  = $field['type']->getSQLDeclaration($field, $this);
2280 7424
            $columnDef = $typeDecl . $charset . $default . $notnull . $unique . $check . $collation;
2281
2282 7424
            if ($this->supportsInlineColumnComments() && isset($field['comment']) && $field['comment'] !== '') {
2283 928
                $columnDef .= ' ' . $this->getInlineColumnCommentSQL($field['comment']);
2284
            }
2285
        }
2286
2287 7600
        return $name . ' ' . $columnDef;
2288
    }
2289
2290
    /**
2291
     * Returns the SQL snippet that declares a floating point column of arbitrary precision.
2292
     *
2293
     * @param mixed[] $columnDef
2294
     *
2295
     * @return string
2296
     */
2297 1834
    public function getDecimalTypeDeclarationSQL(array $columnDef)
2298
    {
2299 1834
        $columnDef['precision'] = ! isset($columnDef['precision']) || empty($columnDef['precision'])
2300 1834
            ? 10 : $columnDef['precision'];
2301 1834
        $columnDef['scale']     = ! isset($columnDef['scale']) || empty($columnDef['scale'])
2302 1834
            ? 0 : $columnDef['scale'];
2303
2304 1834
        return 'NUMERIC(' . $columnDef['precision'] . ', ' . $columnDef['scale'] . ')';
2305
    }
2306
2307
    /**
2308
     * Obtains DBMS specific SQL code portion needed to set a default value
2309
     * declaration to be used in statements like CREATE TABLE.
2310
     *
2311
     * @param mixed[] $field The field definition array.
2312
     *
2313
     * @return string DBMS specific SQL code portion needed to set a default value.
2314
     */
2315 9091
    public function getDefaultValueDeclarationSQL($field)
2316
    {
2317 9091
        if (! isset($field['default'])) {
2318 7658
            return empty($field['notnull']) ? ' DEFAULT NULL' : '';
2319
        }
2320
2321 1877
        $default = $field['default'];
2322
2323 1877
        if (! isset($field['type'])) {
2324 88
            return " DEFAULT '" . $default . "'";
2325
        }
2326
2327 1789
        $type = $field['type'];
2328
2329 1789
        if ($type instanceof Types\PhpIntegerMappingType) {
2330 512
            return ' DEFAULT ' . $default;
2331
        }
2332
2333 1361
        if ($type instanceof Types\PhpDateTimeMappingType && $default === $this->getCurrentTimestampSQL()) {
2334 270
            return ' DEFAULT ' . $this->getCurrentTimestampSQL();
2335
        }
2336
2337 1107
        if ($type instanceof Types\TimeType && $default === $this->getCurrentTimeSQL()) {
2338 12
            return ' DEFAULT ' . $this->getCurrentTimeSQL();
2339
        }
2340
2341 1099
        if ($type instanceof Types\DateType && $default === $this->getCurrentDateSQL()) {
2342 234
            return ' DEFAULT ' . $this->getCurrentDateSQL();
2343
        }
2344
2345 865
        if ($type instanceof Types\BooleanType) {
2346 248
            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

2346
            return " DEFAULT '" . /** @scrutinizer ignore-type */ $this->convertBooleans($default) . "'";
Loading history...
2347
        }
2348
2349 838
        return ' DEFAULT ' . $this->quoteStringLiteral($default);
2350
    }
2351
2352
    /**
2353
     * Obtains DBMS specific SQL code portion needed to set a CHECK constraint
2354
     * declaration to be used in statements like CREATE TABLE.
2355
     *
2356
     * @param string[]|mixed[][] $definition The check definition.
2357
     *
2358
     * @return string DBMS specific SQL code portion needed to set a CHECK constraint.
2359
     */
2360 1579
    public function getCheckDeclarationSQL(array $definition)
2361
    {
2362 1579
        $constraints = [];
2363 1579
        foreach ($definition as $field => $def) {
2364 1579
            if (is_string($def)) {
2365
                $constraints[] = 'CHECK (' . $def . ')';
2366
            } else {
2367 1579
                if (isset($def['min'])) {
2368 44
                    $constraints[] = 'CHECK (' . $field . ' >= ' . $def['min'] . ')';
2369
                }
2370
2371 1579
                if (isset($def['max'])) {
2372 44
                    $constraints[] = 'CHECK (' . $field . ' <= ' . $def['max'] . ')';
2373
                }
2374
            }
2375
        }
2376
2377 1579
        return implode(', ', $constraints);
2378
    }
2379
2380
    /**
2381
     * Obtains DBMS specific SQL code portion needed to set a unique
2382
     * constraint declaration to be used in statements like CREATE TABLE.
2383
     *
2384
     * @param string           $name       The name of the unique constraint.
2385
     * @param UniqueConstraint $constraint The unique constraint definition.
2386
     *
2387
     * @return string DBMS specific SQL code portion needed to set a constraint.
2388
     *
2389
     * @throws InvalidArgumentException
2390
     */
2391 484
    public function getUniqueConstraintDeclarationSQL($name, UniqueConstraint $constraint)
2392
    {
2393 484
        $columns = $constraint->getQuotedColumns($this);
2394 484
        $name    = new Identifier($name);
2395
2396 484
        if (count($columns) === 0) {
2397 22
            throw new InvalidArgumentException("Incomplete definition. 'columns' required.");
2398
        }
2399
2400 462
        $constraintFlags = array_merge(['UNIQUE'], array_map('strtoupper', $constraint->getFlags()));
2401 462
        $constraintName  = $name->getQuotedName($this);
2402 462
        $columnListNames = $this->getIndexFieldDeclarationListSQL($columns);
2403
2404 462
        return sprintf('CONSTRAINT %s %s (%s)', $constraintName, implode(' ', $constraintFlags), $columnListNames);
2405
    }
2406
2407
    /**
2408
     * Obtains DBMS specific SQL code portion needed to set an index
2409
     * declaration to be used in statements like CREATE TABLE.
2410
     *
2411
     * @param string $name  The name of the index.
2412
     * @param Index  $index The index definition.
2413
     *
2414
     * @return string DBMS specific SQL code portion needed to set an index.
2415
     *
2416
     * @throws InvalidArgumentException
2417
     */
2418 1020
    public function getIndexDeclarationSQL($name, Index $index)
2419
    {
2420 1020
        $columns = $index->getColumns();
2421 1020
        $name    = new Identifier($name);
2422
2423 1020
        if (count($columns) === 0) {
2424
            throw new InvalidArgumentException("Incomplete definition. 'columns' required.");
2425
        }
2426
2427 1020
        return $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name->getQuotedName($this)
2428 1020
            . ' (' . $this->getIndexFieldDeclarationListSQL($index) . ')' . $this->getPartialIndexSQL($index);
2429
    }
2430
2431
    /**
2432
     * Obtains SQL code portion needed to create a custom column,
2433
     * e.g. when a field has the "columnDefinition" keyword.
2434
     * Only "AUTOINCREMENT" and "PRIMARY KEY" are added if appropriate.
2435
     *
2436
     * @param mixed[] $columnDef
2437
     *
2438
     * @return string
2439
     */
2440 234
    public function getCustomTypeDeclarationSQL(array $columnDef)
2441
    {
2442 234
        return $columnDef['columnDefinition'];
2443
    }
2444
2445
    /**
2446
     * Obtains DBMS specific SQL code portion needed to set an index
2447
     * declaration to be used in statements like CREATE TABLE.
2448
     *
2449
     * @param mixed[]|Index $columnsOrIndex array declaration is deprecated, prefer passing Index to this method
2450
     */
2451 3578
    public function getIndexFieldDeclarationListSQL($columnsOrIndex) : string
2452
    {
2453 3578
        if ($columnsOrIndex instanceof Index) {
2454 3160
            return implode(', ', $columnsOrIndex->getQuotedColumns($this));
2455
        }
2456
2457 660
        if (! is_array($columnsOrIndex)) {
0 ignored issues
show
introduced by
The condition is_array($columnsOrIndex) is always true.
Loading history...
2458
            throw new InvalidArgumentException('Fields argument should be an Index or array.');
2459
        }
2460
2461 660
        $ret = [];
2462
2463 660
        foreach ($columnsOrIndex as $column => $definition) {
2464 660
            if (is_array($definition)) {
2465
                $ret[] = $column;
2466
            } else {
2467 660
                $ret[] = $definition;
2468
            }
2469
        }
2470
2471 660
        return implode(', ', $ret);
2472
    }
2473
2474
    /**
2475
     * Returns the required SQL string that fits between CREATE ... TABLE
2476
     * to create the table as a temporary table.
2477
     *
2478
     * Should be overridden in driver classes to return the correct string for the
2479
     * specific database type.
2480
     *
2481
     * The default is to return the string "TEMPORARY" - this will result in a
2482
     * SQL error for any database that does not support temporary tables, or that
2483
     * requires a different SQL command from "CREATE TEMPORARY TABLE".
2484
     *
2485
     * @return string The string required to be placed between "CREATE" and "TABLE"
2486
     *                to generate a temporary table, if possible.
2487
     */
2488
    public function getTemporaryTableSQL()
2489
    {
2490
        return 'TEMPORARY';
2491
    }
2492
2493
    /**
2494
     * Some vendors require temporary table names to be qualified specially.
2495
     *
2496
     * @param string $tableName
2497
     *
2498
     * @return string
2499
     */
2500 34
    public function getTemporaryTableName($tableName)
2501
    {
2502 34
        return $tableName;
2503
    }
2504
2505
    /**
2506
     * Obtain DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
2507
     * of a field declaration to be used in statements like CREATE TABLE.
2508
     *
2509
     * @return string DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
2510
     *                of a field declaration.
2511
     */
2512 1388
    public function getForeignKeyDeclarationSQL(ForeignKeyConstraint $foreignKey)
2513
    {
2514 1388
        $sql  = $this->getForeignKeyBaseDeclarationSQL($foreignKey);
2515 1322
        $sql .= $this->getAdvancedForeignKeyOptionsSQL($foreignKey);
2516
2517 1322
        return $sql;
2518
    }
2519
2520
    /**
2521
     * Returns the FOREIGN KEY query section dealing with non-standard options
2522
     * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
2523
     *
2524
     * @param ForeignKeyConstraint $foreignKey The foreign key definition.
2525
     *
2526
     * @return string
2527
     */
2528 1230
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey)
2529
    {
2530 1230
        $query = '';
2531 1230
        if ($this->supportsForeignKeyOnUpdate() && $foreignKey->hasOption('onUpdate')) {
2532 22
            $query .= ' ON UPDATE ' . $this->getForeignKeyReferentialActionSQL($foreignKey->getOption('onUpdate'));
2533
        }
2534
2535 1230
        if ($foreignKey->hasOption('onDelete')) {
2536 86
            $query .= ' ON DELETE ' . $this->getForeignKeyReferentialActionSQL($foreignKey->getOption('onDelete'));
2537
        }
2538
2539 1230
        return $query;
2540
    }
2541
2542
    /**
2543
     * Returns the given referential action in uppercase if valid, otherwise throws an exception.
2544
     *
2545
     * @param string $action The foreign key referential action.
2546
     *
2547
     * @return string
2548
     *
2549
     * @throws InvalidArgumentException If unknown referential action given.
2550
     */
2551 1428
    public function getForeignKeyReferentialActionSQL($action)
2552
    {
2553 1428
        $upper = strtoupper($action);
2554 128
        switch ($upper) {
2555 1428
            case 'CASCADE':
2556 973
            case 'SET NULL':
2557 753
            case 'NO ACTION':
2558 577
            case 'RESTRICT':
2559 401
            case 'SET DEFAULT':
2560 1230
                return $upper;
2561
2562
            default:
2563 198
                throw new InvalidArgumentException('Invalid foreign key action: ' . $upper);
2564
        }
2565
    }
2566
2567
    /**
2568
     * Obtains DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
2569
     * of a field declaration to be used in statements like CREATE TABLE.
2570
     *
2571
     * @return string
2572
     *
2573
     * @throws InvalidArgumentException
2574
     */
2575 1190
    public function getForeignKeyBaseDeclarationSQL(ForeignKeyConstraint $foreignKey)
2576
    {
2577 1190
        $sql = '';
2578 1190
        if (strlen($foreignKey->getName()) > 0) {
2579 992
            $sql .= 'CONSTRAINT ' . $foreignKey->getQuotedName($this) . ' ';
2580
        }
2581
2582 1190
        $sql .= 'FOREIGN KEY (';
2583
2584 1190
        if (count($foreignKey->getLocalColumns()) === 0) {
2585
            throw new InvalidArgumentException("Incomplete definition. 'local' required.");
2586
        }
2587
2588 1190
        if (count($foreignKey->getForeignColumns()) === 0) {
2589
            throw new InvalidArgumentException("Incomplete definition. 'foreign' required.");
2590
        }
2591
2592 1190
        if (strlen($foreignKey->getForeignTableName()) === 0) {
2593
            throw new InvalidArgumentException("Incomplete definition. 'foreignTable' required.");
2594
        }
2595
2596 1190
        return $sql . implode(', ', $foreignKey->getQuotedLocalColumns($this))
2597 1190
            . ') REFERENCES '
2598 1190
            . $foreignKey->getQuotedForeignTableName($this) . ' ('
2599 1190
            . implode(', ', $foreignKey->getQuotedForeignColumns($this)) . ')';
2600
    }
2601
2602
    /**
2603
     * Obtains DBMS specific SQL code portion needed to set the UNIQUE constraint
2604
     * of a field declaration to be used in statements like CREATE TABLE.
2605
     *
2606
     * @return string DBMS specific SQL code portion needed to set the UNIQUE constraint
2607
     *                of a field declaration.
2608
     */
2609
    public function getUniqueFieldDeclarationSQL()
2610
    {
2611
        return 'UNIQUE';
2612
    }
2613
2614
    /**
2615
     * Obtains DBMS specific SQL code portion needed to set the CHARACTER SET
2616
     * of a field declaration to be used in statements like CREATE TABLE.
2617
     *
2618
     * @param string $charset The name of the charset.
2619
     *
2620
     * @return string DBMS specific SQL code portion needed to set the CHARACTER SET
2621
     *                of a field declaration.
2622
     */
2623
    public function getColumnCharsetDeclarationSQL($charset)
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

2623
    public function getColumnCharsetDeclarationSQL(/** @scrutinizer ignore-unused */ $charset)

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...
2624
    {
2625
        return '';
2626
    }
2627
2628
    /**
2629
     * Obtains DBMS specific SQL code portion needed to set the COLLATION
2630
     * of a field declaration to be used in statements like CREATE TABLE.
2631
     *
2632
     * @param string $collation The name of the collation.
2633
     *
2634
     * @return string DBMS specific SQL code portion needed to set the COLLATION
2635
     *                of a field declaration.
2636
     */
2637 95
    public function getColumnCollationDeclarationSQL($collation)
2638
    {
2639 95
        return $this->supportsColumnCollation() ? 'COLLATE ' . $collation : '';
2640
    }
2641
2642
    /**
2643
     * Whether the platform prefers sequences for ID generation.
2644
     * Subclasses should override this method to return TRUE if they prefer sequences.
2645
     *
2646
     * @return bool
2647
     */
2648 44
    public function prefersSequences()
2649
    {
2650 44
        return false;
2651
    }
2652
2653
    /**
2654
     * Whether the platform prefers identity columns (eg. autoincrement) for ID generation.
2655
     * Subclasses should override this method to return TRUE if they prefer identity columns.
2656
     *
2657
     * @return bool
2658
     */
2659 66
    public function prefersIdentityColumns()
2660
    {
2661 66
        return false;
2662
    }
2663
2664
    /**
2665
     * Some platforms need the boolean values to be converted.
2666
     *
2667
     * The default conversion in this implementation converts to integers (false => 0, true => 1).
2668
     *
2669
     * Note: if the input is not a boolean the original input might be returned.
2670
     *
2671
     * There are two contexts when converting booleans: Literals and Prepared Statements.
2672
     * This method should handle the literal case
2673
     *
2674
     * @param mixed $item A boolean or an array of them.
2675
     *
2676
     * @return mixed A boolean database value or an array of them.
2677
     */
2678 312
    public function convertBooleans($item)
2679
    {
2680 312
        if (is_array($item)) {
2681
            foreach ($item as $k => $value) {
2682
                if (! is_bool($value)) {
2683
                    continue;
2684
                }
2685
2686
                $item[$k] = (int) $value;
2687
            }
2688 312
        } elseif (is_bool($item)) {
2689 290
            $item = (int) $item;
2690
        }
2691
2692 312
        return $item;
2693
    }
2694
2695
    /**
2696
     * Some platforms have boolean literals that needs to be correctly converted
2697
     *
2698
     * The default conversion tries to convert value into bool "(bool)$item"
2699
     *
2700
     * @param mixed $item
2701
     *
2702
     * @return bool|null
2703
     */
2704 484
    public function convertFromBoolean($item)
2705
    {
2706 484
        return $item === null ? null: (bool) $item;
2707
    }
2708
2709
    /**
2710
     * This method should handle the prepared statements case. When there is no
2711
     * distinction, it's OK to use the same method.
2712
     *
2713
     * Note: if the input is not a boolean the original input might be returned.
2714
     *
2715
     * @param mixed $item A boolean or an array of them.
2716
     *
2717
     * @return mixed A boolean database value or an array of them.
2718
     */
2719 100
    public function convertBooleansToDatabaseValue($item)
2720
    {
2721 100
        return $this->convertBooleans($item);
2722
    }
2723
2724
    /**
2725
     * Returns the SQL specific for the platform to get the current date.
2726
     *
2727
     * @return string
2728
     */
2729 209
    public function getCurrentDateSQL()
2730
    {
2731 209
        return 'CURRENT_DATE';
2732
    }
2733
2734
    /**
2735
     * Returns the SQL specific for the platform to get the current time.
2736
     *
2737
     * @return string
2738
     */
2739 19
    public function getCurrentTimeSQL()
2740
    {
2741 19
        return 'CURRENT_TIME';
2742
    }
2743
2744
    /**
2745
     * Returns the SQL specific for the platform to get the current timestamp
2746
     *
2747
     * @return string
2748
     */
2749 262
    public function getCurrentTimestampSQL()
2750
    {
2751 262
        return 'CURRENT_TIMESTAMP';
2752
    }
2753
2754
    /**
2755
     * Returns the SQL for a given transaction isolation level Connection constant.
2756
     *
2757
     * @param int $level
2758
     *
2759
     * @return string
2760
     *
2761
     * @throws InvalidArgumentException
2762
     */
2763 132
    protected function _getTransactionIsolationLevelSQL($level)
2764
    {
2765 12
        switch ($level) {
2766 120
            case TransactionIsolationLevel::READ_UNCOMMITTED:
2767 132
                return 'READ UNCOMMITTED';
2768
2769 120
            case TransactionIsolationLevel::READ_COMMITTED:
2770 132
                return 'READ COMMITTED';
2771
2772 120
            case TransactionIsolationLevel::REPEATABLE_READ:
2773 132
                return 'REPEATABLE READ';
2774
2775 120
            case TransactionIsolationLevel::SERIALIZABLE:
2776 132
                return 'SERIALIZABLE';
2777
2778
            default:
2779
                throw new InvalidArgumentException('Invalid isolation level:' . $level);
2780
        }
2781
    }
2782
2783
    /**
2784
     * @return string
2785
     *
2786
     * @throws DBALException If not supported on this platform.
2787
     */
2788 2
    public function getListDatabasesSQL()
2789
    {
2790 2
        throw DBALException::notSupported(__METHOD__);
2791
    }
2792
2793
    /**
2794
     * Returns the SQL statement for retrieving the namespaces defined in the database.
2795
     *
2796
     * @return string
2797
     *
2798
     * @throws DBALException If not supported on this platform.
2799
     */
2800
    public function getListNamespacesSQL()
2801
    {
2802
        throw DBALException::notSupported(__METHOD__);
2803
    }
2804
2805
    /**
2806
     * @param string $database
2807
     *
2808
     * @return string
2809
     *
2810
     * @throws DBALException If not supported on this platform.
2811
     */
2812
    public function getListSequencesSQL($database)
2813
    {
2814
        throw DBALException::notSupported(__METHOD__);
2815
    }
2816
2817
    /**
2818
     * @param string $table
2819
     *
2820
     * @return string
2821
     *
2822
     * @throws DBALException If not supported on this platform.
2823
     */
2824
    public function getListTableConstraintsSQL($table)
2825
    {
2826
        throw DBALException::notSupported(__METHOD__);
2827
    }
2828
2829
    /**
2830
     * @param string      $table
2831
     * @param string|null $database
2832
     *
2833
     * @return string
2834
     *
2835
     * @throws DBALException If not supported on this platform.
2836
     */
2837
    public function getListTableColumnsSQL($table, $database = null)
2838
    {
2839
        throw DBALException::notSupported(__METHOD__);
2840
    }
2841
2842
    /**
2843
     * @return string
2844
     *
2845
     * @throws DBALException If not supported on this platform.
2846
     */
2847
    public function getListTablesSQL()
2848
    {
2849
        throw DBALException::notSupported(__METHOD__);
2850
    }
2851
2852
    /**
2853
     * @return string
2854
     *
2855
     * @throws DBALException If not supported on this platform.
2856
     */
2857
    public function getListUsersSQL()
2858
    {
2859
        throw DBALException::notSupported(__METHOD__);
2860
    }
2861
2862
    /**
2863
     * Returns the SQL to list all views of a database or user.
2864
     *
2865
     * @param string $database
2866
     *
2867
     * @return string
2868
     *
2869
     * @throws DBALException If not supported on this platform.
2870
     */
2871
    public function getListViewsSQL($database)
2872
    {
2873
        throw DBALException::notSupported(__METHOD__);
2874
    }
2875
2876
    /**
2877
     * Returns the list of indexes for the current database.
2878
     *
2879
     * The current database parameter is optional but will always be passed
2880
     * when using the SchemaManager API and is the database the given table is in.
2881
     *
2882
     * Attention: Some platforms only support currentDatabase when they
2883
     * are connected with that database. Cross-database information schema
2884
     * requests may be impossible.
2885
     *
2886
     * @param string $table
2887
     * @param string $currentDatabase
2888
     *
2889
     * @return string
2890
     *
2891
     * @throws DBALException If not supported on this platform.
2892
     */
2893
    public function getListTableIndexesSQL($table, $currentDatabase = null)
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

2893
    public function getListTableIndexesSQL($table, /** @scrutinizer ignore-unused */ $currentDatabase = null)

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...
2894
    {
2895
        throw DBALException::notSupported(__METHOD__);
2896
    }
2897
2898
    /**
2899
     * @param string $table
2900
     *
2901
     * @return string
2902
     *
2903
     * @throws DBALException If not supported on this platform.
2904
     */
2905
    public function getListTableForeignKeysSQL($table)
2906
    {
2907
        throw DBALException::notSupported(__METHOD__);
2908
    }
2909
2910
    /**
2911
     * @param string $name
2912
     * @param string $sql
2913
     *
2914
     * @return string
2915
     *
2916
     * @throws DBALException If not supported on this platform.
2917
     */
2918
    public function getCreateViewSQL($name, $sql)
2919
    {
2920
        throw DBALException::notSupported(__METHOD__);
2921
    }
2922
2923
    /**
2924
     * @param string $name
2925
     *
2926
     * @return string
2927
     *
2928
     * @throws DBALException If not supported on this platform.
2929
     */
2930
    public function getDropViewSQL($name)
2931
    {
2932
        throw DBALException::notSupported(__METHOD__);
2933
    }
2934
2935
    /**
2936
     * Returns the SQL snippet to drop an existing sequence.
2937
     *
2938
     * @param Sequence|string $sequence
2939
     *
2940
     * @return string
2941
     *
2942
     * @throws DBALException If not supported on this platform.
2943
     */
2944
    public function getDropSequenceSQL($sequence)
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

2944
    public function getDropSequenceSQL(/** @scrutinizer ignore-unused */ $sequence)

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...
2945
    {
2946
        throw DBALException::notSupported(__METHOD__);
2947
    }
2948
2949
    /**
2950
     * @param string $sequenceName
2951
     *
2952
     * @return string
2953
     *
2954
     * @throws DBALException If not supported on this platform.
2955
     */
2956
    public function getSequenceNextValSQL($sequenceName)
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

2956
    public function getSequenceNextValSQL(/** @scrutinizer ignore-unused */ $sequenceName)

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...
2957
    {
2958
        throw DBALException::notSupported(__METHOD__);
2959
    }
2960
2961
    /**
2962
     * Returns the SQL to create a new database.
2963
     *
2964
     * @param string $database The name of the database that should be created.
2965
     *
2966
     * @return string
2967
     *
2968
     * @throws DBALException If not supported on this platform.
2969
     */
2970 22
    public function getCreateDatabaseSQL($database)
2971
    {
2972 22
        throw DBALException::notSupported(__METHOD__);
2973
    }
2974
2975
    /**
2976
     * Returns the SQL to set the transaction isolation level.
2977
     *
2978
     * @param int $level
2979
     *
2980
     * @return string
2981
     *
2982
     * @throws DBALException If not supported on this platform.
2983
     */
2984
    public function getSetTransactionIsolationSQL($level)
2985
    {
2986
        throw DBALException::notSupported(__METHOD__);
2987
    }
2988
2989
    /**
2990
     * Obtains DBMS specific SQL to be used to create datetime fields in
2991
     * statements like CREATE TABLE.
2992
     *
2993
     * @param mixed[] $fieldDeclaration
2994
     *
2995
     * @return string
2996
     *
2997
     * @throws DBALException If not supported on this platform.
2998
     */
2999
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
3000
    {
3001
        throw DBALException::notSupported(__METHOD__);
3002
    }
3003
3004
    /**
3005
     * Obtains DBMS specific SQL to be used to create datetime with timezone offset fields.
3006
     *
3007
     * @param mixed[] $fieldDeclaration
3008
     *
3009
     * @return string
3010
     */
3011 210
    public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration)
3012
    {
3013 210
        return $this->getDateTimeTypeDeclarationSQL($fieldDeclaration);
3014
    }
3015
3016
    /**
3017
     * Obtains DBMS specific SQL to be used to create date fields in statements
3018
     * like CREATE TABLE.
3019
     *
3020
     * @param mixed[] $fieldDeclaration
3021
     *
3022
     * @return string
3023
     *
3024
     * @throws DBALException If not supported on this platform.
3025
     */
3026
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
3027
    {
3028
        throw DBALException::notSupported(__METHOD__);
3029
    }
3030
3031
    /**
3032
     * Obtains DBMS specific SQL to be used to create time fields in statements
3033
     * like CREATE TABLE.
3034
     *
3035
     * @param mixed[] $fieldDeclaration
3036
     *
3037
     * @return string
3038
     *
3039
     * @throws DBALException If not supported on this platform.
3040
     */
3041
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
3042
    {
3043
        throw DBALException::notSupported(__METHOD__);
3044
    }
3045
3046
    /**
3047
     * @param mixed[] $fieldDeclaration
3048
     *
3049
     * @return string
3050
     */
3051 1079
    public function getFloatDeclarationSQL(array $fieldDeclaration)
3052
    {
3053 1079
        return 'DOUBLE PRECISION';
3054
    }
3055
3056
    /**
3057
     * Gets the default transaction isolation level of the platform.
3058
     *
3059
     * @see TransactionIsolationLevel
3060
     *
3061
     * @return int The default isolation level.
3062
     */
3063
    public function getDefaultTransactionIsolationLevel()
3064
    {
3065
        return TransactionIsolationLevel::READ_COMMITTED;
3066
    }
3067
3068
    /* supports*() methods */
3069
3070
    /**
3071
     * Whether the platform supports sequences.
3072
     *
3073
     * @return bool
3074
     */
3075 118
    public function supportsSequences()
3076
    {
3077 118
        return false;
3078
    }
3079
3080
    /**
3081
     * Whether the platform supports identity columns.
3082
     *
3083
     * Identity columns are columns that receive an auto-generated value from the
3084
     * database on insert of a row.
3085
     *
3086
     * @return bool
3087
     */
3088 26
    public function supportsIdentityColumns()
3089
    {
3090 26
        return false;
3091
    }
3092
3093
    /**
3094
     * Whether the platform emulates identity columns through sequences.
3095
     *
3096
     * Some platforms that do not support identity columns natively
3097
     * but support sequences can emulate identity columns by using
3098
     * sequences.
3099
     *
3100
     * @return bool
3101
     */
3102 169
    public function usesSequenceEmulatedIdentityColumns()
3103
    {
3104 169
        return false;
3105
    }
3106
3107
    /**
3108
     * Gets the sequence name prefix based on table information.
3109
     */
3110 440
    public function getSequencePrefix(string $tableName, ?string $schemaName = null) : string
3111
    {
3112 440
        if ($schemaName === null) {
3113 220
            return $tableName;
3114
        }
3115
3116
        // Prepend the schema name to the table name if there is one
3117 220
        return ! $this->supportsSchemas() && $this->canEmulateSchemas()
3118 22
            ? $schemaName . '__' . $tableName
3119 220
            : $schemaName . '.' . $tableName;
3120
    }
3121
3122
    /**
3123
     * Returns the name of the sequence for a particular identity column in a particular table.
3124
     *
3125
     * @see usesSequenceEmulatedIdentityColumns
3126
     *
3127
     * @param string $tableName  The name of the table to return the sequence name for.
3128
     * @param string $columnName The name of the identity column in the table to return the sequence name for.
3129
     *
3130
     * @return string
3131
     *
3132
     * @throws DBALException If not supported on this platform.
3133
     */
3134 154
    public function getIdentitySequenceName($tableName, $columnName)
3135
    {
3136 154
        throw DBALException::notSupported(__METHOD__);
3137
    }
3138
3139
    /**
3140
     * Whether the platform supports indexes.
3141
     *
3142
     * @return bool
3143
     */
3144 22
    public function supportsIndexes()
3145
    {
3146 22
        return true;
3147
    }
3148
3149
    /**
3150
     * Whether the platform supports partial indexes.
3151
     *
3152
     * @return bool
3153
     */
3154 2268
    public function supportsPartialIndexes()
3155
    {
3156 2268
        return false;
3157
    }
3158
3159
    /**
3160
     * Whether the platform supports indexes with column length definitions.
3161
     */
3162 3437
    public function supportsColumnLengthIndexes() : bool
3163
    {
3164 3437
        return false;
3165
    }
3166
3167
    /**
3168
     * Whether the platform supports altering tables.
3169
     *
3170
     * @return bool
3171
     */
3172 44
    public function supportsAlterTable()
3173
    {
3174 44
        return true;
3175
    }
3176
3177
    /**
3178
     * Whether the platform supports transactions.
3179
     *
3180
     * @return bool
3181
     */
3182 22
    public function supportsTransactions()
3183
    {
3184 22
        return true;
3185
    }
3186
3187
    /**
3188
     * Whether the platform supports savepoints.
3189
     *
3190
     * @return bool
3191
     */
3192 242
    public function supportsSavepoints()
3193
    {
3194 242
        return true;
3195
    }
3196
3197
    /**
3198
     * Whether the platform supports releasing savepoints.
3199
     *
3200
     * @return bool
3201
     */
3202 41
    public function supportsReleaseSavepoints()
3203
    {
3204 41
        return $this->supportsSavepoints();
3205
    }
3206
3207
    /**
3208
     * Whether the platform supports primary key constraints.
3209
     *
3210
     * @return bool
3211
     */
3212 22
    public function supportsPrimaryConstraints()
3213
    {
3214 22
        return true;
3215
    }
3216
3217
    /**
3218
     * Whether the platform supports foreign key constraints.
3219
     *
3220
     * @return bool
3221
     */
3222 6250
    public function supportsForeignKeyConstraints()
3223
    {
3224 6250
        return true;
3225
    }
3226
3227
    /**
3228
     * Whether foreign key constraints can be dropped.
3229
     *
3230
     * If false, then getDropForeignKeySQL() throws exception.
3231
     */
3232 468
    public function supportsCreateDropForeignKeyConstraints() : bool
3233
    {
3234 468
        return true;
3235
    }
3236
3237
    /**
3238
     * Whether this platform supports onUpdate in foreign key constraints.
3239
     *
3240
     * @return bool
3241
     */
3242 1252
    public function supportsForeignKeyOnUpdate()
3243
    {
3244 1252
        return $this->supportsForeignKeyConstraints();
3245
    }
3246
3247
    /**
3248
     * Whether the platform supports database schemas.
3249
     *
3250
     * @return bool
3251
     */
3252 342
    public function supportsSchemas()
3253
    {
3254 342
        return false;
3255
    }
3256
3257
    /**
3258
     * Whether this platform can emulate schemas.
3259
     *
3260
     * Platforms that either support or emulate schemas don't automatically
3261
     * filter a schema for the namespaced elements in {@link
3262
     * AbstractManager#createSchema}.
3263
     *
3264
     * @return bool
3265
     */
3266 154
    public function canEmulateSchemas()
3267
    {
3268 154
        return false;
3269
    }
3270
3271
    /**
3272
     * Returns the default schema name.
3273
     *
3274
     * @return string
3275
     *
3276
     * @throws DBALException If not supported on this platform.
3277
     */
3278
    public function getDefaultSchemaName()
3279
    {
3280
        throw DBALException::notSupported(__METHOD__);
3281
    }
3282
3283
    /**
3284
     * Whether this platform supports create database.
3285
     *
3286
     * Some databases don't allow to create and drop databases at all or only with certain tools.
3287
     *
3288
     * @return bool
3289
     */
3290 70
    public function supportsCreateDropDatabase()
3291
    {
3292 70
        return true;
3293
    }
3294
3295
    /**
3296
     * Whether the platform supports getting the affected rows of a recent update/delete type query.
3297
     *
3298
     * @return bool
3299
     */
3300 22
    public function supportsGettingAffectedRows()
3301
    {
3302 22
        return true;
3303
    }
3304
3305
    /**
3306
     * Whether this platform support to add inline column comments as postfix.
3307
     *
3308
     * @return bool
3309
     */
3310 2617
    public function supportsInlineColumnComments()
3311
    {
3312 2617
        return false;
3313
    }
3314
3315
    /**
3316
     * Whether this platform support the proprietary syntax "COMMENT ON asset".
3317
     *
3318
     * @return bool
3319
     */
3320 4601
    public function supportsCommentOnStatement()
3321
    {
3322 4601
        return false;
3323
    }
3324
3325
    /**
3326
     * Does this platform have native guid type.
3327
     *
3328
     * @return bool
3329
     */
3330 6612
    public function hasNativeGuidType()
3331
    {
3332 6612
        return false;
3333
    }
3334
3335
    /**
3336
     * Does this platform have native JSON type.
3337
     *
3338
     * @return bool
3339
     */
3340 7716
    public function hasNativeJsonType()
3341
    {
3342 7716
        return false;
3343
    }
3344
3345
    /**
3346
     * @deprecated
3347
     *
3348
     * @return string
3349
     *
3350
     * @todo Remove in 3.0
3351
     */
3352
    public function getIdentityColumnNullInsertSQL()
3353
    {
3354
        return '';
3355
    }
3356
3357
    /**
3358
     * Whether this platform supports views.
3359
     *
3360
     * @return bool
3361
     */
3362 22
    public function supportsViews()
3363
    {
3364 22
        return true;
3365
    }
3366
3367
    /**
3368
     * Does this platform support column collation?
3369
     *
3370
     * @return bool
3371
     */
3372
    public function supportsColumnCollation()
3373
    {
3374
        return false;
3375
    }
3376
3377
    /**
3378
     * Gets the format string, as accepted by the date() function, that describes
3379
     * the format of a stored datetime value of this platform.
3380
     *
3381
     * @return string The format string.
3382
     */
3383 385
    public function getDateTimeFormatString()
3384
    {
3385 385
        return 'Y-m-d H:i:s';
3386
    }
3387
3388
    /**
3389
     * Gets the format string, as accepted by the date() function, that describes
3390
     * the format of a stored datetime with timezone value of this platform.
3391
     *
3392
     * @return string The format string.
3393
     */
3394 146
    public function getDateTimeTzFormatString()
3395
    {
3396 146
        return 'Y-m-d H:i:s';
3397
    }
3398
3399
    /**
3400
     * Gets the format string, as accepted by the date() function, that describes
3401
     * the format of a stored date value of this platform.
3402
     *
3403
     * @return string The format string.
3404
     */
3405 151
    public function getDateFormatString()
3406
    {
3407 151
        return 'Y-m-d';
3408
    }
3409
3410
    /**
3411
     * Gets the format string, as accepted by the date() function, that describes
3412
     * the format of a stored time value of this platform.
3413
     *
3414
     * @return string The format string.
3415
     */
3416 129
    public function getTimeFormatString()
3417
    {
3418 129
        return 'H:i:s';
3419
    }
3420
3421
    /**
3422
     * Adds an driver-specific LIMIT clause to the query.
3423
     *
3424
     * @param string   $query
3425
     * @param int|null $limit
3426
     * @param int|null $offset
3427
     *
3428
     * @return string
3429
     *
3430
     * @throws DBALException
3431
     */
3432 1562
    final public function modifyLimitQuery($query, $limit, $offset = null)
3433
    {
3434 1562
        if ($limit !== null) {
3435 1188
            $limit = (int) $limit;
3436
        }
3437
3438 1562
        $offset = (int) $offset;
3439
3440 1562
        if ($offset < 0) {
3441
            throw new DBALException(sprintf(
3442
                'Offset must be a positive integer or zero, %d given',
3443
                $offset
3444
            ));
3445
        }
3446
3447 1562
        if ($offset > 0 && ! $this->supportsLimitOffset()) {
3448
            throw new DBALException(sprintf(
3449
                'Platform %s does not support offset values in limit queries.',
3450
                $this->getName()
3451
            ));
3452
        }
3453
3454 1562
        return $this->doModifyLimitQuery($query, $limit, $offset);
3455
    }
3456
3457
    /**
3458
     * Adds an platform-specific LIMIT clause to the query.
3459
     *
3460
     * @param string   $query
3461
     * @param int|null $limit
3462
     * @param int|null $offset
3463
     *
3464
     * @return string
3465
     */
3466 254
    protected function doModifyLimitQuery($query, $limit, $offset)
3467
    {
3468 254
        if ($limit !== null) {
3469 181
            $query .= ' LIMIT ' . $limit;
3470
        }
3471
3472 254
        if ($offset > 0) {
3473 49
            $query .= ' OFFSET ' . $offset;
3474
        }
3475
3476 254
        return $query;
3477
    }
3478
3479
    /**
3480
     * Whether the database platform support offsets in modify limit clauses.
3481
     *
3482
     * @return bool
3483
     */
3484 345
    public function supportsLimitOffset()
3485
    {
3486 345
        return true;
3487
    }
3488
3489
    /**
3490
     * Gets the character casing of a column in an SQL result set of this platform.
3491
     *
3492
     * @param string $column The column name for which to get the correct character casing.
3493
     *
3494
     * @return string The column name in the character casing used in SQL result sets.
3495
     */
3496
    public function getSQLResultCasing($column)
3497
    {
3498
        return $column;
3499
    }
3500
3501
    /**
3502
     * Makes any fixes to a name of a schema element (table, sequence, ...) that are required
3503
     * by restrictions of the platform, like a maximum length.
3504
     *
3505
     * @param string $schemaElementName
3506
     *
3507
     * @return string
3508
     */
3509
    public function fixSchemaElementName($schemaElementName)
3510
    {
3511
        return $schemaElementName;
3512
    }
3513
3514
    /**
3515
     * Maximum length of any given database identifier, like tables or column names.
3516
     *
3517
     * @return int
3518
     */
3519 373
    public function getMaxIdentifierLength()
3520
    {
3521 373
        return 63;
3522
    }
3523
3524
    /**
3525
     * Returns the insert SQL for an empty insert statement.
3526
     *
3527
     * @param string $tableName
3528
     * @param string $identifierColumnName
3529
     *
3530
     * @return string
3531
     */
3532 16
    public function getEmptyIdentityInsertSQL($tableName, $identifierColumnName)
3533
    {
3534 16
        return 'INSERT INTO ' . $tableName . ' (' . $identifierColumnName . ') VALUES (null)';
3535
    }
3536
3537
    /**
3538
     * Generates a Truncate Table SQL statement for a given table.
3539
     *
3540
     * Cascade is not supported on many platforms but would optionally cascade the truncate by
3541
     * following the foreign keys.
3542
     *
3543
     * @param string $tableName
3544
     * @param bool   $cascade
3545
     *
3546
     * @return string
3547
     */
3548 174
    public function getTruncateTableSQL($tableName, $cascade = false)
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

3548
    public function getTruncateTableSQL($tableName, /** @scrutinizer ignore-unused */ $cascade = false)

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...
3549
    {
3550 174
        $tableIdentifier = new Identifier($tableName);
3551
3552 174
        return 'TRUNCATE ' . $tableIdentifier->getQuotedName($this);
3553
    }
3554
3555
    /**
3556
     * This is for test reasons, many vendors have special requirements for dummy statements.
3557
     *
3558
     * @return string
3559
     */
3560 174
    public function getDummySelectSQL()
3561
    {
3562 174
        $expression = func_num_args() > 0 ? func_get_arg(0) : '1';
3563
3564 174
        return sprintf('SELECT %s', $expression);
3565
    }
3566
3567
    /**
3568
     * Returns the SQL to create a new savepoint.
3569
     *
3570
     * @param string $savepoint
3571
     *
3572
     * @return string
3573
     */
3574 21
    public function createSavePoint($savepoint)
3575
    {
3576 21
        return 'SAVEPOINT ' . $savepoint;
3577
    }
3578
3579
    /**
3580
     * Returns the SQL to release a savepoint.
3581
     *
3582
     * @param string $savepoint
3583
     *
3584
     * @return string
3585
     */
3586 19
    public function releaseSavePoint($savepoint)
3587
    {
3588 19
        return 'RELEASE SAVEPOINT ' . $savepoint;
3589
    }
3590
3591
    /**
3592
     * Returns the SQL to rollback a savepoint.
3593
     *
3594
     * @param string $savepoint
3595
     *
3596
     * @return string
3597
     */
3598 21
    public function rollbackSavePoint($savepoint)
3599
    {
3600 21
        return 'ROLLBACK TO SAVEPOINT ' . $savepoint;
3601
    }
3602
3603
    /**
3604
     * Returns the keyword list instance of this platform.
3605
     *
3606
     * @return KeywordList
3607
     *
3608
     * @throws DBALException If no keyword list is specified.
3609
     */
3610 15829
    final public function getReservedKeywordsList()
3611
    {
3612
        // Check for an existing instantiation of the keywords class.
3613 15829
        if ($this->_keywords !== null) {
3614 15059
            return $this->_keywords;
3615
        }
3616
3617 11770
        $class    = $this->getReservedKeywordsClass();
3618 11770
        $keywords = new $class();
3619 11770
        if (! $keywords instanceof KeywordList) {
3620
            throw DBALException::notSupported(__METHOD__);
3621
        }
3622
3623
        // Store the instance so it doesn't need to be generated on every request.
3624 11770
        $this->_keywords = $keywords;
3625
3626 11770
        return $keywords;
3627
    }
3628
3629
    /**
3630
     * Returns the class name of the reserved keywords list.
3631
     *
3632
     * @return string
3633
     *
3634
     * @throws DBALException If not supported on this platform.
3635
     */
3636
    protected function getReservedKeywordsClass()
3637
    {
3638
        throw DBALException::notSupported(__METHOD__);
3639
    }
3640
3641
    /**
3642
     * Quotes a literal string.
3643
     * This method is NOT meant to fix SQL injections!
3644
     * It is only meant to escape this platform's string literal
3645
     * quote character inside the given literal string.
3646
     *
3647
     * @param string $str The literal string to be quoted.
3648
     *
3649
     * @return string The quoted literal string.
3650
     */
3651 6660
    public function quoteStringLiteral($str)
3652
    {
3653 6660
        $c = $this->getStringLiteralQuoteCharacter();
3654
3655 6660
        return $c . str_replace($c, $c . $c, $str) . $c;
3656
    }
3657
3658
    /**
3659
     * Gets the character used for string literal quoting.
3660
     *
3661
     * @return string
3662
     */
3663 6880
    public function getStringLiteralQuoteCharacter()
3664
    {
3665 6880
        return "'";
3666
    }
3667
3668
    /**
3669
     * Escapes metacharacters in a string intended to be used with a LIKE
3670
     * operator.
3671
     *
3672
     * @param string $inputString a literal, unquoted string
3673
     * @param string $escapeChar  should be reused by the caller in the LIKE
3674
     *                            expression.
3675
     */
3676 242
    final public function escapeStringForLike(string $inputString, string $escapeChar) : string
3677
    {
3678 242
        return preg_replace(
3679 242
            '~([' . preg_quote($this->getLikeWildcardCharacters() . $escapeChar, '~') . '])~u',
3680 242
            addcslashes($escapeChar, '\\') . '$1',
3681 242
            $inputString
3682
        );
3683
    }
3684
3685 242
    protected function getLikeWildcardCharacters() : string
3686
    {
3687 242
        return '%_';
3688
    }
3689
}
3690