Completed
Pull Request — master (#3512)
by David
61:25
created

AbstractPlatform   F

Complexity

Total Complexity 391

Size/Duplication

Total Lines 3571
Duplicated Lines 0 %

Test Coverage

Coverage 80.12%

Importance

Changes 0
Metric Value
wmc 391
eloc 663
dl 0
loc 3571
ccs 673
cts 840
cp 0.8012
rs 1.937
c 0
b 0
f 0

210 Methods

Rating   Name   Duplication   Size   Complexity  
A getTemporaryTableSQL() 0 3 1
A getEventManager() 0 3 1
A initializeCommentedDoctrineTypes() 0 12 3
A registerDoctrineTypeMapping() 0 20 4
A getGuidTypeDeclarationSQL() 0 6 1
A getBinaryTypeDeclarationSQLSnippet() 0 3 1
A getVarcharTypeDeclarationSQLSnippet() 0 3 1
A hasDoctrineTypeMappingFor() 0 9 2
A __construct() 0 2 1
A initializeAllDoctrineTypeMappings() 0 7 3
A getDoctrineTypeMapping() 0 13 3
A getVarcharTypeDeclarationSQL() 0 17 4
A setEventManager() 0 3 1
A getBinaryTypeDeclarationSQL() 0 23 4
A getJsonTypeDeclarationSQL() 0 3 1
A getWriteLockSQL() 0 3 1
A getCharMaxLength() 0 3 1
A getLtrimExpression() 0 3 1
A getCosExpression() 0 3 1
A getForUpdateSQL() 0 3 1
A getVarcharMaxLength() 0 3 1
A getSqrtExpression() 0 3 1
A getDateSubMonthExpression() 0 3 1
A getDateAddYearsExpression() 0 3 1
A getGuidExpression() 0 3 1
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 getBinaryDefaultLength() 0 3 1
A getSumExpression() 0 3 1
A appendLockHint() 0 3 1
A markDoctrineTypeCommented() 0 9 3
A getSqlCommentEndString() 0 3 1
A getDateDiffExpression() 0 3 1
A getPiExpression() 0 3 1
A getAvgExpression() 0 3 1
A getBinaryMaxLength() 0 3 1
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 getModExpression() 0 3 1
A getDropConstraintSQL() 0 14 3
A getDateSubQuartersExpression() 0 3 1
A getDateAddMonthExpression() 0 3 1
A getMaxExpression() 0 3 1
A getBitAndComparisonExpression() 0 3 1
B getDropTableSQL() 0 28 7
A getDateAddWeeksExpression() 0 3 1
A getDropIndexSQL() 0 9 3
A getDateSubMinutesExpression() 0 3 1
A getDateSubHourExpression() 0 3 1
A getLengthExpression() 0 3 1
A getVarcharDefaultLength() 0 3 1
A getDateSubWeeksExpression() 0 3 1
A getDateAddDaysExpression() 0 3 1
A getIdentifierQuoteCharacter() 0 3 1
A getDateSubDaysExpression() 0 3 1
A isCommentedDoctrineType() 0 9 2
A getRegexpExpression() 0 3 1
A getBitOrComparisonExpression() 0 3 1
A getSinExpression() 0 3 1
A getLowerExpression() 0 3 1
A getNowExpression() 0 3 1
A getDateSubSecondsExpression() 0 3 1
A getRoundExpression() 0 3 1
A getIsNotNullExpression() 0 3 1
A getRtrimExpression() 0 3 1
A getSubstringExpression() 0 7 2
A getDateArithmeticIntervalExpression() 0 3 1
A getDateAddMinutesExpression() 0 3 1
A getConcatExpression() 0 3 1
A getLocateExpression() 0 3 1
A getWildcards() 0 3 1
B getTrimExpression() 0 27 7
A getDateAddQuartersExpression() 0 3 1
A getDropTemporaryTableSQL() 0 3 1
A getNotExpression() 0 3 1
A getDateSubYearsExpression() 0 3 1
A getDropDatabaseSQL() 0 3 1
A getColumnComment() 0 9 2
A getDateAddSecondsExpression() 0 3 1
A getDateAddHourExpression() 0 3 1
A supportsAlterTable() 0 3 1
A supportsForeignKeyOnUpdate() 0 3 1
A getCheckDeclarationSQL() 0 18 5
A getCreateSchemaSQL() 0 3 1
A getFloatDeclarationSQL() 0 3 1
A getDefaultSchemaName() 0 3 1
A supportsCreateDropDatabase() 0 3 1
A onSchemaAlterTableRenameColumn() 0 16 3
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
F getCreateTableSQL() 0 93 24
A supportsTransactions() 0 3 1
A getPreAlterTableIndexForeignKeySQL() 0 22 6
A hasNativeGuidType() 0 3 1
A getRenameIndexSQL() 0 5 1
A fixSchemaElementName() 0 3 1
A getDateTimeTypeDeclarationSQL() 0 3 1
A supportsCommentOnStatement() 0 3 1
A convertFromBoolean() 0 3 2
A _getAlterTableIndexForeignKeySQL() 0 3 1
A getIdentityColumnNullInsertSQL() 0 3 1
A getCreateIndexSQL() 0 20 4
A getDropSequenceSQL() 0 3 1
A getDefaultTransactionIsolationLevel() 0 3 1
A getMaxIdentifierLength() 0 3 1
A _getTransactionIsolationLevelSQL() 0 13 5
A getForeignKeyDeclarationSQL() 0 6 1
A prefersIdentityColumns() 0 3 1
A getListNamespacesSQL() 0 3 1
A getUniqueConstraintDeclarationSQL() 0 12 2
A supportsViews() 0 3 1
A getCreatePrimaryKeySQL() 0 7 2
A canEmulateSchemas() 0 3 1
A getCommentOnTableSQL() 0 8 1
A getAlterTableSQL() 0 3 1
A getCreateViewSQL() 0 3 1
A getColumnCharsetDeclarationSQL() 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 getCreateForeignKeySQL() 0 7 2
A convertBooleansToDatabaseValue() 0 3 1
A supportsIdentityColumns() 0 3 1
A getIdentitySequenceName() 0 3 1
A getForeignKeyReferentialActionSQL() 0 12 6
A getSequenceNextValSQL() 0 3 1
A getCurrentDateSQL() 0 3 1
A getCustomTypeDeclarationSQL() 0 3 1
A supportsPartialIndexes() 0 3 1
A prefersSequences() 0 3 1
A getReservedKeywordsClass() 0 3 1
A getReservedKeywordsList() 0 17 3
A getStringLiteralQuoteCharacter() 0 3 1
A getColumnCollationDeclarationSQL() 0 3 2
F getColumnDeclarationSQL() 0 30 15
A getCommentOnColumnSQL() 0 10 1
C getDefaultValueDeclarationSQL() 0 35 12
A supportsSchemas() 0 3 1
A getSQLResultCasing() 0 3 1
A getDropViewSQL() 0 3 1
A onSchemaAlterTableAddColumn() 0 16 3
A getDateTimeFormatString() 0 3 1
A quoteSingleIdentifier() 0 5 1
A supportsSequences() 0 3 1
A getCurrentTimeSQL() 0 3 1
A supportsReleaseSavepoints() 0 3 1
A getDummySelectSQL() 0 5 2
A supportsIndexes() 0 3 1
A getIndexFieldDeclarationListSQL() 0 21 5
A getDateTypeDeclarationSQL() 0 3 1
A getCreateIndexSQLFlags() 0 3 2
A getAdvancedForeignKeyOptionsSQL() 0 11 4
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
B getPostAlterTableIndexForeignKeySQL() 0 38 8
C _getCreateTableSQL() 0 37 12
A onSchemaAlterTable() 0 16 3
A getListViewsSQL() 0 3 1
A getUniqueFieldDeclarationSQL() 0 3 1
A supportsForeignKeyConstraints() 0 3 1
A modifyLimitQuery() 0 23 5
A getTimeFormatString() 0 3 1
A getTimeTypeDeclarationSQL() 0 3 1
A supportsColumnLengthIndexes() 0 3 1
A getTemporaryTableName() 0 3 1
A getForeignKeyBaseDeclarationSQL() 0 22 5
A getCreateTemporaryTableSnippetSQL() 0 3 1
A getCreateSequenceSQL() 0 3 1
A getDateTimeTzFormatString() 0 3 1
A supportsGettingAffectedRows() 0 3 1
A getCurrentTimestampSQL() 0 3 1
A releaseSavePoint() 0 3 1
A getCreateConstraintSQL() 0 30 6
A rollbackSavePoint() 0 3 1
A getInlineColumnCommentSQL() 0 7 2
A getListTableConstraintsSQL() 0 3 1
A getAlterSequenceSQL() 0 3 1
A getIndexDeclarationSQL() 0 12 2
A getListTableIndexesSQL() 0 3 1
A getListTablesSQL() 0 3 1
A getEmptyIdentityInsertSQL() 0 3 1
A supportsInlineColumnComments() 0 3 1
A quoteIdentifier() 0 9 2
A doModifyLimitQuery() 0 11 3
A getPartialIndexSQL() 0 7 3
A onSchemaAlterTableRemoveColumn() 0 16 3
A escapeStringForLike() 0 6 1
A getColumnDeclarationListSQL() 0 9 2
A onSchemaAlterTableChangeColumn() 0 16 3
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
namespace Doctrine\DBAL\Platforms;
4
5
use Doctrine\Common\EventManager;
6
use Doctrine\DBAL\DBALException;
7
use Doctrine\DBAL\Event\SchemaAlterTableAddColumnEventArgs;
8
use Doctrine\DBAL\Event\SchemaAlterTableChangeColumnEventArgs;
9
use Doctrine\DBAL\Event\SchemaAlterTableEventArgs;
10
use Doctrine\DBAL\Event\SchemaAlterTableRemoveColumnEventArgs;
11
use Doctrine\DBAL\Event\SchemaAlterTableRenameColumnEventArgs;
12
use Doctrine\DBAL\Event\SchemaCreateTableColumnEventArgs;
13
use Doctrine\DBAL\Event\SchemaCreateTableEventArgs;
14
use Doctrine\DBAL\Event\SchemaDropTableEventArgs;
15
use Doctrine\DBAL\Events;
16
use Doctrine\DBAL\Platforms\Keywords\KeywordList;
17
use Doctrine\DBAL\Schema\Column;
18
use Doctrine\DBAL\Schema\ColumnDiff;
19
use Doctrine\DBAL\Schema\Constraint;
20
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
21
use Doctrine\DBAL\Schema\Identifier;
22
use Doctrine\DBAL\Schema\Index;
23
use Doctrine\DBAL\Schema\Sequence;
24
use Doctrine\DBAL\Schema\Table;
25
use Doctrine\DBAL\Schema\TableDiff;
26
use Doctrine\DBAL\TransactionIsolationLevel;
27
use Doctrine\DBAL\Types;
28
use Doctrine\DBAL\Types\Type;
29
use InvalidArgumentException;
30
use UnexpectedValueException;
31
use const E_USER_DEPRECATED;
32
use function addcslashes;
33
use function array_map;
34
use function array_merge;
35
use function array_unique;
36
use function array_values;
37
use function assert;
38
use function count;
39
use function explode;
40
use function func_get_arg;
41
use function func_get_args;
42
use function func_num_args;
43
use function implode;
44
use function in_array;
45
use function is_array;
46
use function is_bool;
47
use function is_int;
48
use function is_string;
49
use function preg_quote;
50
use function preg_replace;
51
use function sprintf;
52
use function str_replace;
53
use function strlen;
54
use function strpos;
55
use function strtolower;
56
use function strtoupper;
57
use function trigger_error;
58
59
/**
60
 * Base class for all DatabasePlatforms. The DatabasePlatforms are the central
61
 * point of abstraction of platform-specific behaviors, features and SQL dialects.
62
 * They are a passive source of information.
63
 *
64
 * @todo Remove any unnecessary methods.
65
 */
66
abstract class AbstractPlatform
67
{
68
    public const CREATE_INDEXES = 1;
69
70
    public const CREATE_FOREIGNKEYS = 2;
71
72
    /**
73
     * @deprecated Use DateIntervalUnit::INTERVAL_UNIT_SECOND.
74
     */
75
    public const DATE_INTERVAL_UNIT_SECOND = DateIntervalUnit::SECOND;
76
77
    /**
78
     * @deprecated Use DateIntervalUnit::MINUTE.
79
     */
80
    public const DATE_INTERVAL_UNIT_MINUTE = DateIntervalUnit::MINUTE;
81
82
    /**
83
     * @deprecated Use DateIntervalUnit::HOUR.
84
     */
85
    public const DATE_INTERVAL_UNIT_HOUR = DateIntervalUnit::HOUR;
86
87
    /**
88
     * @deprecated Use DateIntervalUnit::DAY.
89
     */
90
    public const DATE_INTERVAL_UNIT_DAY = DateIntervalUnit::DAY;
91
92
    /**
93
     * @deprecated Use DateIntervalUnit::WEEK.
94
     */
95
    public const DATE_INTERVAL_UNIT_WEEK = DateIntervalUnit::WEEK;
96
97
    /**
98
     * @deprecated Use DateIntervalUnit::MONTH.
99
     */
100
    public const DATE_INTERVAL_UNIT_MONTH = DateIntervalUnit::MONTH;
101
102
    /**
103
     * @deprecated Use DateIntervalUnit::QUARTER.
104
     */
105
    public const DATE_INTERVAL_UNIT_QUARTER = DateIntervalUnit::QUARTER;
106
107
    /**
108
     * @deprecated Use DateIntervalUnit::QUARTER.
109
     */
110
    public const DATE_INTERVAL_UNIT_YEAR = DateIntervalUnit::YEAR;
111
112
    /**
113
     * @deprecated Use TrimMode::UNSPECIFIED.
114
     */
115
    public const TRIM_UNSPECIFIED = TrimMode::UNSPECIFIED;
116
117
    /**
118
     * @deprecated Use TrimMode::LEADING.
119
     */
120
    public const TRIM_LEADING = TrimMode::LEADING;
121
122
    /**
123
     * @deprecated Use TrimMode::TRAILING.
124
     */
125
    public const TRIM_TRAILING = TrimMode::TRAILING;
126
127
    /**
128
     * @deprecated Use TrimMode::BOTH.
129
     */
130
    public const TRIM_BOTH = TrimMode::BOTH;
131
132
    /** @var string[]|null */
133
    protected $doctrineTypeMapping = null;
134
135
    /**
136
     * Contains a list of all columns that should generate parseable column comments for type-detection
137
     * in reverse engineering scenarios.
138
     *
139
     * @var string[]|null
140
     */
141
    protected $doctrineTypeComments = null;
142
143
    /** @var EventManager */
144
    protected $_eventManager;
145
146
    /**
147
     * Holds the KeywordList instance for the current platform.
148
     *
149
     * @var KeywordList|null
150
     */
151
    protected $_keywords;
152
153 85042
    public function __construct()
154
    {
155 85042
    }
156
157
    /**
158
     * Sets the EventManager used by the Platform.
159
     */
160 78280
    public function setEventManager(EventManager $eventManager)
161
    {
162 78280
        $this->_eventManager = $eventManager;
163 78280
    }
164
165
    /**
166
     * Gets the EventManager used by the Platform.
167
     *
168
     * @return EventManager
169
     */
170 75238
    public function getEventManager()
171
    {
172 75238
        return $this->_eventManager;
173
    }
174
175
    /**
176
     * Returns the SQL snippet that declares a boolean column.
177
     *
178
     * @param mixed[] $columnDef
179
     *
180
     * @return string
181
     */
182
    abstract public function getBooleanTypeDeclarationSQL(array $columnDef);
183
184
    /**
185
     * Returns the SQL snippet that declares a 4 byte integer column.
186
     *
187
     * @param mixed[] $columnDef
188
     *
189
     * @return string
190
     */
191
    abstract public function getIntegerTypeDeclarationSQL(array $columnDef);
192
193
    /**
194
     * Returns the SQL snippet that declares an 8 byte integer column.
195
     *
196
     * @param mixed[] $columnDef
197
     *
198
     * @return string
199
     */
200
    abstract public function getBigIntTypeDeclarationSQL(array $columnDef);
201
202
    /**
203
     * Returns the SQL snippet that declares a 2 byte integer column.
204
     *
205
     * @param mixed[] $columnDef
206
     *
207
     * @return string
208
     */
209
    abstract public function getSmallIntTypeDeclarationSQL(array $columnDef);
210
211
    /**
212
     * Returns the SQL snippet that declares common properties of an integer column.
213
     *
214
     * @param mixed[] $columnDef
215
     *
216
     * @return string
217
     */
218
    abstract protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef);
219
220
    /**
221
     * Lazy load Doctrine Type Mappings.
222
     *
223
     * @return void
224
     */
225
    abstract protected function initializeDoctrineTypeMappings();
226
227
    /**
228
     * Initializes Doctrine Type Mappings with the platform defaults
229
     * and with all additional type mappings.
230
     *
231
     * @return void
232
     */
233 75352
    private function initializeAllDoctrineTypeMappings()
234
    {
235 75352
        $this->initializeDoctrineTypeMappings();
236
237 75352
        foreach (Type::getTypesMap() as $typeName => $className) {
238 75352
            foreach (Type::getType($typeName)->getMappedDatabaseTypes($this) as $dbType) {
239 42114
                $this->doctrineTypeMapping[$dbType] = $typeName;
240
            }
241
        }
242 75352
    }
243
244
    /**
245
     * Returns the SQL snippet used to declare a VARCHAR column type.
246
     *
247
     * @param mixed[] $field
248
     *
249
     * @return string
250
     */
251 77628
    public function getVarcharTypeDeclarationSQL(array $field)
252
    {
253 77628
        if (! isset($field['length'])) {
254 73822
            $field['length'] = $this->getVarcharDefaultLength();
255
        }
256
257 77628
        $fixed = $field['fixed'] ?? false;
258
259 77628
        $maxLength = $fixed
260 75399
            ? $this->getCharMaxLength()
261 77628
            : $this->getVarcharMaxLength();
262
263 77628
        if ($field['length'] > $maxLength) {
264
            return $this->getClobTypeDeclarationSQL($field);
265
        }
266
267 77628
        return $this->getVarcharTypeDeclarationSQLSnippet($field['length'], $fixed);
268
    }
269
270
    /**
271
     * Returns the SQL snippet used to declare a BINARY/VARBINARY column type.
272
     *
273
     * @param mixed[] $field The column definition.
274
     *
275
     * @return string
276
     */
277 73988
    public function getBinaryTypeDeclarationSQL(array $field)
278
    {
279 73988
        if (! isset($field['length'])) {
280 73931
            $field['length'] = $this->getBinaryDefaultLength();
281
        }
282
283 73988
        $fixed = $field['fixed'] ?? false;
284
285 73988
        $maxLength = $this->getBinaryMaxLength();
286
287 73988
        if ($field['length'] > $maxLength) {
288 71600
            if ($maxLength > 0) {
289 71324
                @trigger_error(sprintf(
290 24
                    'Binary field length %d is greater than supported by the platform (%d). Reduce the field length or use a BLOB field instead.',
291 71324
                    $field['length'],
292 71324
                    $maxLength
293 71324
                ), E_USER_DEPRECATED);
294
            }
295
296 71600
            return $this->getBlobTypeDeclarationSQL($field);
297
        }
298
299 73964
        return $this->getBinaryTypeDeclarationSQLSnippet($field['length'], $fixed);
300
    }
301
302
    /**
303
     * Returns the SQL snippet to declare a GUID/UUID field.
304
     *
305
     * By default this maps directly to a CHAR(36) and only maps to more
306
     * special datatypes when the underlying databases support this datatype.
307
     *
308
     * @param mixed[] $field
309
     *
310
     * @return string
311
     */
312 73125
    public function getGuidTypeDeclarationSQL(array $field)
313
    {
314 73125
        $field['length'] = 36;
315 73125
        $field['fixed']  = true;
316
317 73125
        return $this->getVarcharTypeDeclarationSQL($field);
318
    }
319
320
    /**
321
     * Returns the SQL snippet to declare a JSON field.
322
     *
323
     * By default this maps directly to a CLOB and only maps to more
324
     * special datatypes when the underlying databases support this datatype.
325
     *
326
     * @param mixed[] $field
327
     *
328
     * @return string
329
     */
330 71273
    public function getJsonTypeDeclarationSQL(array $field)
331
    {
332 71273
        return $this->getClobTypeDeclarationSQL($field);
333
    }
334
335
    /**
336
     * @param int  $length
337
     * @param bool $fixed
338
     *
339
     * @return string
340
     *
341
     * @throws DBALException If not supported on this platform.
342
     */
343
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
0 ignored issues
show
Unused Code introduced by
The parameter $fixed is not used and could be removed. ( Ignorable by Annotation )

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

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

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

Loading history...
344
    {
345
        throw DBALException::notSupported('VARCHARs not supported by Platform.');
346
    }
347
348
    /**
349
     * Returns the SQL snippet used to declare a BINARY/VARBINARY column type.
350
     *
351
     * @param int  $length The length of the column.
352
     * @param bool $fixed  Whether the column length is fixed.
353
     *
354
     * @return string
355
     *
356
     * @throws DBALException If not supported on this platform.
357
     */
358
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
0 ignored issues
show
Unused Code introduced by
The parameter $fixed is not used and could be removed. ( Ignorable by Annotation )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
Unused Code introduced by
The parameter $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

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

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

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

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

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

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

Loading history...
1311
    {
1312
        throw DBALException::notSupported(__METHOD__);
1313
    }
1314
1315
    /**
1316
     * Returns the SQL bit AND comparison expression.
1317
     *
1318
     * @param string $value1
1319
     * @param string $value2
1320
     *
1321
     * @return string
1322
     */
1323 75782
    public function getBitAndComparisonExpression($value1, $value2)
1324
    {
1325 75782
        return '(' . $value1 . ' & ' . $value2 . ')';
1326
    }
1327
1328
    /**
1329
     * Returns the SQL bit OR comparison expression.
1330
     *
1331
     * @param string $value1
1332
     * @param string $value2
1333
     *
1334
     * @return string
1335
     */
1336 75781
    public function getBitOrComparisonExpression($value1, $value2)
1337
    {
1338 75781
        return '(' . $value1 . ' | ' . $value2 . ')';
1339
    }
1340
1341
    /**
1342
     * Returns the FOR UPDATE expression.
1343
     *
1344
     * @return string
1345
     */
1346 61020
    public function getForUpdateSQL()
1347
    {
1348 61020
        return 'FOR UPDATE';
1349
    }
1350
1351
    /**
1352
     * Honors that some SQL vendors such as MsSql use table hints for locking instead of the ANSI SQL FOR UPDATE specification.
1353
     *
1354
     * @param string   $fromClause The FROM clause to append the hint for the given lock mode to.
1355
     * @param int|null $lockMode   One of the Doctrine\DBAL\LockMode::* constants. If null is given, nothing will
1356
     *                             be appended to the FROM clause.
1357
     *
1358
     * @return string
1359
     */
1360 63925
    public function appendLockHint($fromClause, $lockMode)
0 ignored issues
show
Unused Code introduced by
The parameter $lockMode is not used and could be removed. ( Ignorable by Annotation )

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

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

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

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

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

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

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

Loading history...
1747
    {
1748
        throw DBALException::notSupported(__METHOD__);
1749
    }
1750
1751 70151
    /**
1752
     * Returns the SQL to change a sequence on this platform.
1753 70151
     *
1754
     * @return string
1755
     *
1756
     * @throws DBALException If not supported on this platform.
1757 70151
     */
1758
    public function getAlterSequenceSQL(Sequence $sequence)
0 ignored issues
show
Unused Code introduced by
The parameter $sequence is not used and could be removed. ( Ignorable by Annotation )

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

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

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

Loading history...
1759 70151
    {
1760
        throw DBALException::notSupported(__METHOD__);
1761 70151
    }
1762 70151
1763 70151
    /**
1764 70151
     * Returns the SQL to create a constraint on a table on this platform.
1765 70101
     *
1766 70101
     * @param Table|string $table
1767
     *
1768
     * @return string
1769 70151
     *
1770
     * @throws InvalidArgumentException
1771
     */
1772 70101
    public function getCreateConstraintSQL(Constraint $constraint, $table)
1773 70101
    {
1774
        if ($table instanceof Table) {
1775 70101
            $table = $table->getQuotedName($this);
1776 70101
        }
1777
1778 70151
        $query = 'ALTER TABLE ' . $table . ' ADD CONSTRAINT ' . $constraint->getQuotedName($this);
1779
1780 70151
        $columnList = '(' . implode(', ', $constraint->getQuotedColumns($this)) . ')';
1781
1782
        $referencesClause = '';
1783
        if ($constraint instanceof Index) {
1784
            if ($constraint->isPrimary()) {
1785
                $query .= ' PRIMARY KEY';
1786
            } elseif ($constraint->isUnique()) {
1787
                $query .= ' UNIQUE';
1788
            } else {
1789
                throw new InvalidArgumentException(
1790
                    'Can only create primary or unique constraints, no common indexes with getCreateConstraintSQL().'
1791
                );
1792 75033
            }
1793
        } elseif ($constraint instanceof ForeignKeyConstraint) {
1794 75033
            $query .= ' FOREIGN KEY';
1795 74088
1796
            $referencesClause = ' REFERENCES ' . $constraint->getQuotedForeignTableName($this) .
1797 75033
                ' (' . implode(', ', $constraint->getQuotedForeignColumns($this)) . ')';
1798 75033
        }
1799
        $query .= ' ' . $columnList . $referencesClause;
1800 75033
1801
        return $query;
1802
    }
1803
1804 75033
    /**
1805 68192
     * Returns the SQL to create an index on a table on this platform.
1806
     *
1807
     * @param Table|string $table The name of the table on which the index is to be created.
1808 74995
     *
1809 74995
     * @return string
1810
     *
1811 74995
     * @throws InvalidArgumentException
1812
     */
1813
    public function getCreateIndexSQL(Index $index, $table)
1814
    {
1815
        if ($table instanceof Table) {
1816
            $table = $table->getQuotedName($this);
1817
        }
1818
        $name    = $index->getQuotedName($this);
1819 76263
        $columns = $index->getColumns();
1820
1821 76263
        if (count($columns) === 0) {
1822 58251
            throw new InvalidArgumentException("Incomplete definition. 'columns' required.");
1823
        }
1824
1825 76253
        if ($index->isPrimary()) {
1826
            return $this->getCreatePrimaryKeySQL($index, $table);
1827
        }
1828
1829
        $query  = 'CREATE ' . $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name . ' ON ' . $table;
1830
        $query .= ' (' . $this->getIndexFieldDeclarationListSQL($index) . ')' . $this->getPartialIndexSQL($index);
1831
1832
        return $query;
1833 73293
    }
1834
1835 73293
    /**
1836
     * Adds condition for partial index.
1837
     *
1838
     * @return string
1839
     */
1840
    protected function getPartialIndexSQL(Index $index)
1841
    {
1842
        if ($this->supportsPartialIndexes() && $index->hasOption('where')) {
1843
            return ' WHERE ' . $index->getOption('where');
1844
        }
1845 71534
1846
        return '';
1847 71534
    }
1848
1849
    /**
1850
     * Adds additional flags for index generation.
1851 71534
     *
1852
     * @return string
1853
     */
1854
    protected function getCreateIndexSQLFlags(Index $index)
1855
    {
1856
        return $index->isUnique() ? 'UNIQUE ' : '';
1857
    }
1858
1859
    /**
1860
     * Returns the SQL to create an unnamed primary key constraint.
1861
     *
1862
     * @param Table|string $table
1863 69495
     *
1864
     * @return string
1865 69495
     */
1866
    public function getCreatePrimaryKeySQL(Index $index, $table)
1867
    {
1868
        if ($table instanceof Table) {
1869
            $table = $table->getQuotedName($this);
1870
        }
1871
1872
        return 'ALTER TABLE ' . $table . ' ADD PRIMARY KEY (' . $this->getIndexFieldDeclarationListSQL($index) . ')';
1873
    }
1874
1875
    /**
1876
     * Returns the SQL to create a named schema.
1877
     *
1878
     * @param string $schemaName
1879
     *
1880
     * @return string
1881 77808
     *
1882
     * @throws DBALException If not supported on this platform.
1883 77808
     */
1884 71659
    public function getCreateSchemaSQL($schemaName)
0 ignored issues
show
Unused Code introduced by
The parameter $schemaName 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

1884
    public function getCreateSchemaSQL(/** @scrutinizer ignore-unused */ $schemaName)

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...
1885
    {
1886 71659
        throw DBALException::notSupported(__METHOD__);
1887
    }
1888
1889 77808
    /**
1890
     * Quotes a string so that it can be safely used as a table or column name,
1891
     * even if it is a reserved word of the platform. This also detects identifier
1892
     * chains separated by dot and quotes them independently.
1893
     *
1894
     * NOTE: Just because you CAN use quoted identifiers doesn't mean
1895
     * you SHOULD use them. In general, they end up causing way more
1896
     * problems than they solve.
1897
     *
1898
     * @param string $str The identifier name to be quoted.
1899 77385
     *
1900
     * @return string The quoted identifier string.
1901 77385
     */
1902
    public function quoteIdentifier($str)
1903 77385
    {
1904
        if (strpos($str, '.') !== false) {
1905
            $parts = array_map([$this, 'quoteSingleIdentifier'], explode('.', $str));
1906
1907
            return implode('.', $parts);
1908
        }
1909
1910
        return $this->quoteSingleIdentifier($str);
1911
    }
1912
1913
    /**
1914 75898
     * Quotes a single identifier (no dot chain separation).
1915
     *
1916 75898
     * @param string $str The identifier name to be quoted.
1917 2977
     *
1918
     * @return string The quoted identifier string.
1919
     */
1920 75898
    public function quoteSingleIdentifier($str)
1921
    {
1922
        $c = $this->getIdentifierQuoteCharacter();
1923
1924
        return $c . str_replace($c, $c . $c, $str) . $c;
1925
    }
1926
1927
    /**
1928
     * Returns the SQL to create a new foreign key.
1929
     *
1930
     * @param ForeignKeyConstraint $foreignKey The foreign key constraint.
1931
     * @param Table|string         $table      The name of the table on which the foreign key is to be created.
1932
     *
1933
     * @return string
1934
     */
1935
    public function getCreateForeignKeySQL(ForeignKeyConstraint $foreignKey, $table)
1936
    {
1937
        if ($table instanceof Table) {
1938
            $table = $table->getQuotedName($this);
1939
        }
1940
1941
        return 'ALTER TABLE ' . $table . ' ADD ' . $this->getForeignKeyDeclarationSQL($foreignKey);
1942 75013
    }
1943
1944 75013
    /**
1945 70160
     * Gets the SQL statements for altering an existing table.
1946
     *
1947
     * This method returns an array of SQL statements, since some platforms need several statements.
1948 74853
     *
1949 74817
     * @return string[]
1950
     *
1951
     * @throws DBALException If not supported on this platform.
1952 69936
     */
1953 69936
    public function getAlterTableSQL(TableDiff $diff)
1954
    {
1955 69936
        throw DBALException::notSupported(__METHOD__);
1956
    }
1957 69936
1958
    /**
1959
     * @param mixed[] $columnSql
1960
     *
1961
     * @return bool
1962
     */
1963
    protected function onSchemaAlterTableAddColumn(Column $column, TableDiff $diff, &$columnSql)
1964
    {
1965 74189
        if ($this->_eventManager === null) {
1966
            return false;
1967 74189
        }
1968 70114
1969
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableAddColumn)) {
1970
            return false;
1971 74075
        }
