Completed
Pull Request — 2.10.x (#3984)
by Craig
61:21 queued 57:56
created

SqlitePlatform::getColumnNamesInAlteredTable()   B

Complexity

Conditions 7
Paths 48

Size

Total Lines 35
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 7.0052

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 35
ccs 20
cts 21
cp 0.9524
rs 8.6666
c 0
b 0
f 0
cc 7
nc 48
nop 1
crap 7.0052
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 1634
    public function getRegexpExpression()
40
    {
41 1634
        return 'REGEXP';
42
    }
43
44
    /**
45
     * {@inheritDoc}
46
     *
47
     * @deprecated Use application-generated UUIDs instead
48
     */
49 105
    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 105
            . "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
            case 'date':
68
                return 'date(\'now\')';
69
            case 'timestamp':
70
            default:
71
                return 'datetime(\'now\')';
72
        }
73
    }
74
75
    /**
76
     * {@inheritDoc}
77
     */
78 256
    public function getTrimExpression($str, $pos = TrimMode::UNSPECIFIED, $char = false)
79
    {
80 256
        $trimChar = $char !== false ? (', ' . $char) : '';
81
82 256
        switch ($pos) {
83
            case TrimMode::LEADING:
84 255
                $trimFn = 'LTRIM';
85 255
                break;
86
87
            case TrimMode::TRAILING:
88 254
                $trimFn = 'RTRIM';
89 254
                break;
90
91
            default:
92 256
                $trimFn = 'TRIM';
93
        }
94
95 256
        return $trimFn . '(' . $str . $trimChar . ')';
96
    }
97
98
    /**
99
     * {@inheritDoc}
100
     *
101
     * SQLite only supports the 2 parameter variant of this function
102
     */
103 1634
    public function getSubstringExpression($value, $position, $length = null)
104
    {
105 1634
        if ($length !== null) {
106 1634
            return 'SUBSTR(' . $value . ', ' . $position . ', ' . $length . ')';
107
        }
108
109 1634
        return 'SUBSTR(' . $value . ', ' . $position . ', LENGTH(' . $value . '))';
110
    }
111
112
    /**
113
     * {@inheritDoc}
114
     */
115 242
    public function getLocateExpression($str, $substr, $startPos = false)
116
    {
117 242
        if ($startPos === false) {
118 242
            return 'LOCATE(' . $str . ', ' . $substr . ')';
119
        }
120
121 242
        return 'LOCATE(' . $str . ', ' . $substr . ', ' . $startPos . ')';
122
    }
123
124
    /**
125
     * {@inheritdoc}
126
     */
127 1302
    protected function getDateArithmeticIntervalExpression($date, $operator, $interval, $unit)
128
    {
129 1302
        switch ($unit) {
130
            case DateIntervalUnit::SECOND:
131
            case DateIntervalUnit::MINUTE:
132
            case DateIntervalUnit::HOUR:
133 244
                return 'DATETIME(' . $date . ",'" . $operator . $interval . ' ' . $unit . "')";
134
135
            default:
136 1302
                switch ($unit) {
137
                    case DateIntervalUnit::WEEK:
138 244
                        $interval *= 7;
139 244
                        $unit      = DateIntervalUnit::DAY;
140 244
                        break;
141
142
                    case DateIntervalUnit::QUARTER:
143 244
                        $interval *= 3;
144 244
                        $unit      = DateIntervalUnit::MONTH;
145 244
                        break;
146
                }
147
148 1302
                if (! is_numeric($interval)) {
149 1300
                    $interval = "' || " . $interval . " || '";
150
                }
151
152 1302
                return 'DATE(' . $date . ",'" . $operator . $interval . ' ' . $unit . "')";
153
        }
154
    }
155
156
    /**
157
     * {@inheritDoc}
158
     */
159 214
    public function getDateDiffExpression($date1, $date2)
160
    {
161 214
        return sprintf("JULIANDAY(%s, 'start of day') - JULIANDAY(%s, 'start of day')", $date1, $date2);
162
    }
163
164
    /**
165
     * {@inheritDoc}
166
     */
167 1611
    protected function _getTransactionIsolationLevelSQL($level)
168
    {
169 1
        switch ($level) {
170 1610
            case TransactionIsolationLevel::READ_UNCOMMITTED:
171 1611
                return '0';
172 1610
            case TransactionIsolationLevel::READ_COMMITTED:
173 1610
            case TransactionIsolationLevel::REPEATABLE_READ:
174 1610
            case TransactionIsolationLevel::SERIALIZABLE:
175 1611
                return '1';
176
            default:
177
                return parent::_getTransactionIsolationLevelSQL($level);
178
        }
179
    }
180
181
    /**
182
     * {@inheritDoc}
183
     */
184 1611
    public function getSetTransactionIsolationSQL($level)
185
    {
186 1611
        return 'PRAGMA read_uncommitted = ' . $this->_getTransactionIsolationLevelSQL($level);
187
    }
