Failed Conditions
Push — develop ( 55bd22...e46c09 )
by Sergei
33s queued 23s
created

SqliteSchemaManager::listTableForeignKeys()   B

Complexity

Conditions 10
Paths 6

Size

Total Lines 40
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 10.0862

Importance

Changes 0
Metric Value
eloc 29
dl 0
loc 40
ccs 19
cts 21
cp 0.9048
rs 7.6666
c 0
b 0
f 0
cc 10
nc 6
nop 2
crap 10.0862

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

117
        /** @scrutinizer ignore-call */ 
118
        $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...
118 85
        $tableForeignKeys = $this->_conn->fetchAll($sql);
119
120 85
        if (! empty($tableForeignKeys)) {
121 85
            $createSql = $this->getCreateTableSQL($table);
122
123 85
            if ($createSql !== null && preg_match_all(
124
                '#
125
                    (?:CONSTRAINT\s+([^\s]+)\s+)?
126
                    (?:FOREIGN\s+KEY[^\)]+\)\s*)?
127
                    REFERENCES\s+[^\s]+\s+(?:\([^\)]+\))?
128
                    (?:
129
                        [^,]*?
130
                        (NOT\s+DEFERRABLE|DEFERRABLE)
131
                        (?:\s+INITIALLY\s+(DEFERRED|IMMEDIATE))?
132
                    )?#isx',
133 85
                $createSql,
134 85
                $match
135
            )) {
136 85
                $names      = array_reverse($match[1]);
137 85
                $deferrable = array_reverse($match[2]);
138 85
                $deferred   = array_reverse($match[3]);
139
            } else {
140
                $names = $deferrable = $deferred = [];
141
            }
142
143 85
            foreach ($tableForeignKeys as $key => $value) {
144 85
                $id                                        = $value['id'];
145 85
                $tableForeignKeys[$key]['constraint_name'] = isset($names[$id]) && $names[$id] !== '' ? $names[$id] : $id;
146 85
                $tableForeignKeys[$key]['deferrable']      = isset($deferrable[$id]) && strtolower($deferrable[$id]) === 'deferrable';
147 85
                $tableForeignKeys[$key]['deferred']        = isset($deferred[$id]) && strtolower($deferred[$id]) === 'deferred';
148
            }
149
        }
150
151 85
        return $this->_getPortableTableForeignKeysList($tableForeignKeys);
152
    }
153
154
    /**
155
     * {@inheritdoc}
156
     */
157 150
    protected function _getPortableTableDefinition($table)
158
    {
159 150
        return $table['name'];
160
    }
161
162
    /**
163
     * {@inheritdoc}
164
     *
165
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
166
     */
167 143
    protected function _getPortableTableIndexesList(array $tableIndexRows, string $tableName) : array
168
    {
169 143
        $indexBuffer = [];
170
171
        // fetch primary
172 143
        $stmt       = $this->_conn->executeQuery(sprintf(
173 4
            'PRAGMA TABLE_INFO (%s)',
174 143
            $this->_conn->quote($tableName)
175
        ));
176 143
        $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
177
178
        usort($indexArray, static function ($a, $b) {
179 86
            if ($a['pk'] === $b['pk']) {
180 86
                return $a['cid'] - $b['cid'];
181
            }
182
183 86
            return $a['pk'] - $b['pk'];
184 143
        });
185 143
        foreach ($indexArray as $indexColumnRow) {
186 143
            if ($indexColumnRow['pk'] === '0') {
187 91
                continue;
188
            }
189
190 138
            $indexBuffer[] = [
191 138
                'key_name' => 'primary',
192
                'primary' => true,
193
                'non_unique' => false,
194 138
                'column_name' => $indexColumnRow['name'],
195
            ];
196
        }
197
198
        // fetch regular indexes
199 143
        foreach ($tableIndexRows as $tableIndex) {
200
            // Ignore indexes with reserved names, e.g. autoindexes
201 82
            if (strpos($tableIndex['name'], 'sqlite_') === 0) {
202 82
                continue;
203
            }
204
205 73
            $keyName           = $tableIndex['name'];
206 73
            $idx               = [];
207 73
            $idx['key_name']   = $keyName;
208 73
            $idx['primary']    = false;
209 73
            $idx['non_unique'] = ! $tableIndex['unique'];
210
211 73
                $stmt       = $this->_conn->executeQuery(sprintf(
212
                    'PRAGMA INDEX_INFO (%s)',
213 73
                    $this->_conn->quote($keyName)
214
                ));
215 73
                $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
216
217 73
            foreach ($indexArray as $indexColumnRow) {
218 73
                $idx['column_name'] = $indexColumnRow['name'];
219 73
                $indexBuffer[]      = $idx;
220
            }
221
        }
222
223 143
        return parent::_getPortableTableIndexesList($indexBuffer, $tableName);
224
    }
