Passed
Pull Request — master (#3206)
by Ilya
12:43
created

SqlitePlatform::getSubstringExpression()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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

800
    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...
801
    {
802 21
        $table = str_replace('.', '__', $table);
803
804 21
        return sprintf('PRAGMA foreign_key_list(%s)', $this->quoteStringLiteral($table));
805
    }
806
807
    /**
808
     * {@inheritDoc}
809
     */
810 319
    public function getAlterTableSQL(TableDiff $diff)
811
    {
812 319
        $sql = $this->getSimpleAlterTableSQL($diff);
813 319
        if ($sql !== false) {
0 ignored issues
show
introduced by
The condition $sql !== false is always false.
Loading history...
814 26
            return $sql;
815
        }
816
817 293
        $fromTable = $diff->fromTable;
818 293
        if (! $fromTable instanceof Table) {
0 ignored issues
show
introduced by
$fromTable is always a sub-type of Doctrine\DBAL\Schema\Table. If $fromTable can have other possible types, add them to lib/Doctrine/DBAL/Schema/TableDiff.php:95.
Loading history...
819 40
            throw new DBALException('Sqlite platform requires for alter table the table diff with reference to original table schema');
820
        }
821
822 253
        $table = clone $fromTable;
823
824 253
        $columns        = [];
825 253
        $oldColumnNames = [];
826 253
        $newColumnNames = [];
827 253
        $columnSql      = [];
828
829 253
        foreach ($table->getColumns() as $columnName => $column) {
830 233
            $columnName                  = strtolower($columnName);
831 233
            $columns[$columnName]        = $column;
832 233
            $oldColumnNames[$columnName] = $newColumnNames[$columnName] = $column->getQuotedName($this);
833
        }
834
835 253
        foreach ($diff->removedColumns as $columnName => $column) {
836 81
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
837
                continue;
838
            }
839
840 81
            $columnName = strtolower($columnName);
841 81
            if (! isset($columns[$columnName])) {
842
                continue;
843
            }
844
845
            unset(
846 81
                $columns[$columnName],
847 81
                $oldColumnNames[$columnName],
848 81
                $newColumnNames[$columnName]
849
            );
850
        }
851
852 253
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
853 100
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
854
                continue;
855
            }
856
857 100
            $oldColumnName = strtolower($oldColumnName);
858 100
            if (isset($columns[$oldColumnName])) {
859 100
                unset($columns[$oldColumnName]);
860
            }
861
862 100
            $columns[strtolower($column->getName())] = $column;
863
864 100
            if (! isset($newColumnNames[$oldColumnName])) {
865
                continue;
866
            }
867
868 100
            $newColumnNames[$oldColumnName] = $column->getQuotedName($this);
869
        }
870
871 253
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
872 132
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
873
                continue;
874
            }
875
876 132
            if (isset($columns[$oldColumnName])) {
877 112
                unset($columns[$oldColumnName]);
878
            }
879
880 132
            $columns[strtolower($columnDiff->column->getName())] = $columnDiff->column;
881
882 132
            if (! isset($newColumnNames[$oldColumnName])) {
883 20
                continue;
884
            }
885
886 112
            $newColumnNames[$oldColumnName] = $columnDiff->column->getQuotedName($this);
887
        }
888
889 253
        foreach ($diff->addedColumns as $columnName => $column) {
890 61
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
891
                continue;
892
            }
893
894 61
            $columns[strtolower($columnName)] = $column;
895
        }
896
897 253
        $sql      = [];
898 253
        $tableSql = [];
899 253
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
900 253
            $dataTable = new Table('__temp__' . $table->getName());
901
902 253
            $newTable = new Table($table->getQuotedName($this), $columns, $this->getPrimaryIndexInAlteredTable($diff), $this->getForeignKeysInAlteredTable($diff), 0, $table->getOptions());
903 253
            $newTable->addOption('alter', true);