188
189
    /**
190
     * {@inheritDoc}
191
     */
192 1597
    public function prefersIdentityColumns()
193
    {
194 1597
        return true;
195
    }
196
197
    /**
198
     * {@inheritDoc}
199
     */
200 919
    public function getBooleanTypeDeclarationSQL(array $field)
201
    {
202 919
        return 'BOOLEAN';
203
    }
204
205
    /**
206
     * {@inheritDoc}
207
     */
208 1785
    public function getIntegerTypeDeclarationSQL(array $field)
209
    {
210 1785
        return 'INTEGER' . $this->_getCommonIntegerTypeDeclarationSQL($field);
211
    }
212
213
    /**
214
     * {@inheritDoc}
215
     */
216 1581
    public function getBigIntTypeDeclarationSQL(array $field)
217
    {
218
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for BIGINT fields.
219 1581
        if (! empty($field['autoincrement'])) {
220 1581
            return $this->getIntegerTypeDeclarationSQL($field);
221
        }
222
223 1511
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
224
    }
225
226
    /**
227
     * @param array<string, mixed> $field
228
     *
229
     * @return string
230
     */
231 1543
    public function getTinyIntTypeDeclarationSql(array $field)
232
    {
233
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for TINYINT fields.
234 1543
        if (! empty($field['autoincrement'])) {
235 1543
            return $this->getIntegerTypeDeclarationSQL($field);
236
        }
237
238 1542
        return 'TINYINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
239
    }
240
241
    /**
242
     * {@inheritDoc}
243
     */
244 1629
    public function getSmallIntTypeDeclarationSQL(array $field)
245
    {
246
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for SMALLINT fields.
247 1629
        if (! empty($field['autoincrement'])) {
248 1629
            return $this->getIntegerTypeDeclarationSQL($field);
249
        }
250
251 1601
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
252
    }
253
254
    /**
255
     * @param array<string, mixed> $field
256
     *
257
     * @return string
258
     */
259 1
    public function getMediumIntTypeDeclarationSql(array $field)
260
    {
261
        //  SQLite autoincrement is implicit for INTEGER PKs, but not for MEDIUMINT fields.
262 1
        if (! empty($field['autoincrement'])) {
263 1
            return $this->getIntegerTypeDeclarationSQL($field);
264
        }
265
266 1
        return 'MEDIUMINT' . $this->_getCommonIntegerTypeDeclarationSQL($field);
267
    }
268
269
    /**
270
     * {@inheritDoc}
271
     */
272 257
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
273
    {
274 257
        return 'DATETIME';
275
    }
276
277
    /**
278
     * {@inheritDoc}
279
     */
280 243
    public function getDateTypeDeclarationSQL(array $fieldDeclaration)
281
    {
282 243
        return 'DATE';
283
    }
284
285
    /**
286
     * {@inheritDoc}
287
     */
288 211
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
289
    {
290 211
        return 'TIME';
291
    }
292
293
    /**
294
     * {@inheritDoc}
295
     */
296 1785
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
297
    {
298
        // sqlite autoincrement is only possible for the primary key
299 1785
        if (! empty($columnDef['autoincrement'])) {
300 1734
            return ' PRIMARY KEY AUTOINCREMENT';
301
        }
302
303 1760
        return ! empty($columnDef['unsigned']) ? ' UNSIGNED' : '';
304
    }
305
306
    /**
307
     * {@inheritDoc}
308
     */
309 1432
    public function getForeignKeyDeclarationSQL(ForeignKeyConstraint $foreignKey)
310
    {
311 1432
        return parent::getForeignKeyDeclarationSQL(new ForeignKeyConstraint(
312 1432
            $foreignKey->getQuotedLocalColumns($this),
313 1432
            str_replace('.', '__', $foreignKey->getQuotedForeignTableName($this)),
314 1432
            $foreignKey->getQuotedForeignColumns($this),
315 1432
            $foreignKey->getName(),
316 1432
            $foreignKey->getOptions()
317
        ));
318
    }
319
320
    /**
321
     * {@inheritDoc}
322
     */
323 1568
    protected function _getCreateTableSQL($name, array $columns, array $options = [])
324
    {
325 1568
        $name        = str_replace('.', '__', $name);
326 1568
        $queryFields = $this->getColumnDeclarationListSQL($columns);
327
328 1568
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
329
            foreach ($options['uniqueConstraints'] as $name => $definition) {
0 ignored issues
show
introduced by
$name is overwriting one of the parameters of this function.
Loading history...
330
                $queryFields .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
331
            }
332
        }
333
334 1568
        $queryFields .= $this->getNonAutoincrementPrimaryKeyDefinition($columns, $options);
335
336 1568
        if (isset($options['foreignKeys'])) {
337 1568
            foreach ($options['foreignKeys'] as $foreignKey) {
338 1432
                $queryFields .= ', ' . $this->getForeignKeyDeclarationSQL($foreignKey);
339
            }
340
        }