225
226
    /**
227
     * {@inheritdoc}
228
     */
229
    protected function _getPortableTableIndexDefinition($tableIndex)
230
    {
231
        return [
232
            'name' => $tableIndex['name'],
233
            'unique' => (bool) $tableIndex['unique'],
234
        ];
235
    }
236
237
    /**
238
     * {@inheritdoc}
239
     */
240 143
    protected function _getPortableTableColumnList($table, $database, $tableColumns)
241
    {
242 143
        $list = parent::_getPortableTableColumnList($table, $database, $tableColumns);
243
244
        // find column with autoincrement
245 143
        $autoincrementColumn = null;
246 143
        $autoincrementCount  = 0;
247
248 143
        foreach ($tableColumns as $tableColumn) {
249 143
            if ($tableColumn['pk'] === '0') {
250 91
                continue;
251
            }
252
253 138
            $autoincrementCount++;
254 138
            if ($autoincrementColumn !== null || strtolower($tableColumn['type']) !== 'integer') {
255 73
                continue;
256
            }
257
258 138
            $autoincrementColumn = $tableColumn['name'];
259
        }
260
261 143
        if ($autoincrementCount === 1 && $autoincrementColumn !== null) {
0 ignored issues
show
introduced by
The condition $autoincrementColumn !== null is always false.
Loading history...
262 138
            foreach ($list as $column) {
263 138
                if ($autoincrementColumn !== $column->getName()) {
264 86
                    continue;
265
                }
266
267 138
                $column->setAutoincrement(true);
268
            }
269
        }
270
271
        // inspect column collation and comments
272 143
        $createSql = $this->getCreateTableSQL($table) ?? '';
273
274 143
        foreach ($list as $columnName => $column) {
275 143
            $type = $column->getType();
276
277 143
            if ($type instanceof StringType || $type instanceof TextType) {
278 86
                $column->setPlatformOption('collation', $this->parseColumnCollationFromSQL($columnName, $createSql) ?: 'BINARY');
279
            }
280
281 143
            $comment = $this->parseColumnCommentFromSQL($columnName, $createSql);
282
283 143
            $type = $this->extractDoctrineTypeFromComment($comment);
284
285 143
            if ($type !== null) {
286 59
                $column->setType(Type::getType($type));
287
            }
288
289 143
            $column->setComment($comment);
290
        }
291
292 143
        return $list;
293
    }
294
295
    /**
296
     * {@inheritdoc}
297
     */
298 143
    protected function _getPortableTableColumnDefinition($tableColumn)
299
    {
300 143
        preg_match('/^([^()]*)\\s*(\\(((\\d+)(,\\s*(\\d+))?)\\))?/', $tableColumn['type'], $matches);
301
302 143
        $dbType = trim(strtolower($matches[1]));
303
304 143
        $length = $precision = $unsigned = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $unsigned is dead and can be removed.
Loading history...
305 143
        $fixed  = $unsigned = false;
306 143
        $scale  = 0;
307
308 143
        if (count($matches) >= 6) {
309 72
            $precision = (int) $matches[4];
310 72
            $scale     = (int) $matches[6];
311 143
        } elseif (count($matches) >= 4) {
312 86
            $length = (int) $matches[4];
313
        }
314
315 143
        if (strpos($dbType, ' unsigned') !== false) {
316 36
            $dbType   = str_replace(' unsigned', '', $dbType);
317 36
            $unsigned = true;
318
        }
319
320 143
        $type    = $this->_platform->getDoctrineTypeMapping($dbType);
321 143
        $default = $tableColumn['dflt_value'];
322 143
        if ($default === 'NULL') {
323 72
            $default = null;
324
        }
325 143
        if ($default !== null) {
326
            // SQLite returns strings wrapped in single quotes, so we need to strip them
327 91
            $default = preg_replace("/^'(.*)'$/", '\1', $default);
328
        }
329 143
        $notnull = (bool) $tableColumn['notnull'];
330
331 143
        if (! isset($tableColumn['name'])) {
332
            $tableColumn['name'] = '';
333
        }
334
335 143
        if ($dbType === 'char') {
336 71
            $fixed = true;
337
        }
338
339
        $options = [
340 143
            'length'   => $length,
341 143
            'unsigned' => $unsigned,
342 143
            'fixed'    => $fixed,
343 143
            'notnull'  => $notnull,
344 143
            'default'  => $default,
345 143
            'precision' => $precision,
346 143
            'scale'     => $scale,
347
            'autoincrement' => false,
348
        ];
349
350 143
        return new Column($tableColumn['name'], Type::getType($type), $options);
351
    }
