Failed Conditions
Pull Request — 2.11.x (#3985)
by Grégoire
65:16
created

supportsCreateDropForeignKeyConstraints()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
namespace Doctrine\DBAL\Platforms;
4
5
use Doctrine\DBAL\DBALException;
6
use Doctrine\DBAL\Schema\Column;
7
use Doctrine\DBAL\Schema\Constraint;
8
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
9
use Doctrine\DBAL\Schema\Identifier;
10
use Doctrine\DBAL\Schema\Index;
11
use Doctrine\DBAL\Schema\Table;
12
use Doctrine\DBAL\Schema\TableDiff;
13
use Doctrine\DBAL\TransactionIsolationLevel;
14
use Doctrine\DBAL\Types;
15
use function array_merge;
16
use function array_unique;
17
use function array_values;
18
use function implode;
19
use function is_numeric;
20
use function sprintf;
21
use function sqrt;
22
use function str_replace;
23
use function strlen;
24
use function strpos;
25
use function strtolower;
26
use function trim;
27
28
/**
29
 * The SqlitePlatform class describes the specifics and dialects of the SQLite
30
 * database platform.
31
 *
32
 * @todo   Rename: SQLitePlatform
33
 */
34
class SqlitePlatform extends AbstractPlatform
35
{
36
    /**
37
     * {@inheritDoc}
38
     */
39 1680
    public function getRegexpExpression()
40
    {
41 1680
        return 'REGEXP';
42
    }
43
44
    /**
45
     * {@inheritDoc}
46
     *
47
     * @deprecated Use application-generated UUIDs instead
48
     */
49 109
    public function getGuidExpression()
50
    {
51
        return "HEX(RANDOMBLOB(4)) || '-' || HEX(RANDOMBLOB(2)) || '-4' || "
52
            . "SUBSTR(HEX(RANDOMBLOB(2)), 2) || '-' || "
53
            . "SUBSTR('89AB', 1 + (ABS(RANDOM()) % 4), 1) || "
54 109
            . "SUBSTR(HEX(RANDOMBLOB(2)), 2) || '-' || HEX(RANDOMBLOB(6))";
55
    }
56
57
    /**
58
     * @param string $type
59
     *
60
     * @return string
61
     */
62
    public function getNowExpression($type = 'timestamp')
63
    {
64
        switch ($type) {
65
            case 'time':
66
                return 'time(\'now\')';
67
68
            case 'date':
69
                return 'date(\'now\')';
70
71
            case 'timestamp':
72
            default:
73
                return 'datetime(\'now\')';
74
        }
75
    }
76
77
    /**
78 258
     * {@inheritDoc}
79
     */
80 258
    public function getTrimExpression($str, $pos = TrimMode::UNSPECIFIED, $char = false)
81
    {
82 258
        $trimChar = $char !== false ? ', ' . $char : '';
83
84 257
        switch ($pos) {
85 257
            case TrimMode::LEADING:
86
                $trimFn = 'LTRIM';
87
                break;
88 256
89 256
            case TrimMode::TRAILING:
90
                $trimFn = 'RTRIM';
91
                break;
92 258
93
            default:
94
                $trimFn = 'TRIM';
95 258
        }
96
97
        return $trimFn . '(' . $str . $trimChar . ')';
98
    }
99
100
    /**
101
     * {@inheritDoc}
102
     *
103 1680
     * SQLite only supports the 2 parameter variant of this function
104
     */
105 1680
    public function getSubstringExpression($value, $position, $length = null)
106 1680
    {
107
        if ($length !== null) {
108
            return 'SUBSTR(' . $value . ', ' . $position . ', ' . $length . ')';
109 1680
        }
110
111
        return 'SUBSTR(' . $value . ', ' . $position . ', LENGTH(' . $value . '))';
112
    }
113
114
    /**
115 244
     * {@inheritDoc}
116
     */
117 244
    public function getLocateExpression($str, $substr, $startPos = false)
118 244
    {
119
        if ($startPos === false) {
120
            return 'LOCATE(' . $str . ', ' . $substr . ')';
121 244
        }
122
123
        return 'LOCATE(' . $str . ', ' . $substr . ', ' . $startPos . ')';
124
    }
125
126
    /**
127 1326
     * {@inheritdoc}
128
     */
129 1326
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
130
    {
131
        switch ($unit) {
132
            case DateIntervalUnit::SECOND:
133 246
            case DateIntervalUnit::MINUTE:
134
            case DateIntervalUnit::HOUR:
135
                return 'DATETIME(' . $date . ",'" . $operator . $interval . ' ' . $unit . "')";
136 1326
        }
137
138 246
        switch ($unit) {
139 246
            case DateIntervalUnit::WEEK:
140 246
                $interval *= 7;
141
                $unit      = DateIntervalUnit::DAY;
142
                break;
143 246
144 246
            case DateIntervalUnit::QUARTER:
145 246
                $interval *= 3;
146
                $unit      = DateIntervalUnit::MONTH;
147
                break;
148 1326
        }
149 1324
150
        if (! is_numeric($interval)) {
151
            $interval = "' || " . $interval . " || '";
152 1326
        }
153
154
        return 'DATE(' . $date . ",'" . $operator . $interval . ' ' . $unit . "')";
155
    }
156
157
    /**
158
     * {@inheritDoc}
159 220
     */
160
    public function getDateDiffExpression($date1, $date2)
161 220
    {
162
        return sprintf("JULIANDAY(%s, 'start of day') - JULIANDAY(%s, 'start of day')", $date1, $date2);
163
    }
164
165
    /**
166
     * {@inheritDoc}
167 1657
     */
168
    protected function _getTransactionIsolationLevelSQL($level)
169 1
    {
170 1656
        switch ($level) {
171 1657
            case TransactionIsolationLevel::READ_UNCOMMITTED:
172 1656
                return '0';
173 1656
174 1656
            case TransactionIsolationLevel::READ_COMMITTED:
175 1657
            case TransactionIsolationLevel::REPEATABLE_READ:
176
            case TransactionIsolationLevel::SERIALIZABLE:
177
                return '1';
178
179
            default:
180
                return parent::_getTransactionIsolationLevelSQL($level);
181
        }
182
    }
183
184 1657
    /**
185
     * {@inheritDoc}
186 1657
     */
187
    public function getSetTransactionIsolationSQL($level)
188
    {
189
        return 'PRAGMA read_uncommitted = ' . $this->_getTransactionIsolationLevelSQL($level);
190
    }
191
192 1643
    /**
193
     * {@inheritDoc}
194 1643
     */
195
    public function prefersIdentityColumns()
196
    {
197
        return true;
198
    }
199
200 924
    /**
201
     * {@inheritDoc}
202 924
     */
203
    public function getBooleanTypeDeclarationSQL(array $field)
204
    {
205
        return 'BOOLEAN';
206
    }
207
208 1831
    /**
209
     * {@inheritDoc}
210 1831
     */
211
    public function getIntegerTypeDeclarationSQL(array $field)
212
    {
213
        return 'INTEGER' . $this->_getCommonIntegerTypeDeclarationSQL($field);
214
    }
215
216 1623
    /**
217
     * {@inheritDoc}
218
     */
219 1623
    public function getBigIntTypeDeclarationSQL(array $field)
220 1623
    {
221
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for BIGINT fields.
222
        if (! empty($field['autoincrement'])) {
223 1559
            return $this->getIntegerTypeDeclarationSQL($field);
224
        }
225
226
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
227
    }
228
229
    /**
230
     * @param array<string, mixed> $field
231 1589
     *
232
     * @return string
233
     */
234 1589
    public function getTinyIntTypeDeclarationSql(array $field)
235 1589
    {
236
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for TINYINT fields.
237
        if (! empty($field['autoincrement'])) {
238 1588
            return $this->getIntegerTypeDeclarationSQL($field);
239
        }
240
241
        return 'TINYINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
242
    }
243
244 1671
    /**
245
     * {@inheritDoc}
246
     */
247 1671
    public function getSmallIntTypeDeclarationSQL(array $field)
248 1671
    {
249
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for SMALLINT fields.
250
        if (! empty($field['autoincrement'])) {
251 1647
            return $this->getIntegerTypeDeclarationSQL($field);
252
        }
253
254
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
255
    }
256
257
    /**
258
     * @param array<string, mixed> $field
259 1
     *
260
     * @return string
261
     */
262 1
    public function getMediumIntTypeDeclarationSql(array $field)
263 1
    {
264
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for MEDIUMINT fields.
265
        if (! empty($field['autoincrement'])) {
266 1
            return $this->getIntegerTypeDeclarationSQL($field);
267
        }
268
269
        return 'MEDIUMINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
270
    }
271
272 259
    /**
273
     * {@inheritDoc}
274 259
     */
275
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
276
    {
277
        return 'DATETIME';
278
    }
279
280 245
    /**
281
     * {@inheritDoc}
282 245
     */
283
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
284
    {
285
        return 'DATE';
286
    }
287
288 217
    /**
289
     * {@inheritDoc}
290 217
     */
291
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
292
    {
293
        return 'TIME';
294
    }
295
296 1831
    /**
297
     * {@inheritDoc}
298
     */
299 1831
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
300 1784
    {
301
        // sqlite autoincrement is only possible for the primary key
302
        if (! empty($columnDef['autoincrement'])) {
303 1806
            return ' PRIMARY KEY AUTOINCREMENT';
304
        }
305
306
        return ! empty($columnDef['unsigned']) ? ' UNSIGNED' : '';
307
    }
308
309 1372
    /**
310
     * {@inheritDoc}
311 1372
     */
312 1372
    public function getForeignKeyDeclarationSQL(ForeignKeyConstraint $foreignKey)
313 1372
    {
314 1372
        return parent::getForeignKeyDeclarationSQL(new ForeignKeyConstraint(
315 1372
            $foreignKey->getQuotedLocalColumns($this),
316 1372
            str_replace('.', '__', $foreignKey->getQuotedForeignTableName($this)),
317
            $foreignKey->getQuotedForeignColumns($this),
318
            $foreignKey->getName(),
319
            $foreignKey->getOptions()
320
        ));
321
    }
322
323 1592
    /**
324
     * {@inheritDoc}
325 1592
     */
326 1592
    protected function _getCreateTableSQL($name, array $columns, array $options = [])
327
    {
328 1592
        $name        = str_replace('.', '__', $name);
329
        $queryFields = $this->getColumnDeclarationListSQL($columns);
330
331
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
332
            foreach ($options['uniqueConstraints'] as $name => $definition) {
0 ignored issues
show
introduced by
$name is overwriting one of the parameters of this function.
Loading history...
333
                $queryFields .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
334 1592
            }
335
        }
336 1592
337 1591
        $queryFields .= $this->getNonAutoincrementPrimaryKeyDefinition($columns, $options);
338 1372
339
        if (isset($options['foreignKeys'])) {
340
            foreach ($options['foreignKeys'] as $foreignKey) {
341
                $queryFields .= ', ' . $this->getForeignKeyDeclarationSQL($foreignKey);
342 1592
            }
343 1592
        }
344 131
345
        $tableComment = '';
346 131
        if (isset($options['comment'])) {
347
            $comment = trim($options['comment'], " '");
348
349 1592
            $tableComment = $this->getInlineTableCommentSQL($comment);
350
        }
351 1592
352 1357
        $query = ['CREATE TABLE ' . $name . ' ' . $tableComment . '(' . $queryFields . ')'];
353
354
        if (isset($options['alter']) && $options['alter'] === true) {
355 1580
            return $query;
356 1452
        }
357 1452
358
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
359
            foreach ($options['indexes'] as $indexDef) {
360
                $query[] = $this->getCreateIndexSQL($indexDef, $name);
361 1580
            }
362
        }
363
364
        if (isset($options['unique']) && ! empty($options['unique'])) {
365
            foreach ($options['unique'] as $indexDef) {
366
                $query[] = $this->getCreateIndexSQL($indexDef, $name);
367 1580
            }
368
        }
369
370
        return $query;
371
    }