341
342 1568
        $tableComment = '';
343 1568
        if (isset($options['comment'])) {
344 128
            $comment = trim($options['comment'], " '");
345
346 128
            $tableComment = $this->getInlineTableCommentSQL($comment);
347
        }
348
349 1568
        $query = ['CREATE TABLE ' . $name . ' ' . $tableComment . '(' . $queryFields . ')'];
350
351 1568
        if (isset($options['alter']) && $options['alter'] === true) {
352 1337
            return $query;
353
        }
354
355 1556
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
356 1431
            foreach ($options['indexes'] as $indexDef) {
357 1431
                $query[] = $this->getCreateIndexSQL($indexDef, $name);
358
            }
359
        }
360
361 1556
        if (isset($options['unique']) && ! empty($options['unique'])) {
362
            foreach ($options['unique'] as $indexDef) {
363
                $query[] = $this->getCreateIndexSQL($indexDef, $name);
364
            }
365
        }
366
367 1556
        return $query;
368
    }
369
370
    /**
371
     * Generate a PRIMARY KEY definition if no autoincrement value is used
372
     *
373
     * @param mixed[][] $columns
374
     * @param mixed[]   $options
375
     */
376 1568
    private function getNonAutoincrementPrimaryKeyDefinition(array $columns, array $options) : string
377
    {
378 1568
        if (empty($options['primary'])) {
379 1238
            return '';
380
        }
381
382 1554
        $keyColumns = array_unique(array_values($options['primary']));
383
384 1554
        foreach ($keyColumns as $keyColumn) {
385 1554
            if (! empty($columns[$keyColumn]['autoincrement'])) {
386 1508
                return '';
387
            }
388
        }
389
390 1463
        return ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
391
    }
392
393
    /**
394
     * {@inheritDoc}
395
     */
396 1659
    protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
397
    {
398 1659
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
399 1659
                : ($length ? 'VARCHAR(' . $length . ')' : 'TEXT');
400
    }
401
402
    /**
403
     * {@inheritdoc}
404
     */
405 1324
    protected function getBinaryTypeDeclarationSQLSnippet($length, $fixed)
406
    {
407 1324
        return 'BLOB';
408
    }
409
410
    /**
411
     * {@inheritdoc}
412
     */
413 1325
    public function getBinaryMaxLength()
414
    {
415 1325
        return 0;
416
    }
417
418
    /**
419
     * {@inheritdoc}
420
     */
421 1325
    public function getBinaryDefaultLength()
422
    {
423 1325
        return 0;
424
    }
425
426
    /**
427
     * {@inheritDoc}
428
     */
429 707
    public function getClobTypeDeclarationSQL(array $field)
430
    {
431 707
        return 'CLOB';
432
    }
433
434
    /**
435
     * {@inheritDoc}
436
     */
437 1151
    public function getListTableConstraintsSQL($table)
438
    {
439 1151
        $table = str_replace('.', '__', $table);
440
441 1151
        return sprintf(
442 1
            "SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name = %s AND sql NOT NULL ORDER BY name",
443 1151
            $this->quoteStringLiteral($table)
444
        );
445
    }
446
447
    /**
448
     * {@inheritDoc}
449
     */
450 1274
    public function getListTableColumnsSQL($table, $currentDatabase = null)
451
    {
452 1274
        $table = str_replace('.', '__', $table);
453
454 1274
        return sprintf('PRAGMA table_info(%s)', $this->quoteStringLiteral($table));
455
    }
456
457
    /**
458
     * {@inheritDoc}
459
     */
460 262
    public function getListTableIndexesSQL($table, $currentDatabase = null)
461
    {
462 262
        $table = str_replace('.', '__', $table);
463
464 262
        return sprintf('PRAGMA index_list(%s)', $this->quoteStringLiteral($table));
465
    }
466
467
    /**
468
     * {@inheritDoc}
469
     */
470 313
    public function getListTablesSQL()
471
    {
472
        return "SELECT name FROM sqlite_master WHERE type = 'table' AND name != 'sqlite_sequence' AND name != 'geometry_columns' AND name != 'spatial_ref_sys' "
473
             . 'UNION ALL SELECT name FROM sqlite_temp_master '
474 313
             . "WHERE type = 'table' ORDER BY name";
475
    }
476
477
    /**
478
     * {@inheritDoc}
479
     */
480 156
    public function getListViewsSQL($database)
481
    {
482 156
        return "SELECT name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL";
483
    }
484
485
    /**
486
     * {@inheritDoc}
487
     */
488 156
    public function getCreateViewSQL($name, $sql)
489
    {
490 156
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
491
    }
492
493
    /**
494
     * {@inheritDoc}
495
     */
496 156
    public function getDropViewSQL($name)
497
    {
498 156
        return 'DROP VIEW ' . $name;
499
    }
500
501
    /**
502
     * {@inheritDoc}
503
     */