0 ignored issues
show
Bug introduced by
true of type true is incompatible with the type string expected by parameter $value of Doctrine\DBAL\Schema\Table::addOption(). ( Ignorable by Annotation )

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

903
            $newTable->addOption('alter', /** @scrutinizer ignore-type */ true);
Loading history...
904
905 253
            $sql = $this->getPreAlterTableIndexForeignKeySQL($diff);
906
            //$sql = array_merge($sql, $this->getCreateTableSQL($dataTable, 0));
907 253
            $sql[] = sprintf('CREATE TEMPORARY TABLE %s AS SELECT %s FROM %s', $dataTable->getQuotedName($this), implode(', ', $oldColumnNames), $table->getQuotedName($this));
908 253
            $sql[] = $this->getDropTableSQL($fromTable);
909
910 253
            $sql   = array_merge($sql, $this->getCreateTableSQL($newTable));
911 253
            $sql[] = sprintf('INSERT INTO %s (%s) SELECT %s FROM %s', $newTable->getQuotedName($this), implode(', ', $newColumnNames), implode(', ', $oldColumnNames), $dataTable->getQuotedName($this));
912 253
            $sql[] = $this->getDropTableSQL($dataTable);
913
914 253
            if ($diff->newName && $diff->newName !== $diff->name) {
915 60
                $renamedTable = $diff->getNewName();
916 60
                $sql[]        = 'ALTER TABLE ' . $newTable->getQuotedName($this) . ' RENAME TO ' . $renamedTable->getQuotedName($this);
917
            }
918
919 253
            $sql = array_merge($sql, $this->getPostAlterTableIndexForeignKeySQL($diff));
920
        }
921
922 253
        return array_merge($sql, $tableSql, $columnSql);
923
    }
924
925
    /**
926
     * @return string[]|false
927
     */
928 319
    private function getSimpleAlterTableSQL(TableDiff $diff)
929
    {
930
        // Suppress changes on integer type autoincrement columns.
931 319
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
932 137
            if (! $columnDiff->fromColumn instanceof Column ||
933 57
                ! $columnDiff->column instanceof Column ||
934 57
                ! $columnDiff->column->getAutoincrement() ||
935 137
                ! $columnDiff->column->getType() instanceof Types\IntegerType
936
            ) {
937 132
                continue;
938
            }
939
940 5
            if (! $columnDiff->hasChanged('type') && $columnDiff->hasChanged('unsigned')) {
941 1
                unset($diff->changedColumns[$oldColumnName]);
942
943 1
                continue;
944
            }
945
946 4
            $fromColumnType = $columnDiff->fromColumn->getType();
947
948 4
            if (! ($fromColumnType instanceof Types\SmallIntType) && ! ($fromColumnType instanceof Types\BigIntType)) {
949
                continue;
950
            }
951
952 4
            unset($diff->changedColumns[$oldColumnName]);
953
        }
954
955 319
        if (! empty($diff->renamedColumns) || ! empty($diff->addedForeignKeys) || ! empty($diff->addedIndexes)
956 219
                || ! empty($diff->changedColumns) || ! empty($diff->changedForeignKeys) || ! empty($diff->changedIndexes)
957 127
                || ! empty($diff->removedColumns) || ! empty($diff->removedForeignKeys) || ! empty($diff->removedIndexes)
958 319
                || ! empty($diff->renamedIndexes)
959
        ) {
960 253
            return false;
961
        }
962
963 66
        $table = new Table($diff->name);
964
965 66
        $sql       = [];
966 66
        $tableSql  = [];
967 66
        $columnSql = [];
968
969 66
        foreach ($diff->addedColumns as $column) {
970 60
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
971
                continue;
972
            }
973
974 60
            $field = array_merge(['unique' => null, 'autoincrement' => null, 'default' => null], $column->toArray());
975 60
            $type  = $field['type'];