372
373
    /**
374
     * Generate a PRIMARY KEY definition if no autoincrement value is used
375
     *
376 1592
     * @param mixed[][] $columns
377
     * @param mixed[]   $options
378 1592
     */
379 1266
    private function getNonAutoincrementPrimaryKeyDefinition(array $columns, array $options) : string
380
    {
381
        if (empty($options['primary'])) {
382 1578
            return '';
383
        }
384 1578
385 1578
        $keyColumns = array_unique(array_values($options['primary']));
386 1536
387
        foreach ($keyColumns as $keyColumn) {
388
            if (! empty($columns[$keyColumn]['autoincrement'])) {
389
                return '';
390 1487
            }
391
        }
392
393
        return ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
394
    }
395
396 1705
    /**
397
     * {@inheritDoc}
398 1705
     */
399 1705
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
400
    {
401
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
402
                : ($length ? 'VARCHAR(' . $length . ')' : 'TEXT');
403
    }
404
405 1344
    /**
406
     * {@inheritdoc}
407 1344
     */
408
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
409
    {
410
        return 'BLOB';
411
    }
412
413 1345
    /**
414
     * {@inheritdoc}
415 1345
     */
416
    public function getBinaryMaxLength()
417
    {
418
        return 0;
419
    }
420
421 1345
    /**
422
     * {@inheritdoc}
423 1345
     */