504 1432
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey)
505
    {
506 1432
        $query = parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
507
508 1432
        $query .= ($foreignKey->hasOption('deferrable') && $foreignKey->getOption('deferrable') !== false ? ' ' : ' NOT ') . 'DEFERRABLE';
509 1432
        $query .= ' INITIALLY ' . ($foreignKey->hasOption('deferred') && $foreignKey->getOption('deferred') !== false ? 'DEFERRED' : 'IMMEDIATE');
510
511 1432
        return $query;
512
    }
513
514
    /**
515
     * {@inheritDoc}
516
     */
517 155
    public function supportsIdentityColumns()
518
    {
519 155
        return true;
520
    }
521
522
    /**
523
     * {@inheritDoc}
524
     */
525 1217
    public function supportsColumnCollation()
526
    {
527 1217
        return true;
528
    }
529
530
    /**
531
     * {@inheritDoc}
532
     */
533 1572
    public function supportsInlineColumnComments()
534
    {
535 1572
        return true;
536
    }
537
538
    /**
539
     * {@inheritDoc}
540
     */
541 1854
    public function getName()
542
    {
543 1854
        return 'sqlite';
544
    }
545
546
    /**
547
     * {@inheritDoc}
548
     */
549 765
    public function getTruncateTableSQL($tableName, $cascade = false)
550
    {
551 765
        $tableIdentifier = new Identifier($tableName);
552 765
        $tableName       = str_replace('.', '__', $tableIdentifier->getQuotedName($this));
553
554 765
        return 'DELETE FROM ' . $tableName;
555
    }
556
557
    /**
558
     * User-defined function for Sqlite that is used with PDO::sqliteCreateFunction().
559
     *
560
     * @param int|float $value
561
     *
562
     * @return float
563
     */
564
    public static function udfSqrt($value)
565
    {
566
        return sqrt($value);
567
    }
568
569
    /**
570
     * User-defined function for Sqlite that implements MOD(a, b).
571
     *
572
     * @param int $a
573
     * @param int $b
574
     *
575
     * @return int
576
     */
577
    public static function udfMod($a, $b)
578
    {
579
        return $a % $b;
580
    }
581
582
    /**
583
     * @param string $str
584
     * @param string $substr
585
     * @param int    $offset
586
     *
587
     * @return int
588
     */
589 242
    public static function udfLocate($str, $substr, $offset = 0)
590
    {
591
        // SQL's LOCATE function works on 1-based positions, while PHP's strpos works on 0-based positions.
592
        // So we have to make them compatible if an offset is given.
593 242
        if ($offset > 0) {
594 242
            $offset -= 1;
595
        }
596
597 242
        $pos = strpos($str, $substr, $offset);
598
599 242
        if ($pos !== false) {
600 242
            return $pos + 1;
601
        }
602
603 242
        return 0;
604
    }
605
606
    /**
607
     * {@inheritDoc}
608
     */
609
    public function getForUpdateSQL()
610
    {
611
        return '';
612
    }
613
614
    /**
615
     * {@inheritDoc}
616
     */
617 549
    public function getInlineColumnCommentSQL($comment)
618
    {
619 549
        return '--' . str_replace("\n", "\n--", $comment) . "\n";
620
    }
621
622 128
    private function getInlineTableCommentSQL(string $comment) : string
623
    {
624 128
        return $this->getInlineColumnCommentSQL($comment);
625
    }
626
627
    /**
628
     * {@inheritDoc}
629
     */
630 1123
    protected function initializeDoctrineTypeMappings()
631
    {
632 1123
        $this->doctrineTypeMapping = [
633
            'boolean'          => 'boolean',
634
            'tinyint'          => 'boolean',
635
            'smallint'         => 'smallint',
636
            'mediumint'        => 'integer',
637
            'int'              => 'integer',
638
            'integer'          => 'integer',
639
            'serial'           => 'integer',
640
            'bigint'           => 'bigint',
641
            'bigserial'        => 'bigint',
642
            'clob'             => 'text',
643
            'tinytext'         => 'text',
644
            'mediumtext'       => 'text',
645
            'longtext'         => 'text',
646
            'text'             => 'text',
647
            'varchar'          => 'string',
648
            'longvarchar'      => 'string',
649
            'varchar2'         => 'string',
650
            'nvarchar'         => 'string',
651
            'image'            => 'string',
652
            'ntext'            => 'string',
653
            'char'             => 'string',
654
            'date'             => 'date',
655
            'datetime'         => 'datetime',
656
            'timestamp'        => 'datetime',
657
            'time'             => 'time',
658
            'float'            => 'float',
659
            'double'           => 'float',
660
            'double precision' => 'float',
661
            'real'             => 'float',
662
            'decimal'          => 'decimal',
663
            'numeric'          => 'decimal',
664
            'blob'             => 'blob',
665
        ];
666 1123
    }