1972 74039
1973
        $eventArgs = new SchemaAlterTableAddColumnEventArgs($column, $diff, $this);
1974
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableAddColumn, $eventArgs);
1975 69936
1976 69936
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
1977
1978 69936
        return $eventArgs->isDefaultPrevented();
1979
    }
1980 69936
1981
    /**
1982
     * @param string[] $columnSql
1983
     *
1984
     * @return bool
1985
     */
1986
    protected function onSchemaAlterTableRemoveColumn(Column $column, TableDiff $diff, &$columnSql)
1987
    {
1988 75067
        if ($this->_eventManager === null) {
1989
            return false;
1990 75067
        }
1991 71582
1992
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableRemoveColumn)) {
1993
            return false;
1994 74735
        }
1995 74699
1996
        $eventArgs = new SchemaAlterTableRemoveColumnEventArgs($column, $diff, $this);
1997
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableRemoveColumn, $eventArgs);
1998 69936
1999 69936
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
2000
2001 69936
        return $eventArgs->isDefaultPrevented();
2002
    }
2003 69936
2004
    /**
2005
     * @param string[] $columnSql
2006
     *
2007
     * @return bool
2008
     */
2009
    protected function onSchemaAlterTableChangeColumn(ColumnDiff $columnDiff, TableDiff $diff, &$columnSql)