976
            switch (true) {
977 60
                case isset($field['columnDefinition']) || $field['autoincrement'] || $field['unique']:
978 40
                case $type instanceof Types\DateTimeType && $field['default'] === $this->getCurrentTimestampSQL():
979 40
                case $type instanceof Types\DateType && $field['default'] === $this->getCurrentDateSQL():
980 20
                case $type instanceof Types\TimeType && $field['default'] === $this->getCurrentTimeSQL():
981 40
                    return false;
982
            }
983
984 20
            $field['name'] = $column->getQuotedName($this);
985 20
            if ($type instanceof Types\StringType && $field['length'] === null) {
986 20
                $field['length'] = 255;
987
            }
988
989 20
            $sql[] = 'ALTER TABLE ' . $table->getQuotedName($this) . ' ADD COLUMN ' . $this->getColumnDeclarationSQL($field['name'], $field);
990
        }
991
992 26
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
993 26
            if ($diff->newName !== false) {
994 1
                $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

994
                $newTable = new Identifier(/** @scrutinizer ignore-type */ $diff->newName);
Loading history...
995 1
                $sql[]    = 'ALTER TABLE ' . $table->getQuotedName($this) . ' RENAME TO ' . $newTable->getQuotedName($this);
996
            }
997
        }
998
999 26
        return array_merge($sql, $tableSql, $columnSql);
1000
    }
1001
1002
    /**
1003
     * @return string[]
1004
     */
1005 253
    private function getColumnNamesInAlteredTable(TableDiff $diff)
1006
    {
1007 253
        $columns = [];
1008
1009 253
        foreach ($diff->fromTable->getColumns() as $columnName => $column) {
1010 233
            $columns[strtolower($columnName)] = $column->getName();
1011
        }
1012
1013 253
        foreach ($diff->removedColumns as $columnName => $column) {
1014 81
            $columnName = strtolower($columnName);
1015 81
            if (! isset($columns[$columnName])) {
1016
                continue;
1017
            }
1018
1019 81
            unset($columns[$columnName]);
1020
        }
1021
1022 253
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
1023 100
            $columnName                          = $column->getName();
1024 100
            $columns[strtolower($oldColumnName)] = $columnName;
1025 100
            $columns[strtolower($columnName)]    = $columnName;
1026
        }
1027
1028 253
        foreach ($diff->changedColumns as $oldColumnName => $columnDiff) {
1029 132
            $columnName                          = $columnDiff->column->getName();
1030 132
            $columns[strtolower($oldColumnName)] = $columnName;
1031 132
            $columns[strtolower($columnName)]    = $columnName;
1032
        }
1033
1034 253
        foreach ($diff->addedColumns as $columnName => $column) {
1035 61
            $columns[strtolower($columnName)] = $columnName;
1036
        }
1037
1038 253
        return $columns;
1039
    }
1040
1041
    /**
1042
     * @return Index[]
1043
     */
1044 253
    private function getIndexesInAlteredTable(TableDiff $diff)