667
668
    /**
669
     * {@inheritDoc}
670
     */
671 1582
    protected function getReservedKeywordsClass()
672
    {
673 1582
        return Keywords\SQLiteKeywords::class;
674
    }
675
676
    /**
677
     * {@inheritDoc}
678
     */
679 1337
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
680
    {
681 1337
        if (! $diff->fromTable instanceof Table) {
682
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema');
683
        }
684
685 1337
        $sql = [];
686 1337
        foreach ($diff->fromTable->getIndexes() as $index) {
687 1331
            if ($index->isPrimary()) {
688 1329
                continue;
689
            }
690
691 1326
            $sql[] = $this->getDropIndexSQL($index, $diff->name);
692
        }
693
694 1337
        return $sql;
695
    }
696
697
    /**
698
     * {@inheritDoc}
699
     */
700 1337
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff)
701
    {
702 1337
        if (! $diff->fromTable instanceof Table) {
703
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema');
704
        }
705
706 1337
        $sql       = [];
707 1337
        $tableName = $diff->getNewName();
708
709 1337
        if ($tableName === false) {
710 850
            $tableName = $diff->getName($this);
711
        }
712
713 1337
        foreach ($this->getIndexesInAlteredTable($diff) as $index) {
714 1331
            if ($index->isPrimary()) {
715 1329
                continue;
716
            }
717
718 1328
            $sql[] = $this->getCreateIndexSQL($index, $tableName->getQuotedName($this));
719
        }
720
721 1337
        return $sql;
722
    }
723
724
    /**
725
     * {@inheritDoc}
726
     */
727 1575
    protected function doModifyLimitQuery($query, $limit, $offset)
728
    {
729 1575
        if ($limit === null && $offset > 0) {
730 1528
            return $query . ' LIMIT -1 OFFSET ' . $offset;
731
        }
732
733 1574
        return parent::doModifyLimitQuery($query, $limit, $offset);
734
    }
735
736
    /**
737
     * {@inheritDoc}
738
     */
739 1411
    public function getBlobTypeDeclarationSQL(array $field)
740
    {
741 1411
        return 'BLOB';
742
    }
743
744
    /**
745
     * {@inheritDoc}
746
     */
747 107
    public function getTemporaryTableName($tableName)
748
    {
749 107
        $tableName = str_replace('.', '__', $tableName);
750
751 107
        return $tableName;
752
    }
753
754
    /**
755
     * {@inheritDoc}
756
     *
757
     * Sqlite Platform emulates schema by underscoring each dot and generating tables
758
     * into the default database.
759
     *
760
     * This hack is implemented to be able to use SQLite as testdriver when
761
     * using schema supporting databases.
762
     */
763
    public function canEmulateSchemas()
764
    {
765
        return true;
766
    }
767
768
    /**
769
     * {@inheritDoc}
770
     */
771 1435
    public function supportsForeignKeyConstraints()
772
    {
773 1435
        return true;
774
    }
775
776
    /**
777
     * {@inheritDoc}
778
     */
779 1470
    public function supportsCreateDropForeignKeyConstraints() : bool
780
    {
781 1470
        return false;
782
    }
783
784
    /**
785
     * {@inheritDoc}
786
     */
787
    public function getCreatePrimaryKeySQL(Index $index, $table)
788
    {
789
        throw new DBALException('Sqlite platform does not support alter primary key.');
790
    }
791
792
    /**
793
     * {@inheritdoc}
794
     */
795 1427
    public function getCreateForeignKeySQL(ForeignKeyConstraint $foreignKey, $table)
796
    {
797 1427
        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
    public function getDropForeignKeySQL($foreignKey, $table)
804
    {
805
        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
        throw new DBALException('Sqlite platform does not support alter constraint.');
814
    }
815
816
    /**
817
     * {@inheritDoc}
818
     *
819
     * @param int|null $createFlags
820
     */
821 1569
    public function getCreateTableSQL(Table $table, $createFlags = null)
822
    {
823 1569
        $createFlags = $createFlags ?? self::CREATE_INDEXES | self::CREATE_FOREIGNKEYS;
824
825 1569
        return parent::getCreateTableSQL($table, $createFlags);
826
    }
827
828
    /**
829
     * @param string      $table
830
     * @param string|null $database
831
     *
832
     * @return string
833
     */
834 262
    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 262
        $table = str_replace('.', '__', $table);
837
838 262
        return sprintf('PRAGMA foreign_key_list(%s)', $this->quoteStringLiteral($table));
839
    }
840
841
    /**
842
     * {@inheritDoc}
843
     */
844 1451
    public function getAlterTableSQL(TableDiff $diff)