2010
    {
2011
        if ($this->_eventManager === null) {
2012 73937
            return false;
2013
        }
2014 73937
2015 69391
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableChangeColumn)) {
2016
            return false;
2017
        }
2018 73821
2019 70989
        $eventArgs = new SchemaAlterTableChangeColumnEventArgs($columnDiff, $diff, $this);
2020
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableChangeColumn, $eventArgs);
2021
2022 69936
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
2023 69936
2024
        return $eventArgs->isDefaultPrevented();
2025 69936
    }
2026
2027 69936
    /**
2028
     * @param string   $oldColumnName
2029
     * @param string[] $columnSql
2030
     *
2031
     * @return bool
2032
     */
2033
    protected function onSchemaAlterTableRenameColumn($oldColumnName, Column $column, TableDiff $diff, &$columnSql)
2034
    {
2035 75829
        if ($this->_eventManager === null) {
2036
            return false;
2037 75829
        }
2038 71920
2039
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTableRenameColumn)) {
2040
            return false;
2041 75159
        }
2042 75123
2043
        $eventArgs = new SchemaAlterTableRenameColumnEventArgs($oldColumnName, $column, $diff, $this);
2044
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableRenameColumn, $eventArgs);
2045 69936
2046 69936
        $columnSql = array_merge($columnSql, $eventArgs->getSql());