424
    public function getBinaryDefaultLength()
425
    {
426
        return 0;
427
    }
428
429 709
    /**
430
     * {@inheritDoc}
431 709
     */
432
    public function getClobTypeDeclarationSQL(array $field)
433
    {
434
        return 'CLOB';
435
    }
436
437 1174
    /**
438
     * {@inheritDoc}
439 1174
     */
440
    public function getListTableConstraintsSQL($table)
441 1174
    {
442 1
        $table = str_replace('.', '__', $table);
443 1174
444
        return sprintf(
445
            "SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name = %s AND sql NOT NULL ORDER BY name",
446
            $this->quoteStringLiteral($table)
447
        );
448
    }
449
450 1301
    /**
451
     * {@inheritDoc}
452 1301
     */
453
    public function getListTableColumnsSQL($table, $currentDatabase = null)
454 1301
    {
455
        $table = str_replace('.', '__', $table);
456
457
        return sprintf('PRAGMA table_info(%s)', $this->quoteStringLiteral($table));
458
    }
459
460 267
    /**
461
     * {@inheritDoc}
462 267
     */
463
    public function getListTableIndexesSQL($table, $currentDatabase = null)
464 267
    {
465
        $table = str_replace('.', '__', $table);
466
467
        return sprintf('PRAGMA index_list(%s)', $this->quoteStringLiteral($table));
468
    }
469
470 319
    /**
471
     * {@inheritDoc}
472
     */
473
    public function getListTablesSQL()
474 319
    {
475
        return "SELECT name FROM sqlite_master WHERE type = 'table' AND name != 'sqlite_sequence' AND name != 'geometry_columns' AND name != 'spatial_ref_sys' "
476
             . 'UNION ALL SELECT name FROM sqlite_temp_master '
477
             . "WHERE type = 'table' ORDER BY name";
478
    }
479
480 156
    /**
481
     * {@inheritDoc}
482 156
     */
483
    public function getListViewsSQL($database)
484
    {
485
        return "SELECT name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL";
486
    }
487
488 156
    /**
489
     * {@inheritDoc}
490 156
     */
491
    public function getCreateViewSQL($name, $sql)