845
    {
846 1451
        $sql = $this->getSimpleAlterTableSQL($diff);
847 1451
        if ($sql !== false) {
0 ignored issues
show
introduced by
The condition $sql !== false is always false.
Loading history...
848 1437
            return $sql;
849
        }
850
851 1405
        $fromTable = $diff->fromTable;
852 1405
        if (! $fromTable instanceof Table) {
853 1290
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema');
854
        }
855
856 1337
        $table = clone $fromTable;
857
858 1337
        $columns        = [];
859 1337
        $oldColumnNames = [];
860 1337
        $newColumnNames = [];
861 1337
        $columnSql      = [];
862
863 1337
        foreach ($table->getColumns() as $columnName => $column) {
864 1336
            $columnName                  = strtolower($columnName);
865 1336
            $columns[$columnName]        = $column;
866 1336
            $oldColumnNames[$columnName] = $newColumnNames[$columnName] = $column->getQuotedName($this);
867
        }
868
869 1337
        foreach ($diff->removedColumns as $columnName => $column) {
870 1327
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
871
                continue;
872
            }
873
874 1327
            $columnName = strtolower($columnName);
875 1327
            if (! isset($columns[$columnName])) {
876
                continue;
877
            }
878
879
            unset(
880 1327
                $columns[$columnName],
881 1327
                $oldColumnNames[$columnName],
882 1327
                $newColumnNames[$columnName]
883
            );
884
        }
885
886 1337
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
887 1324
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
888
                continue;
889
            }
890
891 1324
            $oldColumnName = strtolower($oldColumnName);
892 1324
            if (isset($columns[$oldColumnName])) {
893 1324
                unset($columns[$oldColumnName]);
894
            }
895
896 1324
            $columns[strtolower($column->getName())] = $column;
897
898 1324
            if (! isset($newColumnNames[$oldColumnName])) {
899
                continue;
900
            }
901
902 1324
            $newColumnNames[$oldColumnName] = $column->getQuotedName($this);
903
        }
904
905 1337
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
906 883
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
907
                continue;
908
            }
909
910 883
            if (isset($columns[$oldColumnName])) {
911 882
                unset($columns[$oldColumnName]);
912
            }
913
914 883
            $columns[strtolower($columnDiff->column->getName())] = $columnDiff->column;
915
916 883
            if (! isset($newColumnNames[$oldColumnName])) {
917 507
                continue;
918
            }
919
920 882
            $newColumnNames[$oldColumnName] = $columnDiff->column->getQuotedName($this);
921
        }
922
923 1337
        foreach ($diff->addedColumns as $columnName => $column) {
924 886
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
925
                continue;
926
            }
927
928 886
            $columns[strtolower($columnName)] = $column;
929
        }
930
931 1337
        $sql      = [];
932 1337
        $tableSql = [];
933 1337
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
934 1337
            $dataTable = new Table('__temp__' . $table->getName());
935
936 1337
            $newTable = new Table($table->getQuotedName($this), $columns, $this->getPrimaryIndexInAlteredTable($diff), $this->getForeignKeysInAlteredTable($diff), 0, $table->getOptions());
937 1337
            $newTable->addOption('alter', true);
938
939 1337
            $sql = $this->getPreAlterTableIndexForeignKeySQL($diff);
940
            //$sql = array_merge($sql, $this->getCreateTableSQL($dataTable, 0));
941 1337
            $sql[] = sprintf('CREATE TEMPORARY TABLE %s AS SELECT %s FROM %s', $dataTable->getQuotedName($this), implode(', ', $oldColumnNames), $table->getQuotedName($this));
942 1337
            $sql[] = $this->getDropTableSQL($fromTable);
943
944 1337
            $sql   = array_merge($sql, $this->getCreateTableSQL($newTable));
945 1337
            $sql[] = sprintf('INSERT INTO %s (%s) SELECT %s FROM %s', $newTable->getQuotedName($this), implode(', ', $newColumnNames), implode(', ', $oldColumnNames), $dataTable->getQuotedName($this));
946 1337
            $sql[] = $this->getDropTableSQL($dataTable);
947
948 1337
            $newName = $diff->getNewName();
949
950 1337
            if ($newName !== false) {
951 1222
                $sql[] = sprintf(
952 3
                    'ALTER TABLE %s RENAME TO %s',
953 1222
                    $newTable->getQuotedName($this),
954 1222
                    $newName->getQuotedName($this)
955
                );
956
            }
957
958 1337
            $sql = array_merge($sql, $this->getPostAlterTableIndexForeignKeySQL($diff));
959
        }
960
961 1337
        return array_merge($sql, $tableSql, $columnSql);
962
    }
963
964
    /**
965
     * @return string[]|false
966
     */
967 1451
    private function getSimpleAlterTableSQL(TableDiff $diff)