2047
2048 69936
        return $eventArgs->isDefaultPrevented();
2049
    }
2050 69936
2051
    /**
2052
     * @param string[] $sql
2053
     *
2054
     * @return bool
2055
     */
2056 75680
    protected function onSchemaAlterTable(TableDiff $diff, &$sql)
2057
    {
2058 75680
        if ($this->_eventManager === null) {
2059
            return false;
2060 75680
        }
2061 75680
2062 75680
        if (! $this->_eventManager->hasListeners(Events::onSchemaAlterTable)) {
2063 73751
            return false;
2064
        }
2065 75680
2066 69040
        $eventArgs = new SchemaAlterTableEventArgs($diff, $this);
2067
        $this->_eventManager->dispatchEvent(Events::onSchemaAlterTable, $eventArgs);
2068
2069
        $sql = array_merge($sql, $eventArgs->getSql());
2070 75680
2071 74229
        return $eventArgs->isDefaultPrevented();
2072
    }
2073 75680
2074 73806
    /**
2075
     * @return string[]
2076
     */
2077 75680
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
2078
    {
2079
        $tableName = $diff->getName($this)->getQuotedName($this);
2080
2081
        $sql = [];
2082
        if ($this->supportsForeignKeyConstraints()) {
2083 75680
            foreach ($diff->removedForeignKeys as $foreignKey) {
2084
                $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
2085 75680
            }
2086 75680
            foreach ($diff->changedForeignKeys as $foreignKey) {
2087
                $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
2088 75680
            }
2089 70432
        }
2090
2091 75610
        foreach ($diff->removedIndexes as $index) {
2092
            $sql[] = $this->getDropIndexSQL($index, $tableName);
2093
        }
2094 75680
        foreach ($diff->changedIndexes as $index) {
2095 75680
            $sql[] = $this->getDropIndexSQL($index, $tableName);
2096 73848
        }
2097
2098
        return $sql;
2099 75680
    }