492
    {
493
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
494
    }
495
496 156
    /**
497
     * {@inheritDoc}
498 156
     */
499
    public function getDropViewSQL($name)
500
    {
501
        return 'DROP VIEW ' . $name;
502
    }
503
504 1372
    /**
505
     * {@inheritDoc}
506 1372
     */
507
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey)
508 1372
    {
509 1372
        $query = parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
510
511 1372
        $query .= ($foreignKey->hasOption('deferrable') && $foreignKey->getOption('deferrable') !== false ? ' ' : ' NOT ') . 'DEFERRABLE';
512
        $query .= ' INITIALLY ' . ($foreignKey->hasOption('deferred') && $foreignKey->getOption('deferred') !== false ? 'DEFERRED' : 'IMMEDIATE');
513
514
        return $query;
515
    }
516
517 155
    /**
518
     * {@inheritDoc}
519 155
     */
520
    public function supportsIdentityColumns()
521
    {
522
        return true;
523
    }
524
525 1237
    /**
526
     * {@inheritDoc}
527 1237
     */
528
    public function supportsColumnCollation()
529
    {
530
        return true;
531
    }
532
533 1596
    /**
534
     * {@inheritDoc}
535 1596
     */
536
    public function supportsInlineColumnComments()
537
    {
538
        return true;
539
    }
540
541 1900
    /**
542
     * {@inheritDoc}
543 1900
     */
544
    public function getName()
545
    {
546
        return 'sqlite';
547
    }
548
549 764
    /**
550
     * {@inheritDoc}
551 764
     */
552 764
    public function getTruncateTableSQL($tableName, $cascade = false)
553
    {
554 764
        $tableIdentifier = new Identifier($tableName);
555
        $tableName       = str_replace('.', '__', $tableIdentifier->getQuotedName($this));
556
557
        return 'DELETE FROM ' . $tableName;
558
    }
559
560
    /**
561
     * User-defined function for Sqlite that is used with PDO::sqliteCreateFunction().
562
     *
563
     * @param int|float $value
564
     *
565
     * @return float
566
     */
567
    public static function udfSqrt($value)
568
    {
569
        return sqrt($value);
570
    }
571
572
    /**
573
     * User-defined function for Sqlite that implements MOD(a, b).
574
     *
575
     * @param int $a
576
     * @param int $b
577
     *
578
     * @return int
579
     */
580
    public static function udfMod($a, $b)
581
    {
582
        return $a % $b;
583
    }
584
585
    /**
586
     * @param string $str
587
     * @param string $substr
588
     * @param int    $offset
589 244
     *
590
     * @return int
591
     */
592
    public static function udfLocate($str, $substr, $offset = 0)
593 244
    {
594 244
        // SQL's LOCATE function works on 1-based positions, while PHP's strpos works on 0-based positions.
595
        // So we have to make them compatible if an offset is given.
596
        if ($offset > 0) {
597 244
            $offset -= 1;
598
        }
599 244
600 244
        $pos = strpos($str, $substr, $offset);
601
602
        if ($pos !== false) {
603 244
            return $pos + 1;
604
        }
605
606
        return 0;
607
    }
608
609
    /**
610
     * {@inheritDoc}
611
     */
612
    public function getForUpdateSQL()
613
    {
614
        return '';
615
    }
616
617 547
    /**
618
     * {@inheritDoc}
619 547
     */
620
    public function getInlineColumnCommentSQL($comment)
621
    {
622 131
        return '--' . str_replace("\n", "\n--", $comment) . "\n";
623
    }
624 131
625
    private function getInlineTableCommentSQL(string $comment) : string
626
    {
627
        return $this->getInlineColumnCommentSQL($comment);
628
    }
629
630 1150
    /**
631
     * {@inheritDoc}
632 1150
     */
633
    protected function initializeDoctrineTypeMappings()
634
    {
635
        $this->doctrineTypeMapping = [
636
            'boolean'          => 'boolean',
637
            'tinyint'          => 'boolean',
638
            'smallint'         => 'smallint',
639
            'mediumint'        => 'integer',
640
            'int'              => 'integer',
641
            'integer'          => 'integer',
642
            'serial'           => 'integer',
643
            'bigint'           => 'bigint',
644
            'bigserial'        => 'bigint',
645
            'clob'             => 'text',
646
            'tinytext'         => 'text',
647
            'mediumtext'       => 'text',
648
            'longtext'         => 'text',
649
            'text'             => 'text',
650
            'varchar'          => 'string',
651
            'longvarchar'      => 'string',
652
            'varchar2'         => 'string',
653
            'nvarchar'         => 'string',
654
            'image'            => 'string',
655
            'ntext'            => 'string',
656
            'char'             => 'string',
657
            'date'             => 'date',
658
            'datetime'         => 'datetime',
659
            'timestamp'        => 'datetime',
660
            'time'             => 'time',
661
            'float'            => 'float',
662
            'double'           => 'float',
663
            'double precision' => 'float',
664
            'real'             => 'float',
665
            'decimal'          => 'decimal',
666 1150
            'numeric'          => 'decimal',
667
            'blob'             => 'blob',
668
        ];
669
    }
670
671 1606
    /**
672
     * {@inheritDoc}
673 1606
     */