968
    {
969
        // Suppress changes on integer type autoincrement columns.
970 1451
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
971 908
            if (! $columnDiff->fromColumn instanceof Column ||
972 904
                ! $columnDiff->column instanceof Column ||
973 904
                ! $columnDiff->column->getAutoincrement() ||
974 908
                ! $columnDiff->column->getType() instanceof Types\IntegerType
975
            ) {
976 883
                continue;
977
            }
978
979 176
            if (! $columnDiff->hasChanged('type') && $columnDiff->hasChanged('unsigned')) {
980 173
                unset($diff->changedColumns[$oldColumnName]);
981
982 173
                continue;
983
            }
984
985 176
            $fromColumnType = $columnDiff->fromColumn->getType();
986
987 176
            if (! ($fromColumnType instanceof Types\SmallIntType) && ! ($fromColumnType instanceof Types\BigIntType)) {
988
                continue;
989
            }
990
991 176
            unset($diff->changedColumns[$oldColumnName]);
992
        }
993
994 1451
        if (! empty($diff->renamedColumns) || ! empty($diff->addedForeignKeys) || ! empty($diff->addedIndexes)
995 1446
                || ! empty($diff->changedColumns) || ! empty($diff->changedForeignKeys) || ! empty($diff->changedIndexes)
996 1442
                || ! empty($diff->removedColumns) || ! empty($diff->removedForeignKeys) || ! empty($diff->removedIndexes)
997 1451
                || ! empty($diff->renamedIndexes)
998
        ) {
999 1337
            return false;
1000
        }
1001
1002 1439
        $table = new Table($diff->name);
1003
1004 1439
        $sql       = [];
1005 1439
        $tableSql  = [];
1006 1439
        $columnSql = [];
1007
1008 1439
        foreach ($diff->addedColumns as $column) {
1009 1314
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
1010
                continue;
1011
            }
1012
1013 1314
            $field = array_merge(['unique' => null, 'autoincrement' => null, 'default' => null], $column->toArray());
1014 1314
            $type  = $field['type'];
1015
            switch (true) {
1016 1314
                case isset($field['columnDefinition']) || $field['autoincrement'] || $field['unique']:
1017 1313
                case $type instanceof Types\DateTimeType && $field['default'] === $this->getCurrentTimestampSQL():
1018 1313
                case $type instanceof Types\DateType && $field['default'] === $this->getCurrentDateSQL():
1019 1312
                case $type instanceof Types\TimeType && $field['default'] === $this->getCurrentTimeSQL():
1020 1290
                    return false;
1021
            }
1022
1023 1312
            $field['name'] = $column->getQuotedName($this);
1024 1312
            if ($type instanceof Types\StringType && $field['length'] === null) {
1025 1312
                $field['length'] = 255;
1026
            }
1027
1028 1312
            $sql[] = 'ALTER TABLE ' . $table->getQuotedName($this) . ' ADD COLUMN ' . $this->getColumnDeclarationSQL($field['name'], $field);
1029
        }
1030
1031 1437
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
1032 1437
            if ($diff->newName !== false) {
1033 182
                $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 182
                $sql[]    = 'ALTER TABLE ' . $table->getQuotedName($this) . ' RENAME TO ' . $newTable->getQuotedName($this);
1035
            }
1036
        }
1037
1038 1437
        return array_merge($sql, $tableSql, $columnSql);
1039
    }
1040
1041
    /**
1042
     * @return string[]
1043
     */
1044 1337
    private function getColumnNamesInAlteredTable(TableDiff $diff)
1045
    {
1046 1337
        $columns = [];
1047
1048 1337
        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 1336
            $columns[strtolower($columnName)] = $column->getName();
1050
        }
1051
1052 1337
        foreach ($diff->removedColumns as $columnName => $column) {
1053 1327
            $columnName = strtolower($columnName);
1054 1327
            if (! isset($columns[$columnName])) {
1055
                continue;
1056
            }
1057
1058 1327
            unset($columns[$columnName]);
1059
        }
1060
1061 1337
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
1062 1324
            $columnName                          = $column->getName();
1063 1324
            $columns[strtolower($oldColumnName)] = $columnName;
1064 1324
            $columns[strtolower($columnName)]    = $columnName;
1065
        }
1066
1067 1337
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
1068 883
            $columnName                          = $columnDiff->column->getName();
1069 883
            $columns[strtolower($oldColumnName)] = $columnName;
1070 883
            $columns[strtolower($columnName)]    = $columnName;
1071
        }
1072
1073 1337
        foreach ($diff->addedColumns as $column) {
1074 886
            $columnName                       = $column->getName();
1075 886
            $columns[strtolower($columnName)] = $columnName;
1076
        }
1077
1078 1337
        return $columns;
1079
    }
1080
1081
    /**
1082
     * @return Index[]
1083
     */
1084 1337
    private function getIndexesInAlteredTable(TableDiff $diff)