2100 69040
2101
    /**
2102
     * @return string[]
2103
     */
2104 75680
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff)
2105 73787
    {
2106
        $sql     = [];
2107
        $newName = $diff->getNewName();
2108 75680
2109 73806
        if ($newName !== false) {
2110
            $tableName = $newName->getQuotedName($this);
2111
        } else {
2112 75680
            $tableName = $diff->getName($this)->getQuotedName($this);
2113 73991
        }
2114 73991
2115 73991
        if ($this->supportsForeignKeyConstraints()) {
2116 73991
            foreach ($diff->addedForeignKeys as $foreignKey) {
2117
                $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
2118
            }
2119
2120 75680
            foreach ($diff->changedForeignKeys as $foreignKey) {
2121
                $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
2122
            }
2123
        }
2124
2125
        foreach ($diff->addedIndexes as $index) {
2126
            $sql[] = $this->getCreateIndexSQL($index, $tableName);
2127
        }
2128
2129
        foreach ($diff->changedIndexes as $index) {
2130
            $sql[] = $this->getCreateIndexSQL($index, $tableName);
2131
        }
2132 69174
2133
        foreach ($diff->renamedIndexes as $oldIndexName => $index) {
2134
            $oldIndexName = new Identifier($oldIndexName);
2135 69174
            $sql          = array_merge(
2136 69174
                $sql,
2137
                $this->getRenameIndexSQL($oldIndexName->getQuotedName($this), $index, $tableName)
2138
            );
2139
        }
2140
2141
        return $sql;
2142
    }
