Completed
Pull Request — develop (#3594)
by Sergei
65:18
created

AbstractPlatform   F

Complexity

Total Complexity 388

Size/Duplication

Total Lines 3065
Duplicated Lines 0 %

Test Coverage

Coverage 81.43%

Importance

Changes 0
Metric Value
wmc 388
eloc 653
dl 0
loc 3065
ccs 684
cts 840
cp 0.8143
rs 1.947
c 0
b 0
f 0

205 Methods

Rating   Name   Duplication   Size   Complexity  
A fixSchemaElementName() 0 3 1
A getDummySelectSQL() 0 3 1
A getDateTimeTypeDeclarationSQL() 0 3 1
A getTemporaryTableSQL() 0 3 1
A getDropSequenceSQL() 0 3 1
A getForeignKeyDeclarationSQL() 0 6 1
A getColumnCharsetDeclarationSQL() 0 3 1
A supportsIdentityColumns() 0 3 1
A getForeignKeyReferentialActionSQL() 0 12 6
A prefersSequences() 0 3 1
A getUniqueFieldDeclarationSQL() 0 3 1
A getListTableIndexesSQL() 0 3 1
A getSequencePrefix() 0 10 4
A prefersIdentityColumns() 0 3 1
A getIdentitySequenceName() 0 3 1
A getCustomTypeDeclarationSQL() 0 3 1
A getColumnCollationDeclarationSQL() 0 3 2
A getCurrentTimeSQL() 0 3 1
A getAdvancedForeignKeyOptionsSQL() 0 11 4
A getTimeTypeDeclarationSQL() 0 3 1
A markDoctrineTypeCommented() 0 9 3
A getStringTypeDeclarationSQL() 0 9 2
A __construct() 0 2 1
A setEventManager() 0 3 1
A getEventManager() 0 3 1
A getWriteLockSQL() 0 3 1
A getCreateSchemaSQL() 0 3 1
A getLtrimExpression() 0 3 1
A onSchemaAlterTableRenameColumn() 0 16 3
A initializeCommentedDoctrineTypes() 0 12 3
A getCosExpression() 0 3 1
F getCreateTableSQL() 0 89 21
A getForUpdateSQL() 0 3 1
A getPreAlterTableIndexForeignKeySQL() 0 22 6
A getRenameIndexSQL() 0 5 1
A getSqrtExpression() 0 3 1
A getDateSubMonthExpression() 0 3 1
A getDateAddYearsExpression() 0 3 1
A getCreateIndexSQL() 0 20 4
A getBetweenExpression() 0 3 1
A getIsNullExpression() 0 3 1
A getSqlCommentStartString() 0 3 1
A getUpperExpression() 0 3 1
A getDropForeignKeySQL() 0 14 3
A getSumExpression() 0 3 1
A registerDoctrineTypeMapping() 0 20 4
A appendLockHint() 0 3 1
A getSqlCommentEndString() 0 3 1
A getDateDiffExpression() 0 3 1
A getCreatePrimaryKeySQL() 0 7 2
A getAlterTableSQL() 0 3 1
A getGuidTypeDeclarationSQL() 0 6 1
A getPiExpression() 0 3 1
A getBinaryTypeDeclarationSQLSnippet() 0 9 2
A getAvgExpression() 0 3 1
A getCreateForeignKeySQL() 0 7 2
A getReadLockSQL() 0 3 1
A getAcosExpression() 0 3 1
A getDoctrineTypeComment() 0 3 1
A getMd5Expression() 0 3 1
A getCountExpression() 0 3 1
A getMinExpression() 0 3 1
A getVarcharTypeDeclarationSQLSnippet() 0 7 2
A getModExpression() 0 3 1
A getDropConstraintSQL() 0 14 3
A getCommentOnColumnSQL() 0 10 1
A getDateSubQuartersExpression() 0 3 1
A getDateAddMonthExpression() 0 3 1
A getMaxExpression() 0 3 1
A getBitAndComparisonExpression() 0 3 1
A onSchemaAlterTableAddColumn() 0 16 3
B getDropTableSQL() 0 28 7
A quoteSingleIdentifier() 0 5 1
A getDateAddWeeksExpression() 0 3 1
A getDropIndexSQL() 0 9 3
A hasDoctrineTypeMappingFor() 0 9 2
A getDateSubMinutesExpression() 0 3 1
A getDateSubHourExpression() 0 3 1
A getCreateIndexSQLFlags() 0 3 2
A getLengthExpression() 0 3 1
A getCharTypeDeclarationSQLSnippet() 0 9 2
A multiplyInterval() 0 3 1
A getDateSubWeeksExpression() 0 3 1
A getDateAddDaysExpression() 0 3 1
A getIdentifierQuoteCharacter() 0 3 1
A getDateSubDaysExpression() 0 3 1
B getPostAlterTableIndexForeignKeySQL() 0 38 8
C _getCreateTableSQL() 0 37 12
A onSchemaAlterTable() 0 16 3
A initializeAllDoctrineTypeMappings() 0 7 3
A isCommentedDoctrineType() 0 9 2
A getRegexpExpression() 0 3 1
A getDoctrineTypeMapping() 0 17 3
A getBitOrComparisonExpression() 0 3 1
A getSinExpression() 0 3 1
A getLowerExpression() 0 3 1
A getVarbinaryTypeDeclarationSQLSnippet() 0 7 2
A getCreateTemporaryTableSnippetSQL() 0 3 1
A getNowExpression() 0 3 1
A getCreateSequenceSQL() 0 3 1
A getDateSubSecondsExpression() 0 3 1
A getRoundExpression() 0 3 1
A getIsNotNullExpression() 0 3 1
A getRtrimExpression() 0 3 1
A getCreateConstraintSQL() 0 30 6
A getInlineColumnCommentSQL() 0 7 2
A getSubstringExpression() 0 7 2
A getAlterSequenceSQL() 0 3 1
A getDateArithmeticIntervalExpression() 0 3 1
A getDateAddMinutesExpression() 0 3 1
A getBinaryTypeDeclarationSQL() 0 9 2
A getJsonTypeDeclarationSQL() 0 3 1
A getConcatExpression() 0 3 1
A getLocateExpression() 0 3 1
A getWildcards() 0 3 1
A quoteIdentifier() 0 9 2
B getTrimExpression() 0 40 7
A getDateAddQuartersExpression() 0 3 1
A getDropTemporaryTableSQL() 0 3 1
A getPartialIndexSQL() 0 7 3
A getNotExpression() 0 3 1
A onSchemaAlterTableRemoveColumn() 0 16 3
A getDateSubYearsExpression() 0 3 1
A getDropDatabaseSQL() 0 3 1
A onSchemaAlterTableChangeColumn() 0 16 3
A getDateAddSecondsExpression() 0 3 1
A getColumnComment() 0 9 2
A getDateAddHourExpression() 0 3 1
A supportsAlterTable() 0 3 1
A supportsForeignKeyOnUpdate() 0 3 1
A getCheckDeclarationSQL() 0 20 5
A getFloatDeclarationSQL() 0 3 1
A getDefaultSchemaName() 0 3 1
A supportsCreateDropDatabase() 0 3 1
A getCreateDatabaseSQL() 0 3 1
A getListTableColumnsSQL() 0 3 1
A supportsLimitOffset() 0 3 1
A getListDatabasesSQL() 0 3 1
A supportsSavepoints() 0 3 1
A getDateTimeTzTypeDeclarationSQL() 0 3 1
A supportsTransactions() 0 3 1
A hasNativeGuidType() 0 3 1
A supportsCommentOnStatement() 0 3 1
A convertFromBoolean() 0 7 2
A getDefaultTransactionIsolationLevel() 0 3 1
A getMaxIdentifierLength() 0 3 1
A _getTransactionIsolationLevelSQL() 0 13 5
A getListNamespacesSQL() 0 3 1
A getUniqueConstraintDeclarationSQL() 0 23 4
A supportsViews() 0 3 1
A canEmulateSchemas() 0 3 1
A getCreateViewSQL() 0 3 1
A getDateFormatString() 0 3 1
A getListUsersSQL() 0 3 1
A getListSequencesSQL() 0 3 1
A convertBooleans() 0 15 5
A createSavePoint() 0 3 1
A convertBooleansToDatabaseValue() 0 3 1
A getSequenceNextValSQL() 0 3 1
A getCurrentDateSQL() 0 3 1
A supportsPartialIndexes() 0 3 1
A getReservedKeywordsClass() 0 3 1
A getReservedKeywordsList() 0 17 3
A getStringLiteralQuoteCharacter() 0 3 1
F getColumnDeclarationSQL() 0 30 15
C getDefaultValueDeclarationSQL() 0 39 14
A supportsSchemas() 0 3 1
A getSQLResultCasing() 0 3 1
A getDropViewSQL() 0 3 1
A getDateTimeFormatString() 0 3 1
A supportsSequences() 0 3 1
A supportsReleaseSavepoints() 0 3 1
A supportsIndexes() 0 3 1
A getIndexFieldDeclarationListSQL() 0 21 5
A getDateTypeDeclarationSQL() 0 3 1
A supportsColumnCollation() 0 3 1
A getDecimalTypeDeclarationSQL() 0 8 5
A quoteStringLiteral() 0 5 1
A hasNativeJsonType() 0 3 1
A getTruncateTableSQL() 0 5 1
A getLikeWildcardCharacters() 0 3 1
A usesSequenceEmulatedIdentityColumns() 0 3 1
A getSetTransactionIsolationSQL() 0 3 1
A getListTableForeignKeysSQL() 0 3 1
A getListViewsSQL() 0 3 1
A supportsForeignKeyConstraints() 0 3 1
A modifyLimitQuery() 0 17 4
A getTimeFormatString() 0 3 1
A supportsColumnLengthIndexes() 0 3 1
A getTemporaryTableName() 0 3 1
A getForeignKeyBaseDeclarationSQL() 0 22 5
A getDateTimeTzFormatString() 0 3 1
A supportsGettingAffectedRows() 0 3 1
A getCurrentTimestampSQL() 0 3 1
A releaseSavePoint() 0 3 1
A rollbackSavePoint() 0 3 1
A getListTableConstraintsSQL() 0 3 1
A getIndexDeclarationSQL() 0 12 2
A getListTablesSQL() 0 3 1
A getEmptyIdentityInsertSQL() 0 3 1
A supportsInlineColumnComments() 0 3 1
A doModifyLimitQuery() 0 11 3
A escapeStringForLike() 0 6 1
A getColumnDeclarationListSQL() 0 9 2
A supportsPrimaryConstraints() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like AbstractPlatform often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AbstractPlatform, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\DBAL\Platforms;
6
7
use Doctrine\Common\EventManager;
8
use Doctrine\DBAL\DBALException;
9
use Doctrine\DBAL\Event\SchemaAlterTableAddColumnEventArgs;
10
use Doctrine\DBAL\Event\SchemaAlterTableChangeColumnEventArgs;
11
use Doctrine\DBAL\Event\SchemaAlterTableEventArgs;
12
use Doctrine\DBAL\Event\SchemaAlterTableRemoveColumnEventArgs;
13
use Doctrine\DBAL\Event\SchemaAlterTableRenameColumnEventArgs;
14
use Doctrine\DBAL\Event\SchemaCreateTableColumnEventArgs;
15
use Doctrine\DBAL\Event\SchemaCreateTableEventArgs;
16
use Doctrine\DBAL\Event\SchemaDropTableEventArgs;
17
use Doctrine\DBAL\Events;
18
use Doctrine\DBAL\Exception\ColumnLengthRequired;
19
use Doctrine\DBAL\Platforms\Exception\NoColumnsSpecifiedForTable;
20
use Doctrine\DBAL\Platforms\Exception\NotSupported;
21
use Doctrine\DBAL\Platforms\Keywords\KeywordList;
22
use Doctrine\DBAL\Schema\Column;
23
use Doctrine\DBAL\Schema\ColumnDiff;
24
use Doctrine\DBAL\Schema\Constraint;
25
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
26
use Doctrine\DBAL\Schema\Identifier;
27
use Doctrine\DBAL\Schema\Index;
28
use Doctrine\DBAL\Schema\Sequence;
29
use Doctrine\DBAL\Schema\Table;
30
use Doctrine\DBAL\Schema\TableDiff;
31
use Doctrine\DBAL\Schema\UniqueConstraint;
32
use Doctrine\DBAL\TransactionIsolationLevel;
33
use Doctrine\DBAL\Types;
34
use Doctrine\DBAL\Types\Exception\TypeNotFound;
35
use Doctrine\DBAL\Types\Type;
36
use InvalidArgumentException;
37
use UnexpectedValueException;
38
use function addcslashes;
39
use function array_map;
40
use function array_merge;
41
use function array_unique;
42
use function array_values;
43
use function assert;
44
use function count;
45
use function explode;
46
use function implode;
47
use function in_array;
48
use function is_array;
49
use function is_bool;
50
use function is_float;
51
use function is_int;
52
use function is_string;
53
use function preg_quote;
54
use function preg_replace;
55
use function sprintf;
56
use function str_replace;
57
use function strlen;
58
use function strpos;
59
use function strtolower;
60
use function strtoupper;
61
62
/**
63
 * Base class for all DatabasePlatforms. The DatabasePlatforms are the central
64
 * point of abstraction of platform-specific behaviors, features and SQL dialects.
65
 * They are a passive source of information.
66
 *
67
 * @todo Remove any unnecessary methods.
68
 */
69
abstract class AbstractPlatform
70
{
71
    public const CREATE_INDEXES = 1;
72
73
    public const CREATE_FOREIGNKEYS = 2;
74
75
    /** @var string[]|null */
76
    protected $doctrineTypeMapping = null;
77
78
    /**
79
     * Contains a list of all columns that should generate parseable column comments for type-detection
80
     * in reverse engineering scenarios.
81
     *
82
     * @var string[]|null
83
     */
84
    protected $doctrineTypeComments = null;
85
86
    /** @var EventManager|null */
87
    protected $_eventManager;
88
89
    /**
90
     * Holds the KeywordList instance for the current platform.
91
     *
92
     * @var KeywordList|null
93
     */
94
    protected $_keywords;
95
96 47445
    public function __construct()
97
    {
98 47445
    }
99
100
    /**
101
     * Sets the EventManager used by the Platform.
102
     */
103 45115
    public function setEventManager(EventManager $eventManager) : void
104
    {
105 45115
        $this->_eventManager = $eventManager;
106 45115
    }
107
108
    /**
109
     * Gets the EventManager used by the Platform.
110
     */
111 40884
    public function getEventManager() : ?EventManager
112
    {
113 40884
        return $this->_eventManager;
114
    }
115
116
    /**
117
     * Returns the SQL snippet that declares a boolean column.
118
     *
119
     * @param mixed[] $columnDef
120
     */
121
    abstract public function getBooleanTypeDeclarationSQL(array $columnDef) : string;
122
123
    /**
124
     * Returns the SQL snippet that declares a 4 byte integer column.
125
     *
126
     * @param mixed[] $columnDef
127
     */
128
    abstract public function getIntegerTypeDeclarationSQL(array $columnDef) : string;
129
130
    /**
131
     * Returns the SQL snippet that declares an 8 byte integer column.
132
     *
133
     * @param mixed[] $columnDef
134
     */
135
    abstract public function getBigIntTypeDeclarationSQL(array $columnDef) : string;
136
137
    /**
138
     * Returns the SQL snippet that declares a 2 byte integer column.
139
     *
140
     * @param mixed[] $columnDef
141
     */
142
    abstract public function getSmallIntTypeDeclarationSQL(array $columnDef) : string;
143
144
    /**
145
     * Returns the SQL snippet that declares common properties of an integer column.
146
     *
147
     * @param mixed[] $columnDef
148
     */
149
    abstract protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef) : string;
150
151
    /**
152
     * Lazy load Doctrine Type Mappings.
153
     */
154
    abstract protected function initializeDoctrineTypeMappings() : void;
155
156
    /**
157
     * Initializes Doctrine Type Mappings with the platform defaults
158
     * and with all additional type mappings.
159
     */
160 42381
    private function initializeAllDoctrineTypeMappings() : void
161
    {
162 42381
        $this->initializeDoctrineTypeMappings();
163
164 42381
        foreach (Type::getTypesMap() as $typeName => $className) {
165 42381
            foreach (Type::getType($typeName)->getMappedDatabaseTypes($this) as $dbType) {
166 23583
                $this->doctrineTypeMapping[$dbType] = $typeName;
167
            }
168
        }
169 42381
    }
170
171
    /**
172
     * Returns the SQL snippet used to declare a string column type.
173
     *
174
     * @param array<string, mixed> $column The column definition.
175
     *
176
     * @throws ColumnLengthRequired
177
     */
178 44710
    public function getStringTypeDeclarationSQL(array $column) : string
179
    {
180 44710
        $length = $column['length'] ?? null;
181
182 44710
        if (empty($column['fixed'])) {
183 44664
            return $this->getVarcharTypeDeclarationSQLSnippet($length);
184
        }
185
186 42481
        return $this->getCharTypeDeclarationSQLSnippet($length);
187
    }
188
189
    /**
190
     * Returns the SQL snippet used to declare a binary string column type.
191
     *
192
     * @param array<string, mixed> $column The column definition.
193
     *
194
     * @throws ColumnLengthRequired
195
     */
196 41086
    public function getBinaryTypeDeclarationSQL(array $column) : string
197
    {
198 41086
        $length = $column['length'] ?? null;
199
200 41086
        if (empty($column['fixed'])) {
201 41060
            return $this->getVarbinaryTypeDeclarationSQLSnippet($length);
202
        }
203
204 40999
        return $this->getBinaryTypeDeclarationSQLSnippet($length);
205
    }
206
207
    /**
208
     * Returns the SQL snippet to declare a GUID/UUID field.
209
     *
210
     * By default this maps directly to a CHAR(36) and only maps to more
211
     * special datatypes when the underlying databases support this datatype.
212
     *
213
     * @param array<string, mixed> $column The column definition.
214
     *
215
     * @throws DBALException
216
     */
217 40441
    public function getGuidTypeDeclarationSQL(array $column) : string
218
    {
219 40441
        $column['length'] = 36;
220 40441
        $column['fixed']  = true;
221
222 40441
        return $this->getStringTypeDeclarationSQL($column);
223
    }
224
225
    /**
226
     * Returns the SQL snippet to declare a JSON field.
227
     *
228
     * By default this maps directly to a CLOB and only maps to more
229
     * special datatypes when the underlying databases support this datatype.
230
     *
231
     * @param mixed[] $field
232
     */
233 38672
    public function getJsonTypeDeclarationSQL(array $field) : string
234
    {
235 38672
        return $this->getClobTypeDeclarationSQL($field);
236
    }
237
238
    /**
239
     * @param int|null $length The length of the column in characters
240
     *                         or NULL if the length should be omitted.
241
     *
242
     * @throws ColumnLengthRequired
243
     */
244 42179
    protected function getCharTypeDeclarationSQLSnippet(?int $length) : string
245
    {
246 42179
        $sql = 'CHAR';
247
248 42179
        if ($length !== null) {
249 42168
            $sql .= sprintf('(%d)', $length);
250
        }
251
252 42179
        return $sql;
253
    }
254
255
    /**
256
     * @param int|null $length The length of the column in characters
257
     *                         or NULL if the length should be omitted.
258
     *
259
     * @throws ColumnLengthRequired
260
     */
261 42513
    protected function getVarcharTypeDeclarationSQLSnippet(?int $length) : string
262
    {
263 42513
        if ($length === null) {
264 38756
            throw ColumnLengthRequired::new($this, 'VARCHAR');
265
        }
266
267 42507
        return sprintf('VARCHAR(%d)', $length);
268
    }
269
270
    /**
271
     * Returns the SQL snippet used to declare a fixed length binary column type.
272
     *
273
     * @param int|null $length The length of the column in bytes
274
     *                         or NULL if the length should be omitted.
275
     *
276
     * @throws ColumnLengthRequired
277
     */
278 38545
    protected function getBinaryTypeDeclarationSQLSnippet(?int $length) : string
279
    {
280 38545
        $sql = 'BINARY';
281
282 38545
        if ($length !== null) {
283 37637
            $sql .= sprintf('(%d)', $length);
284
        }
285
286 38545
        return $sql;
287
    }
288
289
    /**
290
     * Returns the SQL snippet used to declare a variable length binary column type.
291
     *
292
     * @param int|null $length The length of the column in bytes
293
     *                         or NULL if the length should be omitted.
294
     *
295
     * @throws ColumnLengthRequired
296
     */
297 38526
    protected function getVarbinaryTypeDeclarationSQLSnippet(?int $length) : string
298
    {
299 38526
        if ($length === null) {
300 6
            throw ColumnLengthRequired::new($this, 'VARBINARY');
301
        }
302
303 38520
        return sprintf('VARBINARY(%d)', $length);
304
    }
305
306
    /**
307
     * Returns the SQL snippet used to declare a CLOB column type.
308
     *
309
     * @param mixed[] $field
310
     */
311
    abstract public function getClobTypeDeclarationSQL(array $field) : string;
312
313
    /**
314
     * Returns the SQL Snippet used to declare a BLOB column type.
315
     *
316
     * @param mixed[] $field
317
     */
318
    abstract public function getBlobTypeDeclarationSQL(array $field) : string;
319
320
    /**
321
     * Gets the name of the platform.
322
     */
323
    abstract public function getName() : string;
324
325
    /**
326
     * Registers a doctrine type to be used in conjunction with a column type of this platform.
327
     *
328
     * @throws DBALException If the type is not found.
329
     */
330 40459
    public function registerDoctrineTypeMapping(string $dbType, string $doctrineType) : void
331
    {
332 40459
        if ($this->doctrineTypeMapping === null) {
333 39904
            $this->initializeAllDoctrineTypeMappings();
334
        }
335
336 40459
        if (! Types\Type::hasType($doctrineType)) {
337 38237
            throw TypeNotFound::new($doctrineType);
338
        }
339
340 40447
        $dbType                             = strtolower($dbType);
341 40447
        $this->doctrineTypeMapping[$dbType] = $doctrineType;
342
343 40447
        $doctrineType = Type::getType($doctrineType);
344
345 40447
        if (! $doctrineType->requiresSQLCommentHint($this)) {
346 40435
            return;
347
        }
348
349 38212
        $this->markDoctrineTypeCommented($doctrineType);
350 38212
    }
351
352
    /**
353
     * Gets the Doctrine type that is mapped for the given database column type.
354
     *
355
     * @throws DBALException
356
     */
357 42407
    public function getDoctrineTypeMapping(string $dbType) : string
358
    {
359 42407
        if ($this->doctrineTypeMapping === null) {
360 42296
            $this->initializeAllDoctrineTypeMappings();
361
        }
362
363 42407
        $dbType = strtolower($dbType);
364
365 42407
        if (! isset($this->doctrineTypeMapping[$dbType])) {
366 38287
            throw new DBALException(sprintf(
367 12
                'Unknown database type "%s" requested, %s may not support it.',
368 38287
                $dbType,
369 38287
                static::class
370
            ));
371
        }
372
373 42395
        return $this->doctrineTypeMapping[$dbType];
374
    }
375
376
    /**
377
     * Checks if a database type is currently supported by this platform.
378
     */
379 39732
    public function hasDoctrineTypeMappingFor(string $dbType) : bool
380
    {
381 39732
        if ($this->doctrineTypeMapping === null) {
382 36491
            $this->initializeAllDoctrineTypeMappings();
383
        }
384
385 39732
        $dbType = strtolower($dbType);
386
387 39732
        return isset($this->doctrineTypeMapping[$dbType]);
388
    }
389
390
    /**
391
     * Initializes the Doctrine Type comments instance variable for in_array() checks.
392
     */
393 45329
    protected function initializeCommentedDoctrineTypes() : void
394
    {
395 45329
        $this->doctrineTypeComments = [];
396
397 45329
        foreach (Type::getTypesMap() as $typeName => $className) {
398 45329
            $type = Type::getType($typeName);
399
400 45329
            if (! $type->requiresSQLCommentHint($this)) {
401 45329
                continue;
402
            }
403
404 45329
            $this->doctrineTypeComments[] = $typeName;
405
        }
406 45329
    }
407
408
    /**
409
     * Is it necessary for the platform to add a parsable type comment to allow reverse engineering the given type?
410
     */
411 45460
    public function isCommentedDoctrineType(Type $doctrineType) : bool
412
    {
413 45460
        if ($this->doctrineTypeComments === null) {
414 45317
            $this->initializeCommentedDoctrineTypes();
415
        }
416
417 45460
        assert(is_array($this->doctrineTypeComments));
418
419 45460
        return in_array($doctrineType->getName(), $this->doctrineTypeComments);
420
    }
421
422
    /**
423
     * Marks this type as to be commented in ALTER TABLE and CREATE TABLE statements.
424
     *
425
     * @param string|Type $doctrineType
426
     */
427 38212
    public function markDoctrineTypeCommented($doctrineType) : void
428
    {
429 38212
        if ($this->doctrineTypeComments === null) {
430 38212
            $this->initializeCommentedDoctrineTypes();
431
        }
432
433 38212
        assert(is_array($this->doctrineTypeComments));
434
435 38212
        $this->doctrineTypeComments[] = $doctrineType instanceof Type ? $doctrineType->getName() : $doctrineType;
436 38212
    }
437
438
    /**
439
     * Gets the comment to append to a column comment that helps parsing this type in reverse engineering.
440
     */
441 41444
    public function getDoctrineTypeComment(Type $doctrineType) : string
442
    {
443 41444
        return '(DC2Type:' . $doctrineType->getName() . ')';
444
    }
445
446
    /**
447
     * Gets the comment of a passed column modified by potential doctrine type comment hints.
448
     */
449 45161
    protected function getColumnComment(Column $column) : ?string
450
    {
451 45161
        $comment = $column->getComment();
452
453 45161
        if ($this->isCommentedDoctrineType($column->getType())) {
454 41444
            $comment .= $this->getDoctrineTypeComment($column->getType());
455
        }
456
457 45161
        return $comment;
458
    }
459
460
    /**
461
     * Gets the character used for identifier quoting.
462
     */
463 40547
    public function getIdentifierQuoteCharacter() : string
464
    {
465 40547
        return '"';
466
    }
467
468
    /**
469
     * Gets the string portion that starts an SQL comment.
470
     */
471
    public function getSqlCommentStartString() : string
472
    {
473
        return '--';
474
    }
475
476
    /**
477
     * Gets the string portion that ends an SQL comment.
478
     */
479
    public function getSqlCommentEndString() : string
480
    {
481
        return "\n";
482
    }
483
484
    /**
485
     * Gets all SQL wildcard characters of the platform.
486
     *
487
     * @return string[]
488
     */
489
    public function getWildcards() : array
490
    {
491
        return ['%', '_'];
492
    }
493
494
    /**
495
     * Returns the regular expression operator.
496
     *
497
     * @throws DBALException If not supported on this platform.
498
     */
499 27603
    public function getRegexpExpression() : string
500
    {
501 27603
        throw NotSupported::new(__METHOD__);
502
    }
503
504
    /**
505
     * Returns the SQL snippet to get the average value of a column.
506
     *
507
     * @param string $value SQL expression producing the value.
508
     */
509
    public function getAvgExpression(string $value) : string
510
    {
511
        return 'AVG(' . $value . ')';
512
    }
513
514
    /**
515
     * Returns the SQL snippet to get the number of rows (without a NULL value) of a column.
516
     *
517
     * If a '*' is used instead of a column the number of selected rows is returned.
518
     *
519
     * @param string $expression The expression to count.
520
     */
521
    public function getCountExpression(string $expression) : string
522
    {
523
        return 'COUNT(' . $expression . ')';
524
    }
525
526
    /**
527
     * Returns the SQL snippet to get the maximum value in a set of values.
528
     *
529
     * @param string $value SQL expression producing the value.
530
     */
531
    public function getMaxExpression(string $value) : string
532
    {
533
        return 'MAX(' . $value . ')';
534
    }
535
536
    /**
537
     * Returns the SQL snippet to get the minimum value in a set of values.
538
     *
539
     * @param string $value SQL expression producing the value.
540
     */
541
    public function getMinExpression(string $value) : string
542
    {
543
        return 'MIN(' . $value . ')';
544
    }
545
546
    /**
547
     * Returns the SQL snippet to get the total sum of the values in a set.
548
     *
549
     * @param string $value SQL expression producing the value.
550
     */
551
    public function getSumExpression(string $value) : string
552
    {
553
        return 'SUM(' . $value . ')';
554
    }
555
556
    // scalar functions
557
558
    /**
559
     * Returns the SQL snippet to get the md5 sum of the value.
560
     *
561
     * Note: Not SQL92, but common functionality.
562
     *
563
     * @param string $string SQL expression producing the string.
564
     */
565
    public function getMd5Expression(string $string) : string
566
    {
567
        return 'MD5(' . $string . ')';
568
    }
569
570
    /**
571
     * Returns the SQL snippet to get the length of a text field.
572
     *
573
     * @param string $string SQL expression producing the string.
574
     */
575
    public function getLengthExpression(string $string) : string
576
    {
577
        return 'LENGTH(' . $string . ')';
578
    }
579
580
    /**
581
     * Returns the SQL snippet to get the square root of the value.
582
     *
583
     * @param string $number SQL expression producing the number.
584
     */
585
    public function getSqrtExpression(string $number) : string
586
    {
587
        return 'SQRT(' . $number . ')';
588
    }
589
590
    /**
591
     * Returns the SQL snippet to round a number to the number of decimals specified.
592
     *
593
     * @param string $number   SQL expression producing the number to round.
594
     * @param string $decimals SQL expression producing the number of decimals.
595
     */
596
    public function getRoundExpression(string $number, string $decimals = '0') : string
597
    {
598
        return 'ROUND(' . $number . ', ' . $decimals . ')';
599
    }
600
601
    /**
602
     * Returns the SQL snippet to get the remainder of the operation of division of dividend by divisor.
603
     *
604
     * @param string $dividend SQL expression producing the dividend.
605
     * @param string $divisor  SQL expression producing the divisor.
606
     */
607
    public function getModExpression(string $dividend, string $divisor) : string
608
    {
609
        return 'MOD(' . $dividend . ', ' . $divisor . ')';
610
    }
611
612
    /**
613
     * Returns the SQL snippet to trim a string.
614
     *
615
     * @param string      $str  The expression to apply the trim to.
616
     * @param int         $mode The position of the trim (leading/trailing/both).
617
     * @param string|null $char The char to trim, has to be quoted already. Defaults to space.
618
     *
619
     * @throws InvalidArgumentException
620
     */
621 37434
    public function getTrimExpression(string $str, int $mode = TrimMode::UNSPECIFIED, ?string $char = null) : string
622
    {
623 37434
        $tokens = [];
624
625 37434
        switch ($mode) {
626
            case TrimMode::UNSPECIFIED:
627 37406
                break;
628
629
            case TrimMode::LEADING:
630 37385
                $tokens[] = 'LEADING';
631 37385
                break;
632
633
            case TrimMode::TRAILING:
634 9
                $tokens[] = 'TRAILING';
635 9
                break;
636
637
            case TrimMode::BOTH:
638 9
                $tokens[] = 'BOTH';
639 9
                break;
640
641
            default:
642 37272
                throw new InvalidArgumentException(
643 37272
                    sprintf(
644 1
                        'The value of $mode is expected to be one of the TrimMode constants, %d given.',
645 37272
                        $mode
646
                    )
647
                );
648
        }
649
650 37433
        if ($char !== null) {
651 37383
            $tokens[] = $char;
652
        }
653
654 37433
        if (count($tokens) > 0) {
655 37410
            $tokens[] = 'FROM';
656
        }
657
658 37433
        $tokens[] = $str;
659
660 37433
        return sprintf('TRIM(%s)', implode(' ', $tokens));
661
    }
662
663
    /**
664
     * Returns the SQL snippet to trim trailing space characters from the string.
665
     *
666
     * @param string $string SQL expression producing the string.
667
     */
668 14726
    public function getRtrimExpression(string $string) : string
669
    {
670 14726
        return 'RTRIM(' . $string . ')';
671
    }
672
673
    /**
674
     * Returns the SQL snippet to trim leading space characters from the string.
675
     *
676
     * @param string $string SQL expression producing the string.
677
     */
678 14726
    public function getLtrimExpression(string $string) : string
679
    {
680 14726
        return 'LTRIM(' . $string . ')';
681
    }
682
683
    /**
684
     * Returns the SQL snippet to change all characters from the string to uppercase,
685
     * according to the current character set mapping.
686
     *
687
     * @param string $string SQL expression producing the string.
688
     */
689
    public function getUpperExpression(string $string) : string
690
    {
691
        return 'UPPER(' . $string . ')';
692
    }
693
694
    /**
695
     * Returns the SQL snippet to change all characters from the string to lowercase,
696
     * according to the current character set mapping.
697
     *
698
     * @param string $string SQL expression producing the string.
699
     */
700
    public function getLowerExpression(string $string) : string
701
    {
702
        return 'LOWER(' . $string . ')';
703
    }
704
705
    /**
706
     * Returns the SQL snippet to get the position of the first occurrence of the substring in the string.
707
     *
708
     * @param string      $string    SQL expression producing the string to locate the substring in.
709
     * @param string      $substring SQL expression producing the substring to locate.
710
     * @param string|null $start     SQL expression producing the position to start at.
711
     *                               Defaults to the beginning of the string.
712
     *
713
     * @throws DBALException If not supported on this platform.
714
     */
715
    public function getLocateExpression(string $string, string $substring, ?string $start = null) : string
0 ignored issues
show
Unused Code introduced by
The parameter $substring is not used and could be removed. ( Ignorable by Annotation )

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

715
    public function getLocateExpression(string $string, /** @scrutinizer ignore-unused */ string $substring, ?string $start = null) : string

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

Loading history...
716
    {
717
        throw NotSupported::new(__METHOD__);
718
    }
719
720
    /**
721
     * Returns the SQL snippet to get the current system date.
722
     */
723
    public function getNowExpression() : string
724
    {
725
        return 'NOW()';
726
    }
727
728
    /**
729
     * Returns an SQL snippet to get a substring inside the string.
730
     *
731
     * Note: Not SQL92, but common functionality.
732
     *
733
     * @param string      $string SQL expression producing the string from which a substring should be extracted.
734
     * @param string      $start  SQL expression producing the position to start at,
735
     * @param string|null $length SQL expression producing the length of the substring portion to be returned.
736
     *                            By default, the entire substring is returned.
737
     */
738 39811
    public function getSubstringExpression(string $string, string $start, ?string $length = null) : string
739
    {
740 39811
        if ($length === null) {
741 39811
            return sprintf('SUBSTRING(%s FROM %s)', $string, $start);
742
        }
743
744 39785
        return sprintf('SUBSTRING(%s FROM %s FOR %s)', $string, $start, $length);
745
    }
746
747
    /**
748
     * Returns a SQL snippet to concatenate the given strings.
749
     *
750
     * @param string[] ...$string
751
     */
752 28230
    public function getConcatExpression(string ...$string) : string
753
    {
754 28230
        return implode(' || ', $string);
755
    }
756
757
    /**
758
     * Returns the SQL for a logical not.
759
     *
760
     * @param string $value SQL expression producing the value to negate.
761
     */
762
    public function getNotExpression(string $value) : string
763
    {
764
        return 'NOT(' . $value . ')';
765
    }
766
767
    /**
768
     * Returns the SQL that checks if an expression is null.
769
     *
770
     * @param string $value SQL expression producing the to be compared to null.
771
     */
772 45107
    public function getIsNullExpression(string $value) : string
773
    {
774 45107
        return $value . ' IS NULL';
775
    }
776
777
    /**
778
     * Returns the SQL that checks if an expression is not null.
779
     *
780
     * @param string $value SQL expression producing the to be compared to null.
781
     */
782
    public function getIsNotNullExpression(string $value) : string
783
    {
784
        return $value . ' IS NOT NULL';
785
    }
786
787
    /**
788
     * Returns the SQL that checks if an expression evaluates to a value between two values.
789
     *
790
     * The parameter $value is checked if it is between $min and $max.
791
     *
792
     * Note: There is a slight difference in the way BETWEEN works on some databases.
793
     * http://www.w3schools.com/sql/sql_between.asp. If you want complete database
794
     * independence you should avoid using between().
795
     *
796
     * @param string $value SQL expression producing the value to compare.
797
     * @param string $min   SQL expression producing the lower value to compare with.
798
     * @param string $max   SQL expression producing the higher value to compare with.
799
     */
800
    public function getBetweenExpression(string $value, string $min, string $max) : string
801
    {
802
        return $value . ' BETWEEN ' . $min . ' AND ' . $max;
803
    }
804
805
    /**
806
     * Returns the SQL to get the arccosine of a value.
807
     *
808
     * @param string $number SQL expression producing the number.
809
     */
810
    public function getAcosExpression(string $number) : string
811
    {
812
        return 'ACOS(' . $number . ')';
813
    }
814
815
    /**
816
     * Returns the SQL to get the sine of a value.
817
     *
818
     * @param string $number SQL expression producing the number.
819
     */
820
    public function getSinExpression(string $number) : string
821
    {
822
        return 'SIN(' . $number . ')';
823
    }
824
825
    /**
826
     * Returns the SQL to get the PI value.
827
     */
828
    public function getPiExpression() : string
829
    {
830
        return 'PI()';
831
    }
832
833
    /**
834
     * Returns the SQL to get the cosine of a value.
835
     *
836
     * @param string $number SQL expression producing the number.
837
     */
838
    public function getCosExpression(string $number) : string
839
    {
840
        return 'COS(' . $number . ')';
841
    }
842
843
    /**
844
     * Returns the SQL to calculate the difference in days between the two passed dates.
845
     *
846
     * Computes diff = date1 - date2.
847
     *
848
     * @throws DBALException If not supported on this platform.
849
     */
850
    public function getDateDiffExpression(string $date1, string $date2) : string
0 ignored issues
show
Unused Code introduced by
The parameter $date1 is not used and could be removed. ( Ignorable by Annotation )

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

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

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

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

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

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

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

Loading history...
851
    {
852
        throw NotSupported::new(__METHOD__);
853
    }
854
855
    /**
856
     * Returns the SQL to add the number of given seconds to a date.
857
     *
858
     * @param string $date    SQL expression producing the date.
859
     * @param string $seconds SQL expression producing the number of seconds.
860
     *
861
     * @throws DBALException If not supported on this platform.
862
     */
863 44058
    public function getDateAddSecondsExpression(string $date, string $seconds) : string
864
    {
865 44058
        return $this->getDateArithmeticIntervalExpression($date, '+', $seconds, DateIntervalUnit::SECOND);
866
    }
867
868
    /**
869
     * Returns the SQL to subtract the number of given seconds from a date.
870
     *
871
     * @param string $date    SQL expression producing the date.
872
     * @param string $seconds SQL expression producing the number of seconds.
873
     *
874
     * @throws DBALException If not supported on this platform.
875
     */
876 44010
    public function getDateSubSecondsExpression(string $date, string $seconds) : string
877
    {
878 44010
        return $this->getDateArithmeticIntervalExpression($date, '-', $seconds, DateIntervalUnit::SECOND);
879
    }
880
881
    /**
882
     * Returns the SQL to add the number of given minutes to a date.
883
     *
884
     * @param string $date    SQL expression producing the date.
885
     * @param string $minutes SQL expression producing the number of minutes.
886
     *
887
     * @throws DBALException If not supported on this platform.
888
     */
889 43962
    public function getDateAddMinutesExpression(string $date, string $minutes) : string
890
    {
891 43962
        return $this->getDateArithmeticIntervalExpression($date, '+', $minutes, DateIntervalUnit::MINUTE);
892
    }
893
894
    /**
895
     * Returns the SQL to subtract the number of given minutes from a date.
896
     *
897
     * @param string $date    SQL expression producing the date.
898
     * @param string $minutes SQL expression producing the number of minutes.
899
     *
900
     * @throws DBALException If not supported on this platform.
901
     */
902 43914
    public function getDateSubMinutesExpression(string $date, string $minutes) : string
903
    {
904 43914
        return $this->getDateArithmeticIntervalExpression($date, '-', $minutes, DateIntervalUnit::MINUTE);
905
    }
906
907
    /**
908
     * Returns the SQL to add the number of given hours to a date.
909
     *
910
     * @param string $date  SQL expression producing the date.
911
     * @param string $hours SQL expression producing the number of hours.
912
     *
913
     * @throws DBALException If not supported on this platform.
914
     */
915 43866
    public function getDateAddHourExpression(string $date, string $hours) : string
916
    {
917 43866
        return $this->getDateArithmeticIntervalExpression($date, '+', $hours, DateIntervalUnit::HOUR);
918
    }
919
920
    /**
921
     * Returns the SQL to subtract the number of given hours to a date.
922
     *
923
     * @param string $date  SQL expression producing the date.
924
     * @param string $hours SQL expression producing the number of hours.
925
     *
926
     * @throws DBALException If not supported on this platform.
927
     */
928 43818
    public function getDateSubHourExpression(string $date, string $hours) : string
929
    {
930 43818
        return $this->getDateArithmeticIntervalExpression($date, '-', $hours, DateIntervalUnit::HOUR);
931
    }
932
933
    /**
934
     * Returns the SQL to add the number of given days to a date.
935
     *
936
     * @param string $date SQL expression producing the date.
937
     * @param string $days SQL expression producing the number of days.
938
     *
939
     * @throws DBALException If not supported on this platform.
940
     */
941 43772
    public function getDateAddDaysExpression(string $date, string $days) : string
942
    {
943 43772
        return $this->getDateArithmeticIntervalExpression($date, '+', $days, DateIntervalUnit::DAY);
944
    }
945
946
    /**
947
     * Returns the SQL to subtract the number of given days to a date.
948
     *
949
     * @param string $date SQL expression producing the date.
950
     * @param string $days SQL expression producing the number of days.
951
     *
952
     * @throws DBALException If not supported on this platform.
953
     */
954 43722
    public function getDateSubDaysExpression(string $date, string $days) : string
955
    {
956 43722
        return $this->getDateArithmeticIntervalExpression($date, '-', $days, DateIntervalUnit::DAY);
957
    }
958
959
    /**
960
     * Returns the SQL to add the number of given weeks to a date.
961
     *
962
     * @param string $date  SQL expression producing the date.
963
     * @param string $weeks SQL expression producing the number of weeks.
964
     *
965
     * @throws DBALException If not supported on this platform.
966
     */
967 43674
    public function getDateAddWeeksExpression(string $date, string $weeks) : string
968
    {
969 43674
        return $this->getDateArithmeticIntervalExpression($date, '+', $weeks, DateIntervalUnit::WEEK);
970
    }
971
972
    /**
973
     * Returns the SQL to subtract the number of given weeks from a date.
974
     *
975
     * @param string $date  SQL expression producing the date.
976
     * @param string $weeks SQL expression producing the number of weeks.
977
     *
978
     * @throws DBALException If not supported on this platform.
979
     */
980 43626
    public function getDateSubWeeksExpression(string $date, string $weeks) : string
981
    {
982 43626
        return $this->getDateArithmeticIntervalExpression($date, '-', $weeks, DateIntervalUnit::WEEK);
983
    }
984
985
    /**
986
     * Returns the SQL to add the number of given months to a date.
987
     *
988
     * @param string $date   SQL expression producing the date.
989
     * @param string $months SQL expression producing the number of months.
990
     *
991
     * @throws DBALException If not supported on this platform.
992
     */
993 43578
    public function getDateAddMonthExpression(string $date, string $months) : string
994
    {
995 43578
        return $this->getDateArithmeticIntervalExpression($date, '+', $months, DateIntervalUnit::MONTH);
996
    }
997
998
    /**
999
     * Returns the SQL to subtract the number of given months to a date.
1000
     *
1001
     * @param string $date   SQL expression producing the date.
1002
     * @param string $months SQL expression producing the number of months.
1003
     *
1004
     * @throws DBALException If not supported on this platform.
1005
     */
1006 43530
    public function getDateSubMonthExpression(string $date, string $months) : string
1007
    {
1008 43530
        return $this->getDateArithmeticIntervalExpression($date, '-', $months, DateIntervalUnit::MONTH);
1009
    }
1010
1011
    /**
1012
     * Returns the SQL to add the number of given quarters to a date.
1013
     *
1014
     * @param string $date     SQL expression producing the date.
1015
     * @param string $quarters SQL expression producing the number of quarters.
1016
     *
1017
     * @throws DBALException If not supported on this platform.
1018
     */
1019 43482
    public function getDateAddQuartersExpression(string $date, string $quarters) : string
1020
    {
1021 43482
        return $this->getDateArithmeticIntervalExpression($date, '+', $quarters, DateIntervalUnit::QUARTER);
1022
    }
1023
1024
    /**
1025
     * Returns the SQL to subtract the number of given quarters from a date.
1026
     *
1027
     * @param string $date     SQL expression producing the date.
1028
     * @param string $quarters SQL expression producing the number of quarters.
1029
     *
1030
     * @throws DBALException If not supported on this platform.
1031
     */
1032 43434
    public function getDateSubQuartersExpression(string $date, string $quarters) : string
1033
    {
1034 43434
        return $this->getDateArithmeticIntervalExpression($date, '-', $quarters, DateIntervalUnit::QUARTER);
1035
    }
1036
1037
    /**
1038
     * Returns the SQL to add the number of given years to a date.
1039
     *
1040
     * @param string $date  SQL expression producing the date.
1041
     * @param string $years SQL expression producing the number of years.
1042
     *
1043
     * @throws DBALException If not supported on this platform.
1044
     */
1045 43386
    public function getDateAddYearsExpression(string $date, string $years) : string
1046
    {
1047 43386
        return $this->getDateArithmeticIntervalExpression($date, '+', $years, DateIntervalUnit::YEAR);
1048
    }
1049
1050
    /**
1051
     * Returns the SQL to subtract the number of given years from a date.
1052
     *
1053
     * @param string $date  SQL expression producing the date.
1054
     * @param string $years SQL expression producing the number of years.
1055
     *
1056
     * @throws DBALException If not supported on this platform.
1057
     */
1058 43338
    public function getDateSubYearsExpression(string $date, string $years) : string
1059
    {
1060 43338
        return $this->getDateArithmeticIntervalExpression($date, '-', $years, DateIntervalUnit::YEAR);
1061
    }
1062
1063
    /**
1064
     * Returns the SQL for a date arithmetic expression.
1065
     *
1066
     * @param string $date     SQL expression representing a date to perform the arithmetic operation on.
1067
     * @param string $operator The arithmetic operator (+ or -).
1068
     * @param string $interval SQL expression representing the value of the interval that shall be calculated
1069
     *                         into the date.
1070
     * @param string $unit     The unit of the interval that shall be calculated into the date.
1071
     *                         One of the DATE_INTERVAL_UNIT_* constants.
1072
     *
1073
     * @throws DBALException If not supported on this platform.
1074
     */
1075
    protected function getDateArithmeticIntervalExpression(string $date, string $operator, string $interval, string $unit) : string
0 ignored issues
show
Unused Code introduced by
The parameter $operator is not used and could be removed. ( Ignorable by Annotation )

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

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

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

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

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

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

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

Loading history...
1076
    {
1077
        throw NotSupported::new(__METHOD__);
1078
    }
1079
1080
    /**
1081
     * Generates the SQL expression which represents the given date interval multiplied by a number
1082
     *
1083
     * @param string $interval   SQL expression describing the interval value
1084
     * @param int    $multiplier Interval multiplier
1085
     *
1086
     * @throws DBALException
1087
     */
1088 40389
    protected function multiplyInterval(string $interval, int $multiplier) : string
1089
    {
1090 40389
        return sprintf('(%s * %d)', $interval, $multiplier);
1091
    }
1092
1093
    /**
1094
     * Returns the SQL bit AND comparison expression.
1095
     *
1096
     * @param string $value1 SQL expression producing the first value.
1097
     * @param string $value2 SQL expression producing the second value.
1098
     */
1099 42802
    public function getBitAndComparisonExpression(string $value1, string $value2) : string
1100
    {
1101 42802
        return '(' . $value1 . ' & ' . $value2 . ')';
1102
    }
1103
1104
    /**
1105
     * Returns the SQL bit OR comparison expression.
1106
     *
1107
     * @param string $value1 SQL expression producing the first value.
1108
     * @param string $value2 SQL expression producing the second value.
1109
     */
1110 39998
    public function getBitOrComparisonExpression(string $value1, string $value2) : string
1111
    {
1112 39998
        return '(' . $value1 . ' | ' . $value2 . ')';
1113
    }
1114
1115
    /**
1116
     * Returns the FOR UPDATE expression.
1117
     */
1118 32005
    public function getForUpdateSQL() : string
1119
    {
1120 32005
        return 'FOR UPDATE';
1121
    }
1122
1123
    /**
1124
     * Honors that some SQL vendors such as MsSql use table hints for locking instead of the ANSI SQL FOR UPDATE specification.
1125
     *
1126
     * @param string   $fromClause The FROM clause to append the hint for the given lock mode to.
1127
     * @param int|null $lockMode   One of the Doctrine\DBAL\LockMode::* constants. If null is given, nothing will
1128
     *                             be appended to the FROM clause.
1129
     */
1130 33605
    public function appendLockHint(string $fromClause, ?int $lockMode) : string
0 ignored issues
show
Unused Code introduced by
The parameter $lockMode is not used and could be removed. ( Ignorable by Annotation )

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

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

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

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

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

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

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

Loading history...
1460
    {
1461
        throw NotSupported::new(__METHOD__);
1462
    }
1463
1464
    /**
1465
     * Returns the SQL to change a sequence on this platform.
1466
     *
1467
     * @throws DBALException If not supported on this platform.
1468
     */
1469
    public function getAlterSequenceSQL(Sequence $sequence) : string
0 ignored issues
show
Unused Code introduced by
The parameter $sequence is not used and could be removed. ( Ignorable by Annotation )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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