Completed
Pull Request — master (#3445)
by Evgeniy
62:43
created

AbstractPlatform   F

Complexity

Total Complexity 390

Size/Duplication

Total Lines 3566
Duplicated Lines 0 %

Test Coverage

Coverage 80.34%

Importance

Changes 0
Metric Value
wmc 390
eloc 652
dl 0
loc 3566
ccs 666
cts 829
cp 0.8034
rs 1.948
c 0
b 0
f 0

211 Methods

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

356
    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...
357
    {
358
        throw DBALException::notSupported('VARCHARs not supported by Platform.');
359
    }
360
361
    /**
362
     * Returns the SQL snippet used to declare a BINARY/VARBINARY column type.
363
     *
364
     * @param int  $length The length of the column.
365
     * @param bool $fixed  Whether the column length is fixed.
366
     *
367
     * @return string
368
     *
369
     * @throws DBALException If not supported on this platform.
370
     */
371
    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

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

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

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

890
    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...
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

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

1061
    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

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

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

1319
    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

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

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

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

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

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

1728
    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...
1729
    {
1730
        throw DBALException::notSupported(__METHOD__);
1731
    }
1732
1733
    /**
1734
     * Returns the SQL to change a sequence on this platform.
1735
     *
1736
     * @return string
1737
     *
1738
     * @throws DBALException If not supported on this platform.
1739
     */
1740 476
    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

1740
    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...
1741
    {
1742 476
        throw DBALException::notSupported(__METHOD__);
1743
    }
1744
1745
    /**
1746 476
     * Returns the SQL to create a constraint on a table on this platform.
1747
     *
1748 476
     * @param Table|string $table
1749
     *
1750 476
     * @return string
1751 476
     *
1752 476
     * @throws InvalidArgumentException
1753 476
     */
1754 351
    public function getCreateConstraintSQL(Constraint $constraint, $table)
1755 351
    {
1756
        if ($table instanceof Table) {
1757
            $table = $table->getQuotedName($this);
1758 476
        }
1759
1760
        $query = 'ALTER TABLE ' . $table . ' ADD CONSTRAINT ' . $constraint->getQuotedName($this);
1761 351
1762 351
        $columnList = '(' . implode(', ', $constraint->getQuotedColumns($this)) . ')';
1763
1764 351
        $referencesClause = '';
1765 351
        if ($constraint instanceof Index) {
1766
            if ($constraint->isPrimary()) {
1767 476
                $query .= ' PRIMARY KEY';
1768
            } elseif ($constraint->isUnique()) {
1769 476
                $query .= ' UNIQUE';
1770
            } else {
1771
                throw new InvalidArgumentException(
1772
                    'Can only create primary or unique constraints, no common indexes with getCreateConstraintSQL().'
1773
                );
1774
            }
1775
        } elseif ($constraint instanceof ForeignKeyConstraint) {
1776
            $query .= ' FOREIGN KEY';
1777
1778
            $referencesClause = ' REFERENCES ' . $constraint->getQuotedForeignTableName($this) .
1779
                ' (' . implode(', ', $constraint->getQuotedForeignColumns($this)) . ')';
1780
        }
1781 4289
        $query .= ' ' . $columnList . $referencesClause;
1782
1783 4289
        return $query;
1784 27
    }
1785
1786 4289
    /**
1787 4289
     * Returns the SQL to create an index on a table on this platform.
1788
     *
1789 4289
     * @param Table|string $table The name of the table on which the index is to be created.
1790
     *
1791
     * @return string
1792
     *
1793 4289
     * @throws InvalidArgumentException
1794 567
     */
1795
    public function getCreateIndexSQL(Index $index, $table)
1796
    {
1797 3776
        if ($table instanceof Table) {
1798 3776
            $table = $table->getQuotedName($this);
1799
        }
1800 3776
        $name    = $index->getQuotedName($this);
1801
        $columns = $index->getColumns();
1802
1803
        if (count($columns) === 0) {
1804
            throw new InvalidArgumentException("Incomplete definition. 'columns' required.");
1805
        }
1806
1807
        if ($index->isPrimary()) {
1808 5259
            return $this->getCreatePrimaryKeySQL($index, $table);
1809
        }
1810 5259
1811 142
        $query  = 'CREATE ' . $this->getCreateIndexSQLFlags($index) . 'INDEX ' . $name . ' ON ' . $table;
1812
        $query .= ' (' . $this->getIndexFieldDeclarationListSQL($index) . ')' . $this->getPartialIndexSQL($index);
1813
1814 5117
        return $query;
1815
    }
1816
1817
    /**
1818
     * Adds condition for partial index.
1819
     *
1820
     * @return string
1821
     */
1822 1843
    protected function getPartialIndexSQL(Index $index)
1823
    {
1824 1843
        if ($this->supportsPartialIndexes() && $index->hasOption('where')) {
1825
            return ' WHERE ' . $index->getOption('where');
1826
        }
1827
1828
        return '';
1829
    }
1830
1831
    /**
1832
     * Adds additional flags for index generation.
1833
     *
1834 459
     * @return string
1835
     */
1836 459
    protected function getCreateIndexSQLFlags(Index $index)
1837
    {
1838
        return $index->isUnique() ? 'UNIQUE ' : '';
1839
    }
1840
1841
    /**
1842
     * Returns the SQL to create an unnamed primary key constraint.
1843
     *
1844
     * @param Table|string $table
1845
     *
1846
     * @return string
1847
     */
1848 270
    public function getCreatePrimaryKeySQL(Index $index, $table)
1849
    {
1850 270
        if ($table instanceof Table) {
1851
            $table = $table->getQuotedName($this);
1852
        }
1853
1854
        return 'ALTER TABLE ' . $table . ' ADD PRIMARY KEY (' . $this->getIndexFieldDeclarationListSQL($index) . ')';
1855
    }
1856
1857
    /**
1858
     * Returns the SQL to create a named schema.
1859
     *
1860
     * @param string $schemaName
1861
     *
1862
     * @return string
1863
     *
1864
     * @throws DBALException If not supported on this platform.
1865
     */
1866 10903
    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

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

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

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

2902
    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...
2903
    {
2904
        throw DBALException::notSupported(__METHOD__);
2905
    }
2906
2907 27
    /**
2908
     * @param string $sequenceName
2909 27
     *
2910
     * @return string
2911
     *
2912
     * @throws DBALException If not supported on this platform.
2913
     */
2914
    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

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

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