2143
2144
    /**
2145
     * Returns the SQL for renaming an index on a table.
2146
     *
2147
     * @param string $oldIndexName The name of the index to rename from.
2148
     * @param Index  $index        The definition of the index to rename to.
2149
     * @param string $tableName    The table to rename the given index on.
2150
     *
2151
     * @return string[] The sequence of SQL statements for renaming the given index.
2152
     */
2153
    protected function getRenameIndexSQL($oldIndexName, Index $index, $tableName)
2154
    {
2155
        return [
2156
            $this->getDropIndexSQL($oldIndexName, $tableName),
2157
            $this->getCreateIndexSQL($index, $tableName),
2158
        ];
2159
    }
2160
2161
    /**
2162
     * Common code for alter table statement generation that updates the changed Index and Foreign Key definitions.
2163
     *
2164
     * @return string[]
2165
     */
2166
    protected function _getAlterTableIndexForeignKeySQL(TableDiff $diff)
2167
    {
2168
        return array_merge($this->getPreAlterTableIndexForeignKeySQL($diff), $this->getPostAlterTableIndexForeignKeySQL($diff));
2169
    }
2170
2171
    /**
2172
     * Gets declaration of a number of fields in bulk.
2173
     *
2174
     * @param mixed[][] $fields A multidimensional associative array.
2175
     *                          The first dimension determines the field name, while the second
2176
     *                          dimension is keyed with the name of the properties
2177
     *                          of the field being declared as array indexes. Currently, the types
2178
     *                          of supported field properties are as follows:
2179 78106
     *
2180
     *      length
2181 78106
     *          Integer value that determines the maximum length of the text
2182
     *          field. If this argument is missing the field should be
2183 78106
     *          declared to have the longest length allowed by the DBMS.
2184 78106
     *
2185
     *      default
2186
     *          Text value to be used as default for this field.
2187 78106
     *
2188
     *      notnull
2189
     *          Boolean flag that indicates whether this field is constrained
2190
     *          to not be set to null.
2191
     *      charset
2192
     *          Text value with the default CHARACTER SET for this field.
2193
     *      collation
2194
     *          Text value with the default COLLATION for this field.
2195
     *      unique
2196
     *          unique constraint
2197
     *
2198
     * @return string
2199
     */
