Failed Conditions
Pull Request — 2.10.x (#3979)
by Ben
31:35 queued 27:39
created

SqliteSchemaManager   F

Complexity

Total Complexity 80

Size/Duplication

Total Lines 512
Duplicated Lines 0 %

Test Coverage

Coverage 39.83%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 80
eloc 242
dl 0
loc 512
ccs 96
cts 241
cp 0.3983
rs 2
c 2
b 0
f 0

20 Methods

Rating   Name   Duplication   Size   Complexity  
A _getPortableTableDefinition() 0 3 1
A dropForeignKey() 0 6 1
A dropAndCreateForeignKey() 0 6 1
A createForeignKey() 0 6 1
A _getPortableTableIndexDefinition() 0 5 1
A dropDatabase() 0 7 2
B listTableForeignKeys() 0 40 10
A renameTable() 0 6 1
A createDatabase() 0 11 1
B _getPortableTableIndexesList() 0 57 7
A parseColumnCollationFromSQL() 0 10 2
A getTableDiffForAlterForeignKey() 0 16 3
A getCreateTableSQL() 0 18 2
A parseColumnCommentFromSQL() 0 12 3
C _getPortableTableColumnList() 0 59 15
A parseTableCommentFromSQL() 0 17 3
B _getPortableTableForeignKeysList() 0 46 8
A _getPortableViewDefinition() 0 3 1
A listTableDetails() 0 13 2
F _getPortableTableColumnDefinition() 0 72 15

How to fix   Complexity   

Complex Class

Complex classes like SqliteSchemaManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SqliteSchemaManager, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Doctrine\DBAL\Schema;
4
5
use Doctrine\DBAL\DBALException;
6
use Doctrine\DBAL\DriverManager;
7
use Doctrine\DBAL\FetchMode;
8
use Doctrine\DBAL\Types\StringType;
9
use Doctrine\DBAL\Types\TextType;
10
use Doctrine\DBAL\Types\Type;
11
use const CASE_LOWER;
12
use function array_change_key_case;
13
use function array_map;
14
use function array_reverse;
15
use function array_values;
16
use function explode;
17
use function file_exists;
18
use function preg_match;
19
use function preg_match_all;
20
use function preg_quote;
21
use function preg_replace;
22
use function rtrim;
23
use function sprintf;
24
use function str_replace;
25
use function strpos;
26
use function strtolower;
27
use function trim;
28
use function unlink;
29
use function usort;
30
31
/**
32
 * Sqlite SchemaManager.
33
 */
34
class SqliteSchemaManager extends AbstractSchemaManager
35
{
36
    /**
37
     * {@inheritdoc}
38
     */
39
    public function dropDatabase($database)
40
    {
41
        if (! file_exists($database)) {
42
            return;
43
        }
44
45
        unlink($database);
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function createDatabase($database)
52
    {
53
        $params  = $this->_conn->getParams();
54
        $driver  = $params['driver'];
55
        $options = [
56
            'driver' => $driver,
57
            'path' => $database,
58
        ];
59
        $conn    = DriverManager::getConnection($options);
60
        $conn->connect();
61
        $conn->close();
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    public function renameTable($name, $newName)
68
    {
69
        $tableDiff            = new TableDiff($name);
70
        $tableDiff->fromTable = $this->listTableDetails($name);
71
        $tableDiff->newName   = $newName;
72
        $this->alterTable($tableDiff);
73
    }
74
75
    /**
76
     * {@inheritdoc}
77
     */
78
    public function createForeignKey(ForeignKeyConstraint $foreignKey, $table)
79
    {
80
        $tableDiff                     = $this->getTableDiffForAlterForeignKey($table);
81
        $tableDiff->addedForeignKeys[] = $foreignKey;
82
83
        $this->alterTable($tableDiff);
84
    }
85
86
    /**
87
     * {@inheritdoc}
88
     */
89
    public function dropAndCreateForeignKey(ForeignKeyConstraint $foreignKey, $table)
90
    {
91
        $tableDiff                       = $this->getTableDiffForAlterForeignKey($table);
92
        $tableDiff->changedForeignKeys[] = $foreignKey;
93
94
        $this->alterTable($tableDiff);
95
    }
96
97
    /**
98
     * {@inheritdoc}
99
     */
100
    public function dropForeignKey($foreignKey, $table)
101
    {
102
        $tableDiff                       = $this->getTableDiffForAlterForeignKey($table);
103
        $tableDiff->removedForeignKeys[] = $foreignKey;
104
105
        $this->alterTable($tableDiff);
106
    }
107
108
    /**
109
     * {@inheritdoc}
110
     */
111
    public function listTableForeignKeys($table, $database = null)
112
    {
113
        if ($database === null) {
114
            $database = $this->_conn->getDatabase();
115
        }
116
        $sql              = $this->_platform->getListTableForeignKeysSQL($table, $database);
0 ignored issues
show
Unused Code introduced by
The call to Doctrine\DBAL\Platforms\...stTableForeignKeysSQL() has too many arguments starting with $database. ( Ignorable by Annotation )

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

116
        /** @scrutinizer ignore-call */ 
117
        $sql              = $this->_platform->getListTableForeignKeysSQL($table, $database);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
117
        $tableForeignKeys = $this->_conn->fetchAll($sql);
118
119
        if (! empty($tableForeignKeys)) {
120
            $createSql = $this->getCreateTableSQL($table);
121
122
            if ($createSql !== null && preg_match_all(
123
                '#
124
                    (?:CONSTRAINT\s+([^\s]+)\s+)?
125
                    (?:FOREIGN\s+KEY[^\)]+\)\s*)?
126
                    REFERENCES\s+[^\s]+\s+(?:\([^\)]+\))?
127
                    (?:
128
                        [^,]*?
129
                        (NOT\s+DEFERRABLE|DEFERRABLE)
130
                        (?:\s+INITIALLY\s+(DEFERRED|IMMEDIATE))?
131
                    )?#isx',
132
                $createSql,
133
                $match
134
            )) {
135
                $names      = array_reverse($match[1]);
136
                $deferrable = array_reverse($match[2]);
137
                $deferred   = array_reverse($match[3]);
138
            } else {
139
                $names = $deferrable = $deferred = [];
140
            }
141
142
            foreach ($tableForeignKeys as $key => $value) {
143
                $id                                        = $value['id'];
144
                $tableForeignKeys[$key]['constraint_name'] = isset($names[$id]) && $names[$id] !== '' ? $names[$id] : $id;
145
                $tableForeignKeys[$key]['deferrable']      = isset($deferrable[$id]) && strtolower($deferrable[$id]) === 'deferrable';
146
                $tableForeignKeys[$key]['deferred']        = isset($deferred[$id]) && strtolower($deferred[$id]) === 'deferred';
147
            }
148
        }
149
150
        return $this->_getPortableTableForeignKeysList($tableForeignKeys);
151
    }
152
153
    /**
154
     * {@inheritdoc}
155
     */
156 44
    protected function _getPortableTableDefinition($table)
157
    {
158 44
        return $table['name'];
159
    }
160
161
    /**
162
     * {@inheritdoc}
163
     *
164
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
165
     */
166 44
    protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
167
    {
168 44
        $indexBuffer = [];
169
170
        // fetch primary
171 44
        $stmt       = $this->_conn->executeQuery(sprintf(
172
            'PRAGMA TABLE_INFO (%s)',
173 44
            $this->_conn->quote($tableName)
174
        ));
175 44
        $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
176
177
        usort($indexArray, static function ($a, $b) {
178
            if ($a['pk'] === $b['pk']) {
179
                return $a['cid'] - $b['cid'];
180
            }
181
182
            return $a['pk'] - $b['pk'];
183 44
        });
184 44
        foreach ($indexArray as $indexColumnRow) {
185 44
            if ($indexColumnRow['pk'] === '0') {
186
                continue;
187
            }
188
189 44
            $indexBuffer[] = [
190 44
                'key_name' => 'primary',
191
                'primary' => true,
192
                'non_unique' => false,
193 44
                'column_name' => $indexColumnRow['name'],
194
            ];
195
        }
196
197
        // fetch regular indexes
198 44
        foreach ($tableIndexes as $tableIndex) {
199
            // Ignore indexes with reserved names, e.g. autoindexes
200
            if (strpos($tableIndex['name'], 'sqlite_') === 0) {
201
                continue;
202
            }
203
204
            $keyName           = $tableIndex['name'];
205
            $idx               = [];
206
            $idx['key_name']   = $keyName;
207
            $idx['primary']    = false;
208
            $idx['non_unique'] = ! $tableIndex['unique'];
209
210
                $stmt       = $this->_conn->executeQuery(sprintf(
211
                    'PRAGMA INDEX_INFO (%s)',
212
                    $this->_conn->quote($keyName)
213
                ));
214
                $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
215
216
            foreach ($indexArray as $indexColumnRow) {
217
                $idx['column_name'] = $indexColumnRow['name'];
218
                $indexBuffer[]      = $idx;
219
            }
220
        }
221
222 44
        return parent::_getPortableTableIndexesList($indexBuffer, $tableName);
223
    }
224
225
    /**
226
     * @deprecated
227
     *
228
     * @param array<string, mixed> $tableIndex
229
     *
230
     * @return array<string, bool|string>
231
     */
232
    protected function _getPortableTableIndexDefinition($tableIndex)
233
    {
234
        return [
235
            'name' => $tableIndex['name'],
236
            'unique' => (bool) $tableIndex['unique'],
237
        ];
238
    }
239
240
    /**
241
     * {@inheritdoc}
242
     */
243 44
    protected function _getPortableTableColumnList($table, $database, $tableColumns)
244
    {
245 44
        $list = parent::_getPortableTableColumnList($table, $database, $tableColumns);
246
247
        // find column with autoincrement
248 44
        $autoincrementColumn = null;
249 44
        $autoincrementCount  = 0;
250
251 44
        foreach ($tableColumns as $tableColumn) {
252 44
            if ($tableColumn['pk'] === '0') {
253
                continue;
254
            }
255
256 44
            $autoincrementCount++;
257 44
            if ($autoincrementColumn !== null || strtolower($tableColumn['type']) !== 'integer') {
258
                continue;
259
            }
260
261 44
            $autoincrementColumn = $tableColumn['name'];
262
        }
263
264 44
        if ($autoincrementCount === 1 && $autoincrementColumn !== null) {
0 ignored issues
show
introduced by
The condition $autoincrementColumn !== null is always false.
Loading history...
265 44
            foreach ($list as $column) {
266 44
                if ($autoincrementColumn !== $column->getName()) {
267
                    continue;
268
                }
269
270 44
                $column->setAutoincrement(true);
271
            }
272
        }
273
274
        // inspect column collation and comments
275 44
        $createSql = $this->getCreateTableSQL($table) ?? '';
276
277 44
        foreach ($list as $columnName => $column) {
278 44
            $type = $column->getType();
279
280 44
            if ($type instanceof StringType || $type instanceof TextType) {
281
                $column->setPlatformOption('collation', $this->parseColumnCollationFromSQL($columnName, $createSql) ?: 'BINARY');
282
            }
283
284 44
            $comment = $this->parseColumnCommentFromSQL($columnName, $createSql);
285
286 44
            if ($comment === null) {
287 44
                continue;
288
            }
289
290
            $type = $this->extractDoctrineTypeFromComment($comment, '');
291
292
            if ($type !== '') {
293
                $column->setType(Type::getType($type));
294
295
                $comment = $this->removeDoctrineTypeFromComment($comment, $type);
296
            }
297
298
            $column->setComment($comment);
299
        }
300
301 44
        return $list;
302
    }
303
304
    /**
305
     * {@inheritdoc}
306
     */
307 44
    protected function _getPortableTableColumnDefinition($tableColumn)
308
    {
309 44
        $parts               = explode('(', $tableColumn['type']);
310 44
        $tableColumn['type'] = trim($parts[0]);
311 44
        if (isset($parts[1])) {
312
            $length                = trim($parts[1], ')');
313
            $tableColumn['length'] = $length;
314
        }
315
316 44
        $dbType   = strtolower($tableColumn['type']);
317 44
        $length   = $tableColumn['length'] ?? null;
318 44
        $unsigned = false;
319
320 44
        if (strpos($dbType, ' unsigned') !== false) {
321
            $dbType   = str_replace(' unsigned', '', $dbType);
322
            $unsigned = true;
323
        }
324
325 44
        $fixed   = false;
326 44
        $type    = $this->_platform->getDoctrineTypeMapping($dbType);
327 44
        $default = $tableColumn['dflt_value'];
328 44
        if ($default === 'NULL') {
329
            $default = null;
330
        }
331
332 44
        if ($default !== null) {
333
            // SQLite returns the default value as a literal expression, so we need to parse it
334
            if (preg_match('/^\'(.*)\'$/s', $default, $matches)) {
335
                $default = str_replace("''", "'", $matches[1]);
336
            }
337
        }
338
339 44
        $notnull = (bool) $tableColumn['notnull'];
340
341 44
        if (! isset($tableColumn['name'])) {
342
            $tableColumn['name'] = '';
343
        }
344
345 44
        $precision = null;
346 44
        $scale     = null;
347
348
        switch ($dbType) {
349 44
            case 'char':
350
                $fixed = true;
351
                break;
352 44
            case 'float':
353 44
            case 'double':
354 44
            case 'real':
355 44
            case 'decimal':
356 44
            case 'numeric':
357
                if (isset($tableColumn['length'])) {
358
                    if (strpos($tableColumn['length'], ',') === false) {
359
                        $tableColumn['length'] .= ',0';
360
                    }
361
                    [$precision, $scale] = array_map('trim', explode(',', $tableColumn['length']));
362
                }
363
                $length = null;
364
                break;
365
        }
366
367
        $options = [
368 44
            'length'   => $length,
369 44
            'unsigned' => (bool) $unsigned,
370 44
            'fixed'    => $fixed,
371 44
            'notnull'  => $notnull,
372 44
            'default'  => $default,
373 44
            'precision' => $precision,
374 44
            'scale'     => $scale,
375
            'autoincrement' => false,
376
        ];
377
378 44
        return new Column($tableColumn['name'], Type::getType($type), $options);
379
    }
380
381
    /**
382
     * {@inheritdoc}
383
     */
384
    protected function _getPortableViewDefinition($view)
385
    {
386
        return new View($view['name'], $view['sql']);
387
    }
388
389
    /**
390
     * {@inheritdoc}
391
     */
392
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
393
    {
394
        $list = [];
395
        foreach ($tableForeignKeys as $value) {
396
            $value = array_change_key_case($value, CASE_LOWER);
397
            $name  = $value['constraint_name'];
398
            if (! isset($list[$name])) {
399
                if (! isset($value['on_delete']) || $value['on_delete'] === 'RESTRICT') {
400
                    $value['on_delete'] = null;
401
                }
402
                if (! isset($value['on_update']) || $value['on_update'] === 'RESTRICT') {
403
                    $value['on_update'] = null;
404
                }
405
406
                $list[$name] = [
407
                    'name' => $name,
408
                    'local' => [],
409
                    'foreign' => [],
410
                    'foreignTable' => $value['table'],
411
                    'onDelete' => $value['on_delete'],
412
                    'onUpdate' => $value['on_update'],
413
                    'deferrable' => $value['deferrable'],
414
                    'deferred'=> $value['deferred'],
415
                ];
416
            }
417
            $list[$name]['local'][]   = $value['from'];
418
            $list[$name]['foreign'][] = $value['to'];
419
        }
420
421
        $result = [];
422
        foreach ($list as $constraint) {
423
            $result[] = new ForeignKeyConstraint(
424
                array_values($constraint['local']),
425
                $constraint['foreignTable'],
426
                array_values($constraint['foreign']),
427
                $constraint['name'],
428
                [
429
                    'onDelete' => $constraint['onDelete'],
430
                    'onUpdate' => $constraint['onUpdate'],
431
                    'deferrable' => $constraint['deferrable'],
432
                    'deferred'=> $constraint['deferred'],
433
                ]
434
            );
435
        }
436
437
        return $result;
438
    }
439
440
    /**
441
     * @param Table|string $table
442
     *
443
     * @return TableDiff
444
     *
445
     * @throws DBALException
446
     */
447
    private function getTableDiffForAlterForeignKey($table)
448
    {
449
        if (! $table instanceof Table) {
450
            $tableDetails = $this->tryMethod('listTableDetails', $table);
451
452
            if ($tableDetails === false) {
453
                throw new DBALException(sprintf('Sqlite schema manager requires to modify foreign keys table definition "%s".', $table));
454
            }
455
456
            $table = $tableDetails;
457
        }
458
459
        $tableDiff            = new TableDiff($table->getName());
460
        $tableDiff->fromTable = $table;
461
462
        return $tableDiff;
463
    }
464
465 682
    private function parseColumnCollationFromSQL(string $column, string $sql) : ?string
466
    {
467 682
        $pattern = '{(?:\W' . preg_quote($column) . '\W|\W' . preg_quote($this->_platform->quoteSingleIdentifier($column))
468 682
            . '\W)[^,(]+(?:\([^()]+\)[^,]*)?(?:(?:DEFAULT|CHECK)\s*(?:\(.*?\))?[^,]*)*COLLATE\s+["\']?([^\s,"\')]+)}is';
469
470 682
        if (preg_match($pattern, $sql, $match) !== 1) {
471 660
            return null;
472
        }
473
474 682
        return $match[1];
475
    }
476
477 44
    private function parseTableCommentFromSQL(string $table, string $sql) : ?string
478
    {
479
        $pattern = '/\s* # Allow whitespace characters at start of line
480
CREATE\sTABLE # Match "CREATE TABLE"
481 44
(?:\W"' . preg_quote($this->_platform->quoteSingleIdentifier($table), '/') . '"\W|\W' . preg_quote($table, '/')
482 44
            . '\W) # Match table name (quoted and unquoted)
483
( # Start capture
484
   (?:\s*--[^\n]*\n?)+ # Capture anything that starts with whitespaces followed by -- until the end of the line(s)
485
)/ix';
486
487 44
        if (preg_match($pattern, $sql, $match) !== 1) {
488 44
            return null;
489
        }
490
491
        $comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n"));
492
493
        return $comment === '' ? null : $comment;
494
    }
495
496 462
    private function parseColumnCommentFromSQL(string $column, string $sql) : ?string
497
    {
498 462
        $pattern = '{[\s(,](?:\W' . preg_quote($this->_platform->quoteSingleIdentifier($column)) . '\W|\W' . preg_quote($column)
499 462
            . '\W)(?:\([^)]*?\)|[^,(])*?,?((?:(?!\n))(?:\s*--[^\n]*\n?)+)}i';
500
501 462
        if (preg_match($pattern, $sql, $match) !== 1) {
502 440
            return null;
503
        }
504
505 462
        $comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n"));
506
507 462
        return $comment === '' ? null : $comment;
508
    }
509
510 44
    private function getCreateTableSQL(string $table) : ?string
511
    {
512 44
        return $this->_conn->fetchColumn(
513
            <<<'SQL'
514 44
SELECT sql
515
  FROM (
516
      SELECT *
517
        FROM sqlite_master
518
   UNION ALL
519
      SELECT *
520
        FROM sqlite_temp_master
521
  )
522
WHERE type = 'table'
523
AND name = ?
524
SQL
525
            ,
526 44
            [$table]
527 44
        ) ?: null;
528
    }
529
530
    /**
531
     * @param string $tableName
532
     */
533 44
    public function listTableDetails($tableName) : Table
534
    {
535 44
        $table = parent::listTableDetails($tableName);
536
537 44
        $tableCreateSql = $this->getCreateTableSQL($tableName) ?? '';
538
539 44
        $comment = $this->parseTableCommentFromSQL($tableName, $tableCreateSql);
540
541 44
        if ($comment !== null) {
542
            $table->addOption('comment', $comment);
543
        }
544
545 44
        return $table;
546
    }
547
}
548