674
    protected function getReservedKeywordsClass()
675
    {
676
        return Keywords\SQLiteKeywords::class;
677
    }
678
679 1357
    /**
680
     * {@inheritDoc}
681 1357
     */
682
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
683
    {
684
        if (! $diff->fromTable instanceof Table) {
685 1357
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema');
686 1357
        }
687 1351
688 1349
        $sql = [];
689
        foreach ($diff->fromTable->getIndexes() as $index) {
690
            if ($index->isPrimary()) {
691 1348
                continue;
692
            }
693
694 1357
            $sql[] = $this->getDropIndexSQL($index, $diff->name);
695
        }
696
697
        return $sql;
698
    }
699
700 1357
    /**
701
     * {@inheritDoc}
702 1357
     */
703
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff)
704
    {
705
        if (! $diff->fromTable instanceof Table) {
706 1357
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema');
707 1357
        }
708
709 1357
        $sql       = [];
710 848
        $tableName = $diff->getNewName();
711
712
        if ($tableName === false) {
713 1357
            $tableName = $diff->getName($this);
714 1351
        }
715 1349
716
        foreach ($this->getIndexesInAlteredTable($diff) as $index) {
717
            if ($index->isPrimary()) {
718 1350
                continue;
719
            }
720
721 1357
            $sql[] = $this->getCreateIndexSQL($index, $tableName->getQuotedName($this));
722
        }
723
724
        return $sql;
725
    }
726
727 1603
    /**
728
     * {@inheritDoc}
729 1603
     */
730 1556
    protected function doModifyLimitQuery($query, $limit, $offset)
731
    {
732
        if ($limit === null && $offset > 0) {
733 1602
            return $query . ' LIMIT -1 OFFSET ' . $offset;
734
        }
735
736
        return parent::doModifyLimitQuery($query, $limit, $offset);
737
    }
738
739 1435
    /**
740
     * {@inheritDoc}
741 1435
     */
742
    public function getBlobTypeDeclarationSQL(array $field)
743
    {
744
        return 'BLOB';
745
    }
746
747 111
    /**
748
     * {@inheritDoc}
749 111
     */
750
    public function getTemporaryTableName($tableName)
751 111
    {
752
        $tableName = str_replace('.', '__', $tableName);
753
754
        return $tableName;
755
    }
756
757
    /**
758
     * {@inheritDoc}
759
     *
760
     * Sqlite Platform emulates schema by underscoring each dot and generating tables
761
     * into the default database.
762
     *
763
     * This hack is implemented to be able to use SQLite as testdriver when
764
     * using schema supporting databases.
765
     */
766
    public function canEmulateSchemas()
767
    {
768
        return true;
769
    }
770
771 1460
    /**
772
     * {@inheritDoc}
773 1460
     */
774
    public function supportsForeignKeyConstraints()
775
    {
776
        return true;
777
    }
778
779
    public function supportsCreateDropForeignKeyConstraints() : bool
780
    {
781
        return false;
782
    }
783
784
    /**
785
     * {@inheritDoc}
786
     */
787 1474
    public function getCreatePrimaryKeySQL(Index $index, $table)
788
    {
789 1474
        throw new DBALException('Sqlite platform does not support alter primary key.');
790
    }
791
792
    /**
793
     * {@inheritdoc}
794
     */
795
    public function getCreateForeignKeySQL(ForeignKeyConstraint $foreignKey, $table)
796
    {
797
        throw new DBALException('Sqlite platform does not support alter foreign key, the table must be fully recreated using getAlterTableSQL.');
798
    }
799
800
    /**
801
     * {@inheritdoc}
802
     */
803 1450
    public function getDropForeignKeySQL($foreignKey, $table)
804
    {
805 1450
        throw new DBALException('Sqlite platform does not support alter foreign key, the table must be fully recreated using getAlterTableSQL.');
806
    }
807
808
    /**
809
     * {@inheritDoc}
810
     */
811
    public function getCreateConstraintSQL(Constraint $constraint, $table)
812
    {
813 1593
        throw new DBALException('Sqlite platform does not support alter constraint.');
814
    }
815 1593
816
    /**
817 1593
     * {@inheritDoc}
818
     *
819
     * @param int|null $createFlags
820
     */
821
    public function getCreateTableSQL(Table $table, $createFlags = null)
822
    {
823
        $createFlags = $createFlags ?? self::CREATE_INDEXES | self::CREATE_FOREIGNKEYS;
824
825
        return parent::getCreateTableSQL($table, $createFlags);
826 180
    }
827
828 180
    /**
829
     * @param string      $table
830 180
     * @param string|null $database
831
     *
832
     * @return string
833
     */
834
    public function getListTableForeignKeysSQL($table, $database = null)
0 ignored issues
show
Unused Code introduced by
The parameter $database 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

834
    public function getListTableForeignKeysSQL($table, /** @scrutinizer ignore-unused */ $database = null)

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

Loading history...
835
    {
836 1471
        $table = str_replace('.', '__', $table);
837
838 1471
        return sprintf('PRAGMA foreign_key_list(%s)', $this->quoteStringLiteral($table));
839 1471
    }
840 1457
841
    /**
842
     * {@inheritDoc}
843 1425
     */