2200
    public function getColumnDeclarationListSQL(array $fields)
2201
    {
2202
        $queryFields = [];
2203
2204
        foreach ($fields as $fieldName => $field) {
2205
            $queryFields[] = $this->getColumnDeclarationSQL($fieldName, $field);
2206
        }
2207
2208
        return implode(', ', $queryFields);
2209
    }
2210
2211
    /**
2212
     * Obtains DBMS specific SQL code portion needed to declare a generic type
2213
     * field to be used in statements like CREATE TABLE.
2214
     *
2215
     * @param string  $name  The name the field to be declared.
2216
     * @param mixed[] $field An associative array with the name of the properties
2217
     *                       of the field being declared as array indexes. Currently, the types
2218
     *                       of supported field properties are as follows:
2219
     *
2220
     *      length
2221
     *          Integer value that determines the maximum length of the text
2222
     *          field. If this argument is missing the field should be
2223 77589
     *          declared to have the longest length allowed by the DBMS.
2224
     *
2225 77589
     *      default
2226 72174
     *          Text value to be used as default for this field.
2227
     *
2228 77561
     *      notnull
2229
     *          Boolean flag that indicates whether this field is constrained
2230 77561
     *          to not be set to null.
2231 77561
     *      charset
2232
     *          Text value with the default CHARACTER SET for this field.
2233 77561
     *      collation
2234 77561
     *          Text value with the default COLLATION for this field.
2235
     *      unique
2236 77561
     *          unique constraint
2237
     *      check
2238 77561
     *          column check constraint
2239 77561
     *      columnDefinition
2240
     *          a string that defines the complete column
2241 77561
     *
2242 77561
     * @return string DBMS specific SQL code portion that should be used to declare the column.
2243
     */
2244 77561
    public function getColumnDeclarationSQL($name, array $field)
2245 77561
    {
2246
        if (isset($field['columnDefinition'])) {
2247 77561
            $columnDef = $this->getCustomTypeDeclarationSQL($field);
2248 71331
        } else {
2249
            $default = $this->getDefaultValueDeclarationSQL($field);
2250
2251
            $charset = isset($field['charset']) && $field['charset'] ?
2252 77589
                ' ' . $this->getColumnCharsetDeclarationSQL($field['charset']) : '';
2253
2254
            $collation = isset($field['collation']) && $field['collation'] ?
2255
                ' ' . $this->getColumnCollationDeclarationSQL($field['collation']) : '';
2256
2257
            $notnull = isset($field['notnull']) && $field['notnull'] ? ' NOT NULL' : '';
2258
2259
            $unique = isset($field['unique']) && $field['unique'] ?
2260
                ' ' . $this->getUniqueFieldDeclarationSQL() : '';
2261
2262 74786
            $check = isset($field['check']) && $field['check'] ?
2263
                ' ' . $field['check'] : '';
2264 74786
2265 74786
            $typeDecl  = $field['type']->getSQLDeclaration($field, $this);
2266 74786
            $columnDef = $typeDecl . $charset . $default . $notnull . $unique . $check . $collation;
2267 74786
2268
            if ($this->supportsInlineColumnComments() && isset($field['comment']) && $field['comment'] !== '') {
2269 74786
                $columnDef .= ' ' . $this->getInlineColumnCommentSQL($field['comment']);
2270
            }
2271
        }
2272
2273
        return $name . ' ' . $columnDef;
2274
    }
2275
2276
    /**
2277
     * Returns the SQL snippet that declares a floating point column of arbitrary precision.
2278
     *
2279
     * @param mixed[] $columnDef
2280 77939
     *
2281
     * @return string
2282 77939
     */
2283 77803
    public function getDecimalTypeDeclarationSQL(array $columnDef)
2284
    {
2285
        $columnDef['precision'] = ! isset($columnDef['precision']) || empty($columnDef['precision'])
2286 74800
            ? 10 : $columnDef['precision'];
2287
        $columnDef['scale']     = ! isset($columnDef['scale']) || empty($columnDef['scale'])
2288 74800
            ? 0 : $columnDef['scale'];
2289
2290
        return 'NUMERIC(' . $columnDef['precision'] . ', ' . $columnDef['scale'] . ')';
2291
    }
2292 74800
2293
    /**
2294 74800
     * Obtains DBMS specific SQL code portion needed to set a default value
2295 74564
     * declaration to be used in statements like CREATE TABLE.
2296
     *
2297
     * @param mixed[] $field The field definition array.
2298 74731
     *
2299 72427
     * @return string DBMS specific SQL code portion needed to set a default value.
2300
     */
2301
    public function getDefaultValueDeclarationSQL($field)