352
353
    /**
354
     * {@inheritdoc}
355
     */
356 63
    protected function _getPortableViewDefinition($view)
357
    {
358 63
        return new View($view['name'], $view['sql']);
359
    }
360
361
    /**
362
     * {@inheritdoc}
363
     */
364 85
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
365
    {
366 85
        $list = [];
367 85
        foreach ($tableForeignKeys as $value) {
368 85
            $value = array_change_key_case($value, CASE_LOWER);
369 85
            $name  = $value['constraint_name'];
370 85
            if (! isset($list[$name])) {
371 85
                if (! isset($value['on_delete']) || $value['on_delete'] === 'RESTRICT') {
372
                    $value['on_delete'] = null;
373
                }
374 85
                if (! isset($value['on_update']) || $value['on_update'] === 'RESTRICT') {
375
                    $value['on_update'] = null;
376
                }
377
378 85
                $list[$name] = [
379 85
                    'name' => $name,
380
                    'local' => [],
381
                    'foreign' => [],
382 85
                    'foreignTable' => $value['table'],
383 85
                    'onDelete' => $value['on_delete'],
384 85
                    'onUpdate' => $value['on_update'],
385 85
                    'deferrable' => $value['deferrable'],
386 85
                    'deferred'=> $value['deferred'],
387
                ];
388
            }
389 85
            $list[$name]['local'][]   = $value['from'];
390 85
            $list[$name]['foreign'][] = $value['to'];
391
        }
392
393 85
        $result = [];
394 85
        foreach ($list as $constraint) {
395 85
            $result[] = new ForeignKeyConstraint(
396 85
                array_values($constraint['local']),
397 85
                $constraint['foreignTable'],
398 85
                array_values($constraint['foreign']),
399 85
                $constraint['name'],
400
                [
401 85
                    'onDelete' => $constraint['onDelete'],
402 85
                    'onUpdate' => $constraint['onUpdate'],
403 85
                    'deferrable' => $constraint['deferrable'],
404 85
                    'deferred'=> $constraint['deferred'],
405
                ]
406
            );
407
        }
408
409 85
        return $result;
410
    }
411
412
    /**
413
     * @param Table|string $table
414
     *
415
     * @return TableDiff
416
     *
417
     * @throws DBALException
418
     */
419
    private function getTableDiffForAlterForeignKey($table)
420
    {
421
        if (! $table instanceof Table) {
422
            $tableDetails = $this->tryMethod('listTableDetails', $table);
423
424
            if ($tableDetails === false) {
425
                throw new DBALException(sprintf('Sqlite schema manager requires to modify foreign keys table definition "%s".', $table));
426
            }
427
428
            $table = $tableDetails;
429
        }
430
431
        $tableDiff            = new TableDiff($table->getName());
432
        $tableDiff->fromTable = $table;
433
434
        return $tableDiff;
435
    }
436
437 958
    private function parseColumnCollationFromSQL(string $column, string $sql) : ?string
438
    {
439 958
        $pattern = '{(?:\W' . preg_quote($column) . '\W|\W' . preg_quote($this->_platform->quoteSingleIdentifier($column))
440 958
            . '\W)[^,(]+(?:\([^()]+\)[^,]*)?(?:(?:DEFAULT|CHECK)\s*(?:\(.*?\))?[^,]*)*COLLATE\s+["\']?([^\s,"\')]+)}is';
441
442 958
        if (preg_match($pattern, $sql, $match) !== 1) {
443 888
            return null;
444
        }
445
446 946
        return $match[1];
447
    }
448
449 667
    private function parseColumnCommentFromSQL(string $column, string $sql) : ?string
450
    {
451 667
        $pattern = '{[\s(,](?:\W' . preg_quote($this->_platform->quoteSingleIdentifier($column)) . '\W|\W' . preg_quote($column)
452 667
            . '\W)(?:\(.*?\)|[^,(])*?,?((?:(?!\n))(?:\s*--[^\n]*\n?)+)}i';
453
454 667
        if (preg_match($pattern, $sql, $match) !== 1) {
455 645
            return null;
456
        }
457
458 610
        $comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n"));
459
460 610
        return $comment === '' ? null : $comment;
461
    }
462
463 143
    private function getCreateTableSQL(string $table) : ?string
464
    {
465 143
        return $this->_conn->fetchColumn(
466
            <<<'SQL'
467 143
SELECT sql
468
  FROM (
469
      SELECT *
470
        FROM sqlite_master
471
   UNION ALL
472
      SELECT *
473
        FROM sqlite_temp_master
474
  )
475
WHERE type = 'table'
476
AND name = ?
477
SQL
478
            ,
479 143
            [$table]
480 143
        ) ?: null;
481
    }
482
}
483