844 1425
    public function getAlterTableSQL(TableDiff $diff)
845 1313
    {
846
        $sql = $this->getSimpleAlterTableSQL($diff);
847
        if ($sql !== false) {
0 ignored issues
show
introduced by
The condition $sql !== false is always false.
Loading history...
848 1357
            return $sql;
849
        }
850 1357
851 1357
        $fromTable = $diff->fromTable;
852 1357
        if (! $fromTable instanceof Table) {
853 1357
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema');
854
        }
855 1357
856 1356
        $table = clone $fromTable;
857 1356
858 1356
        $columns        = [];
859
        $oldColumnNames = [];
860
        $newColumnNames = [];
861 1357
        $columnSql      = [];
862 1349
863
        foreach ($table->getColumns() as $columnName => $column) {
864
            $columnName                  = strtolower($columnName);
865
            $columns[$columnName]        = $column;
866 1349
            $oldColumnNames[$columnName] = $newColumnNames[$columnName] = $column->getQuotedName($this);
867 1349
        }
868
869
        foreach ($diff->removedColumns as $columnName => $column) {
870
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
871
                continue;
872 1349
            }
873 1349
874 1349
            $columnName = strtolower($columnName);
875
            if (! isset($columns[$columnName])) {
876
                continue;
877
            }
878 1357
879 1247
            unset(
880
                $columns[$columnName],
881
                $oldColumnNames[$columnName],
882
                $newColumnNames[$columnName]
883 1247
            );
884 1247
        }
885 1247
886
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
887
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
888 1247
                continue;
889
            }
890 1247
891
            $oldColumnName = strtolower($oldColumnName);
892
            if (isset($columns[$oldColumnName])) {
893
                unset($columns[$oldColumnName]);
894 1247
            }
895
896
            $columns[strtolower($column->getName())] = $column;
897 1357
898 885
            if (! isset($newColumnNames[$oldColumnName])) {
899
                continue;
900
            }
901
902 885
            $newColumnNames[$oldColumnName] = $column->getQuotedName($this);
903 884
        }
904
905
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
906 885
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
907
                continue;
908 885
            }
909 507
910
            if (isset($columns[$oldColumnName])) {
911
                unset($columns[$oldColumnName]);
912 884
            }
913
914
            $columns[strtolower($columnDiff->column->getName())] = $columnDiff->column;
915 1357
916 886
            if (! isset($newColumnNames[$oldColumnName])) {
917
                continue;
918
            }
919
920 886
            $newColumnNames[$oldColumnName] = $columnDiff->column->getQuotedName($this);
921
        }
922
923 1357
        foreach ($diff->addedColumns as $columnName => $column) {
924 1357
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
925 1357
                continue;
926 1357
            }
927
928 1357
            $columns[strtolower($columnName)] = $column;
929 1357
        }
930
931 1357
        $sql      = [];
932
        $tableSql = [];
933 1357
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
934 1357
            $dataTable = new Table('__temp__' . $table->getName());
935
936 1357
            $newTable = new Table($table->getQuotedName($this), $columns, $this->getPrimaryIndexInAlteredTable($diff), $this->getForeignKeysInAlteredTable($diff), 0, $table->getOptions());
937 1357
            $newTable->addOption('alter', true);
938 1357
939
            $sql = $this->getPreAlterTableIndexForeignKeySQL($diff);
940 1357
            //$sql = array_merge($sql, $this->getCreateTableSQL($dataTable, 0));
941
            $sql[] = sprintf('CREATE TEMPORARY TABLE %s AS SELECT %s FROM %s', $dataTable->getQuotedName($this), implode(', ', $oldColumnNames), $table->getQuotedName($this));
942 1357
            $sql[] = $this->getDropTableSQL($fromTable);
943 1245
944 3
            $sql   = array_merge($sql, $this->getCreateTableSQL($newTable));
945 1245
            $sql[] = sprintf('INSERT INTO %s (%s) SELECT %s FROM %s', $newTable->getQuotedName($this), implode(', ', $newColumnNames), implode(', ', $oldColumnNames), $dataTable->getQuotedName($this));
946 1245
            $sql[] = $this->getDropTableSQL($dataTable);
947
948
            $newName = $diff->getNewName();
949
950 1357
            if ($newName !== false) {
951
                $sql[] = sprintf(
952
                    'ALTER TABLE %s RENAME TO %s',
953 1357
                    $newTable->getQuotedName($this),
954
                    $newName->getQuotedName($this)
955
                );
956
            }
957
958
            $sql = array_merge($sql, $this->getPostAlterTableIndexForeignKeySQL($diff));
959 1471
        }
960
961
        return array_merge($sql, $tableSql, $columnSql);
962 1471
    }
963 906
964 902
    /**
965 902
     * @return string[]|false
966 906
     */
967
    private function getSimpleAlterTableSQL(TableDiff $diff)