2302 74701
    {
2303 11904
        if (! isset($field['default'])) {
2304
            return empty($field['notnull']) ? ' DEFAULT NULL' : '';
2305
        }
2306 74701
2307 70503
        $default = $field['default'];
2308
2309
        if (! isset($field['type'])) {
2310 74671
            return " DEFAULT '" . $default . "'";
2311 74543
        }
2312
2313
        $type = $field['type'];
2314 74309
2315
        if ($type instanceof Types\PhpIntegerMappingType) {
2316
            return ' DEFAULT ' . $default;
2317
        }
2318
2319
        if ($type instanceof Types\PhpDateTimeMappingType && $default === $this->getCurrentTimestampSQL()) {
2320
            return ' DEFAULT ' . $this->getCurrentTimestampSQL();
2321
        }
2322
2323
        if ($type instanceof Types\TimeType && $default === $this->getCurrentTimeSQL()) {
2324
            return ' DEFAULT ' . $this->getCurrentTimeSQL();
2325 72686
        }
2326
2327 72686
        if ($type instanceof Types\DateType && $default === $this->getCurrentDateSQL()) {
2328 72686
            return ' DEFAULT ' . $this->getCurrentDateSQL();
2329 72686
        }
2330
2331
        if ($type instanceof Types\BooleanType) {
2332 72686
            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

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

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

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

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

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

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

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

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

Loading history...
2921
    {
2922
        throw DBALException::notSupported(__METHOD__);
2923
    }
2924
2925 57927
    /**
2926
     * @param string $sequenceName
2927 57927
     *
2928
     * @return string
2929
     *
2930
     * @throws DBALException If not supported on this platform.
2931
     */
2932
    public function getSequenceNextValSQL($sequenceName)
0 ignored issues
show
Unused Code introduced by
The parameter $sequenceName is not used and could be removed. ( Ignorable by Annotation )

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

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

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

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

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

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

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

Loading history...
3498
    {
3499
        $tableIdentifier = new Identifier($tableName);
3500
3501
        return 'TRUNCATE ' . $tableIdentifier->getQuotedName($this);
3502 68054
    }
3503
3504 68054
    /**
3505
     * This is for test reasons, many vendors have special requirements for dummy statements.
3506
     *
3507
     * @return string
3508
     */
3509
    public function getDummySelectSQL()
3510
    {
3511
        $expression = func_num_args() > 0 ? func_get_arg(0) : '1';
3512
3513
        return sprintf('SELECT %s', $expression);
3514 68052
    }
3515
3516 68052
    /**
3517
     * Returns the SQL to create a new savepoint.
3518
     *
3519
     * @param string $savepoint
3520
     *
3521
     * @return string
3522
     */
3523
    public function createSavePoint($savepoint)
3524
    {
3525
        return 'SAVEPOINT ' . $savepoint;
3526 68054
    }
3527
3528 68054
    /**
3529
     * Returns the SQL to release a savepoint.
3530
     *
3531
     * @param string $savepoint
3532
     *
3533
     * @return string
3534
     */
3535
    public function releaseSavePoint($savepoint)
3536
    {
3537
        return 'RELEASE SAVEPOINT ' . $savepoint;
3538 79546
    }
3539
3540
    /**
3541 79546
     * Returns the SQL to rollback a savepoint.
3542 79412
     *
3543
     * @param string $savepoint
3544
     *
3545 79263
     * @return string
3546 79263
     */
3547 79263
    public function rollbackSavePoint($savepoint)
3548
    {
3549
        return 'ROLLBACK TO SAVEPOINT ' . $savepoint;
3550
    }
3551
3552 79263
    /**
3553
     * Returns the keyword list instance of this platform.
3554 79263
     *
3555
     * @return KeywordList
3556
     *
3557
     * @throws DBALException If no keyword list is specified.
3558
     */
3559
    final public function getReservedKeywordsList()
3560
    {
3561
        // Check for an existing instantiation of the keywords class.
3562
        if ($this->_keywords) {
3563
            return $this->_keywords;
3564
        }
3565
3566
        $class    = $this->getReservedKeywordsClass();
3567
        $keywords = new $class();
3568
        if (! $keywords instanceof KeywordList) {
3569
            throw DBALException::notSupported(__METHOD__);
3570
        }
3571
3572
        // Store the instance so it doesn't need to be generated on every request.
3573
        $this->_keywords = $keywords;
3574
3575
        return $keywords;
3576
    }
3577
3578
    /**
3579 76090
     * Returns the class name of the reserved keywords list.
3580
     *
3581 76090
     * @return string
3582
     *
3583 76090
     * @throws DBALException If not supported on this platform.
3584
     */
3585
    protected function getReservedKeywordsClass()
3586
    {
3587
        throw DBALException::notSupported(__METHOD__);
3588
    }
3589
3590
    /**
3591 76126
     * Quotes a literal string.
3592
     * This method is NOT meant to fix SQL injections!
3593 76126
     * It is only meant to escape this platform's string literal
3594
     * quote character inside the given literal string.
3595
     *
3596
     * @param string $str The literal string to be quoted.
3597
     *
3598
     * @return string The quoted literal string.
3599
     */
3600
    public function quoteStringLiteral($str)
3601
    {
3602
        $c = $this->getStringLiteralQuoteCharacter();
3603
3604 75850
        return $c . str_replace($c, $c . $c, $str) . $c;
3605
    }
3606 75850
3607 75850
    /**
3608 75850
     * Gets the character used for string literal quoting.
3609 75850
     *
3610
     * @return string
3611
     */
3612
    public function getStringLiteralQuoteCharacter()
3613 75850
    {
3614
        return "'";
3615 75850
    }
3616
3617
    /**
3618
     * Escapes metacharacters in a string intended to be used with a LIKE
3619
     * operator.
3620
     *
3621
     * @param string $inputString a literal, unquoted string
3622
     * @param string $escapeChar  should be reused by the caller in the LIKE
3623
     *                            expression.
3624
     */
3625
    final public function escapeStringForLike(string $inputString, string $escapeChar) : string
3626
    {
3627
        return preg_replace(
3628
            '~([' . preg_quote($this->getLikeWildcardCharacters() . $escapeChar, '~') . '])~u',
3629
            addcslashes($escapeChar, '\\') . '$1',
3630
            $inputString
3631
        );
3632
    }
3633
3634
    protected function getLikeWildcardCharacters() : string
3635
    {
3636
        return '%_';
3637
    }
3638
}
3639