1045
    {
1046 253
        $indexes     = $diff->fromTable->getIndexes();
1047 253
        $columnNames = $this->getColumnNamesInAlteredTable($diff);
1048
1049 253
        foreach ($indexes as $key => $index) {
1050 123
            foreach ($diff->renamedIndexes as $oldIndexName => $renamedIndex) {
1051 61
                if (strtolower($key) !== strtolower($oldIndexName)) {
1052 61
                    continue;
1053
                }
1054
1055 21
                unset($indexes[$key]);
1056
            }
1057
1058 123
            $changed      = false;
1059 123
            $indexColumns = [];
1060 123
            foreach ($index->getColumns() as $columnName) {
1061 123
                $normalizedColumnName = strtolower($columnName);
1062 123
                if (! isset($columnNames[$normalizedColumnName])) {
1063 20
                    unset($indexes[$key]);
1064 20
                    continue 2;
1065
                } else {
1066 123
                    $indexColumns[] = $columnNames[$normalizedColumnName];
1067 123
                    if ($columnName !== $columnNames[$normalizedColumnName]) {
1068 123
                        $changed = true;
1069
                    }
1070
                }
1071
            }
1072
1073 123
            if (! $changed) {
1074 123
                continue;
1075
            }
1076
1077 20
            $indexes[$key] = new Index($index->getName(), $indexColumns, $index->isUnique(), $index->isPrimary(), $index->getFlags());
1078
        }
1079
1080 253
        foreach ($diff->removedIndexes as $index) {
1081 21
            $indexName = strtolower($index->getName());
1082 21
            if (! strlen($indexName) || ! isset($indexes[$indexName])) {
1083
                continue;
1084
            }
1085
1086 21
            unset($indexes[$indexName]);
1087
        }
1088
1089 253
        foreach (array_merge($diff->changedIndexes, $diff->addedIndexes, $diff->renamedIndexes) as $index) {
1090 61
            $indexName = strtolower($index->getName());
1091 61
            if (strlen($indexName)) {
1092 61
                $indexes[$indexName] = $index;
1093
            } else {
1094 61
                $indexes[] = $index;
1095
            }
1096
        }
1097
1098 253
        return $indexes;
1099
    }
1100
1101
    /**
1102
     * @return ForeignKeyConstraint[]
1103
     */
1104 253
    private function getForeignKeysInAlteredTable(TableDiff $diff)
1105
    {
1106 253
        $foreignKeys = $diff->fromTable->getForeignKeys();
1107 253
        $columnNames = $this->getColumnNamesInAlteredTable($diff);
1108
1109 253
        foreach ($foreignKeys as $key => $constraint) {
1110 60
            $changed      = false;
1111 60
            $localColumns = [];
1112 60
            foreach ($constraint->getLocalColumns() as $columnName) {
1113 60
                $normalizedColumnName = strtolower($columnName);
1114 60
                if (! isset($columnNames[$normalizedColumnName])) {
1115 20
                    unset($foreignKeys[$key]);
1116 20
                    continue 2;
1117
                } else {
1118 60
                    $localColumns[] = $columnNames[$normalizedColumnName];
1119 60
                    if ($columnName !== $columnNames[$normalizedColumnName]) {
1120 60
                        $changed = true;
1121
                    }
1122
                }
1123
            }
1124
1125 60
            if (! $changed) {
1126 60
                continue;
1127
            }
1128
1129 20
            $foreignKeys[$key] = new ForeignKeyConstraint($localColumns, $constraint->getForeignTableName(), $constraint->getForeignColumns(), $constraint->getName(), $constraint->getOptions());
1130
        }
1131
1132 253
        foreach ($diff->removedForeignKeys as $constraint) {
1133 20
            $constraintName = strtolower($constraint->getName());
1134 20
            if (! strlen($constraintName) || ! isset($foreignKeys[$constraintName])) {
1135
                continue;
1136
            }
1137
1138 20
            unset($foreignKeys[$constraintName]);
1139
        }
1140
1141 253
        foreach (array_merge($diff->changedForeignKeys, $diff->addedForeignKeys) as $constraint) {
1142 21
            $constraintName = strtolower($constraint->getName());
1143 21
            if (strlen($constraintName)) {
1144 20
                $foreignKeys[$constraintName] = $constraint;
1145
            } else {
1146 21
                $foreignKeys[] = $constraint;
1147
            }
1148
        }
1149
1150 253
        return $foreignKeys;
1151
    }
1152
1153
    /**
1154
     * @return Index[]
1155
     */
1156 253
    private function getPrimaryIndexInAlteredTable(TableDiff $diff)
1157
    {
1158 253
        $primaryIndex = [];
1159
1160 253
        foreach ($this->getIndexesInAlteredTable($diff) as $index) {
1161 123
            if (! $index->isPrimary()) {
1162 101
                continue;
1163
            }
1164
1165 83
            $primaryIndex = [$index->getName() => $index];
1166
        }
1167
1168 253
        return $primaryIndex;
1169
    }
1170
}
1171