968 885
    {
969
        // Suppress changes on integer type autoincrement columns.
970
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
971 174
            if (! $columnDiff->fromColumn instanceof Column ||
972 171
                ! $columnDiff->column instanceof Column ||
973
                ! $columnDiff->column->getAutoincrement() ||
974 171
                ! $columnDiff->column->getType() instanceof Types\IntegerType
975
            ) {
976
                continue;
977 174
            }
978
979 174
            if (! $columnDiff->hasChanged('type') && $columnDiff->hasChanged('unsigned')) {
980
                unset($diff->changedColumns[$oldColumnName]);
981
982
                continue;
983 174
            }
984
985
            $fromColumnType = $columnDiff->fromColumn->getType();
986 1471
987 1466
            if (! ($fromColumnType instanceof Types\SmallIntType) && ! ($fromColumnType instanceof Types\BigIntType)) {
988 1462
                continue;
989 1471
            }
990
991 1357
            unset($diff->changedColumns[$oldColumnName]);
992
        }
993
994 1459
        if (! empty($diff->renamedColumns) || ! empty($diff->addedForeignKeys) || ! empty($diff->addedIndexes)
995
                || ! empty($diff->changedColumns) || ! empty($diff->changedForeignKeys) || ! empty($diff->changedIndexes)
996 1459
                || ! empty($diff->removedColumns) || ! empty($diff->removedForeignKeys) || ! empty($diff->removedIndexes)
997 1459
                || ! empty($diff->renamedIndexes)
998 1459
        ) {
999
            return false;
1000 1459
        }
1001 1337
1002
        $table = new Table($diff->name);
1003
1004
        $sql       = [];
1005 1337
        $tableSql  = [];
1006 1337
        $columnSql = [];
1007
1008 1337
        foreach ($diff->addedColumns as $column) {
1009 1336
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
1010 1336
                continue;
1011 1335
            }
1012 1313
1013
            $field = array_merge(['unique' => null, 'autoincrement' => null, 'default' => null], $column->toArray());
1014
            $type  = $field['type'];
1015 1335
            switch (true) {
1016 1335
                case isset($field['columnDefinition']) || $field['autoincrement'] || $field['unique']:
1017 1335
                case $type instanceof Types\DateTimeType && $field['default'] === $this->getCurrentTimestampSQL():
1018
                case $type instanceof Types\DateType && $field['default'] === $this->getCurrentDateSQL():
1019
                case $type instanceof Types\TimeType && $field['default'] === $this->getCurrentTimeSQL():
1020 1335
                    return false;
1021
            }
1022
1023 1457
            $field['name'] = $column->getQuotedName($this);
1024 1457
            if ($type instanceof Types\StringType && $field['length'] === null) {
1025 180
                $field['length'] = 255;
1026 180
            }
1027
1028
            $sql[] = 'ALTER TABLE ' . $table->getQuotedName($this) . ' ADD COLUMN ' . $this->getColumnDeclarationSQL($field['name'], $field);
1029
        }
1030 1457
1031
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
1032
            if ($diff->newName !== false) {
1033
                $newTable = new Identifier($diff->newName);
0 ignored issues
show
Bug introduced by
It seems like $diff->newName can also be of type true; however, parameter $identifier of Doctrine\DBAL\Schema\Identifier::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

1033
                $newTable = new Identifier(/** @scrutinizer ignore-type */ $diff->newName);
Loading history...
1034
                $sql[]    = 'ALTER TABLE ' . $table->getQuotedName($this) . ' RENAME TO ' . $newTable->getQuotedName($this);
1035
            }
1036 1357
        }
1037
1038 1357
        return array_merge($sql, $tableSql, $columnSql);
1039
    }
1040 1357
1041 1356
    /**
1042
     * @return string[]
1043
     */
1044 1357
    private function getColumnNamesInAlteredTable(TableDiff $diff)
1045 1349
    {
1046 1349
        $columns = [];
1047
1048
        foreach ($diff->fromTable->getColumns() as $columnName => $column) {
0 ignored issues
show
Bug introduced by
The method getColumns() does not exist on null. ( Ignorable by Annotation )

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

1048
        foreach ($diff->fromTable->/** @scrutinizer ignore-call */ getColumns() as $columnName => $column) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1049
            $columns[strtolower($columnName)] = $column->getName();
1050 1349
        }
1051
1052
        foreach ($diff->removedColumns as $columnName => $column) {
1053 1357
            $columnName = strtolower($columnName);
1054 1247
            if (! isset($columns[$columnName])) {
1055 1247
                continue;
1056 1247
            }
1057
1058
            unset($columns[$columnName]);
1059 1357
        }
1060 885
1061 885
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
1062 885
            $columnName                          = $column->getName();
1063
            $columns[strtolower($oldColumnName)] = $columnName;
1064
            $columns[strtolower($columnName)]    = $columnName;
1065 1357
        }
1066 886
1067 886
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
1068
            $columnName                          = $columnDiff->column->getName();
1069
            $columns[strtolower($oldColumnName)] = $columnName;
1070 1357
            $columns[strtolower($columnName)]    = $columnName;
1071
        }
1072
1073
        foreach ($diff->addedColumns as $column) {
1074
            $columnName                       = $column->getName();
1075
            $columns[strtolower($columnName)] = $columnName;
1076 1357
        }
1077
1078 1357
        return $columns;
1079 1357
    }
1080
1081 1357
    /**
1082 1351
     * @return Index[]
1083 578
     */
1084 578
    private function getIndexesInAlteredTable(TableDiff $diff)