1085
    {
1086 1337
        $indexes     = $diff->fromTable->getIndexes();
1087 1337
        $columnNames = $this->getColumnNamesInAlteredTable($diff);
1088
1089 1337
        foreach ($indexes as $key => $index) {
1090 1331
            foreach ($diff->renamedIndexes as $oldIndexName => $renamedIndex) {
1091 578
                if (strtolower($key) !== strtolower($oldIndexName)) {
1092 578
                    continue;
1093
                }
1094
1095 334
                unset($indexes[$key]);
1096
            }
1097
1098 1331
            $changed      = false;
1099 1331
            $indexColumns = [];
1100 1331
            foreach ($index->getColumns() as $columnName) {
1101 1331
                $normalizedColumnName = strtolower($columnName);
1102 1331
                if (! isset($columnNames[$normalizedColumnName])) {
1103 1220
                    unset($indexes[$key]);
1104 1220
                    continue 2;
1105
                }
1106
1107 1331
                $indexColumns[] = $columnNames[$normalizedColumnName];
1108 1331
                if ($columnName === $columnNames[$normalizedColumnName]) {
1109 1331
                    continue;
1110
                }
1111
1112 1320
                $changed = true;
1113
            }
1114
1115 1331
            if (! $changed) {
1116 1331
                continue;
1117
            }
1118
1119 1320
            $indexes[$key] = new Index($index->getName(), $indexColumns, $index->isUnique(), $index->isPrimary(), $index->getFlags());
1120
        }
1121
1122 1337
        foreach ($diff->removedIndexes as $index) {
1123 1324
            $indexName = strtolower($index->getName());
1124 1324
            if (! strlen($indexName) || ! isset($indexes[$indexName])) {
1125
                continue;
1126
            }
1127
1128 1324
            unset($indexes[$indexName]);
1129
        }
1130
1131 1337
        foreach (array_merge($diff->changedIndexes, $diff->addedIndexes, $diff->renamedIndexes) as $index) {
1132 578
            $indexName = strtolower($index->getName());
1133 578
            if (strlen($indexName)) {
1134 578
                $indexes[$indexName] = $index;
1135
            } else {
1136
                $indexes[] = $index;
1137
            }
1138
        }
1139
1140 1337
        return $indexes;
1141
    }
1142
1143
    /**
1144
     * @return ForeignKeyConstraint[]
1145
     */
1146 1337
    private function getForeignKeysInAlteredTable(TableDiff $diff)
1147
    {
1148 1337
        $foreignKeys = $diff->fromTable->getForeignKeys();
1149 1337
        $columnNames = $this->getColumnNamesInAlteredTable($diff);
1150
1151 1337
        foreach ($foreignKeys as $key => $constraint) {
1152 1322
            $changed      = false;
1153 1322
            $localColumns = [];
1154 1322
            foreach ($constraint->getLocalColumns() as $columnName) {
1155 1322
                $normalizedColumnName = strtolower($columnName);
1156 1322
                if (! isset($columnNames[$normalizedColumnName])) {
1157 1220
                    unset($foreignKeys[$key]);
1158 1220
                    continue 2;
1159
                }
1160
1161 1322
                $localColumns[] = $columnNames[$normalizedColumnName];
1162 1322
                if ($columnName === $columnNames[$normalizedColumnName]) {
1163 1321
                    continue;
1164
                }
1165
1166 1320
                $changed = true;
1167
            }
1168
1169 1322
            if (! $changed) {
1170 1321
                continue;
1171
            }
1172
1173 1320
            $foreignKeys[$key] = new ForeignKeyConstraint($localColumns, $constraint->getForeignTableName(), $constraint->getForeignColumns(), $constraint->getName(), $constraint->getOptions());
1174
        }
1175
1176 1337
        foreach ($diff->removedForeignKeys as $constraint) {
1177 374
            if (! $constraint instanceof ForeignKeyConstraint) {
1178
                $constraint = new Identifier($constraint);
1179
            }
1180
1181 374
            $constraintName = strtolower($constraint->getName());
1182 374
            if (! strlen($constraintName) || ! isset($foreignKeys[$constraintName])) {
1183
                continue;
1184
            }
1185
1186 374
            unset($foreignKeys[$constraintName]);
1187
        }
1188
1189 1337
        foreach (array_merge($diff->changedForeignKeys, $diff->addedForeignKeys) as $constraint) {
1190 380
            $constraintName = strtolower($constraint->getName());
1191 380
            if (strlen($constraintName)) {
1192 380
                $foreignKeys[$constraintName] = $constraint;
1193
            } else {
1194 157
                $foreignKeys[] = $constraint;
1195
            }
1196
        }
1197
1198 1337
        return $foreignKeys;
1199
    }
1200
1201
    /**
1202
     * @return Index[]
1203
     */
1204 1337
    private function getPrimaryIndexInAlteredTable(TableDiff $diff)
1205
    {
1206 1337
        $primaryIndex = [];
1207
1208 1337
        foreach ($this->getIndexesInAlteredTable($diff) as $index) {
1209 1331
            if (! $index->isPrimary()) {
1210 1328
                continue;
1211
            }
1212
1213 1329
            $primaryIndex = [$index->getName() => $index];
1214
        }
1215
1216 1337
        return $primaryIndex;
1217
    }
1218
}
1219