1085
    {
1086
        $indexes     = $diff->fromTable->getIndexes();
1087 334
        $columnNames = $this->getColumnNamesInAlteredTable($diff);
1088
1089
        foreach ($indexes as $key => $index) {
1090 1351
            foreach ($diff->renamedIndexes as $oldIndexName => $renamedIndex) {
1091 1351
                if (strtolower($key) !== strtolower($oldIndexName)) {
1092 1351
                    continue;
1093 1351
                }
1094 1351
1095 1243
                unset($indexes[$key]);
1096 1243
            }
1097
1098
            $changed      = false;
1099 1351
            $indexColumns = [];
1100 1351
            foreach ($index->getColumns() as $columnName) {
1101 1351
                $normalizedColumnName = strtolower($columnName);
1102
                if (! isset($columnNames[$normalizedColumnName])) {
1103
                    unset($indexes[$key]);
1104 1243
                    continue 2;
1105
                }
1106
1107 1351
                $indexColumns[] = $columnNames[$normalizedColumnName];
1108 1351
                if ($columnName === $columnNames[$normalizedColumnName]) {
1109
                    continue;
1110
                }
1111 1243
1112
                $changed = true;
1113
            }
1114 1357
1115 1346
            if (! $changed) {
1116 1346
                continue;
1117
            }
1118
1119
            $indexes[$key] = new Index($index->getName(), $indexColumns, $index->isUnique(), $index->isPrimary(), $index->getFlags());
1120 1346
        }
1121
1122
        foreach ($diff->removedIndexes as $index) {
1123 1357
            $indexName = strtolower($index->getName());
1124 578
            if (! strlen($indexName) || ! isset($indexes[$indexName])) {
1125 578
                continue;
1126 578
            }
1127
1128
            unset($indexes[$indexName]);
1129
        }
1130
1131
        foreach (array_merge($diff->changedIndexes, $diff->addedIndexes, $diff->renamedIndexes) as $index) {
1132 1357
            $indexName = strtolower($index->getName());
1133
            if (strlen($indexName)) {
1134
                $indexes[$indexName] = $index;
1135
            } else {
1136
                $indexes[] = $index;
1137
            }
1138 1357
        }
1139
1140 1357
        return $indexes;
1141 1357
    }
1142
1143 1357
    /**
1144 1245
     * @return ForeignKeyConstraint[]
1145 1245
     */
1146 1245
    private function getForeignKeysInAlteredTable(TableDiff $diff)
1147 1245
    {
1148 1245
        $foreignKeys = $diff->fromTable->getForeignKeys();
1149 1243
        $columnNames = $this->getColumnNamesInAlteredTable($diff);
1150 1243
1151
        foreach ($foreignKeys as $key => $constraint) {
1152
            $changed      = false;
1153 1245
            $localColumns = [];
1154 1245
            foreach ($constraint->getLocalColumns() as $columnName) {
1155 1245
                $normalizedColumnName = strtolower($columnName);
1156
                if (! isset($columnNames[$normalizedColumnName])) {
1157
                    unset($foreignKeys[$key]);
1158 1243
                    continue 2;
1159
                }
1160
1161 1245
                $localColumns[] = $columnNames[$normalizedColumnName];
1162 1245
                if ($columnName === $columnNames[$normalizedColumnName]) {
1163
                    continue;
1164
                }
1165 1243
1166
                $changed = true;
1167
            }
1168 1357
1169 231
            if (! $changed) {
1170
                continue;
1171
            }
1172
1173 231
            $foreignKeys[$key] = new ForeignKeyConstraint($localColumns, $constraint->getForeignTableName(), $constraint->getForeignColumns(), $constraint->getName(), $constraint->getOptions());
1174 231
        }
1175
1176
        foreach ($diff->removedForeignKeys as $constraint) {
1177
            if (! $constraint instanceof ForeignKeyConstraint) {
1178 231
                $constraint = new Identifier($constraint);
1179
            }
1180
1181 1357
            $constraintName = strtolower($constraint->getName());
1182 378
            if (! strlen($constraintName) || ! isset($foreignKeys[$constraintName])) {
1183 378
                continue;
1184 231
            }
1185
1186 157
            unset($foreignKeys[$constraintName]);
1187
        }
1188
1189
        foreach (array_merge($diff->changedForeignKeys, $diff->addedForeignKeys) as $constraint) {
1190 1357
            $constraintName = strtolower($constraint->getName());
1191
            if (strlen($constraintName)) {
1192
                $foreignKeys[$constraintName] = $constraint;
1193
            } else {
1194
                $foreignKeys[] = $constraint;
1195
            }
1196 1357
        }
1197
1198 1357
        return $foreignKeys;
1199
    }
1200 1357
1201 1351
    /**
1202 1350
     * @return Index[]
1203
     */
1204
    private function getPrimaryIndexInAlteredTable(TableDiff $diff)
1205 1349
    {
1206
        $primaryIndex = [];
1207
1208 1357
        foreach ($this->getIndexesInAlteredTable($diff) as $index) {
1209
            if (! $index->isPrimary()) {
1210
                continue;
1211
            }
1212
1213
            $primaryIndex = [$index->getName() => $index];
1214
        }
1215
1216
        return $primaryIndex;
1217
    }
1218
}
1219