Completed
Push — develop ( 0c4aa7...b62acb )
by Sergei
55s queued 14s
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\DriverManager;
8
use Doctrine\DBAL\FetchMode;
9
use Doctrine\DBAL\Types\StringType;
10
use Doctrine\DBAL\Types\TextType;
11
use Doctrine\DBAL\Types\Type;
12
use const CASE_LOWER;
13
use function array_change_key_case;
14
use function array_reverse;
15
use function array_values;
16
use function count;
17
use function file_exists;
18
use function is_string;
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 72
    public function dropDatabase(string $database) : void
41
    {
42 72
        if (! file_exists($database)) {
43 71
            return;
44
        }
45
46 72
        unlink($database);
47 72
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52 72
    public function createDatabase(string $database) : void
53
    {
54 72
        $params  = $this->_conn->getParams();
55 72
        $driver  = $params['driver'];
56
        $options = [
57 72
            'driver' => $driver,
58 72
            'path' => $database,
59
        ];
60 72
        $conn    = DriverManager::getConnection($options);
61 72
        $conn->connect();
62 72
        $conn->close();
63 72
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68 70
    public function renameTable(string $name, string $newName) : void
69
    {
70 70
        $tableDiff            = new TableDiff($name);
71 70
        $tableDiff->fromTable = $this->listTableDetails($name);
72 70
        $tableDiff->newName   = $newName;
73 70
        $this->alterTable($tableDiff);
74 70
    }
75
76
    /**
77
     * {@inheritdoc}
78
     */
79
    public function createForeignKey(ForeignKeyConstraint $foreignKey, $table) : void
80
    {
81
        $table = $this->ensureTable($table);
82
83
        $tableDiff = $this->getTableDiffForAlterForeignKey($table);
84
85
        $tableDiff->addedForeignKeys[] = $foreignKey;
86
87
        $this->alterTable($tableDiff);
88
    }
89
90
    /**
91
     * {@inheritdoc}
92
     */
93
    public function dropAndCreateForeignKey(ForeignKeyConstraint $foreignKey, $table) : void
94
    {
95
        $table = $this->ensureTable($table);
96
97
        $tableDiff = $this->getTableDiffForAlterForeignKey($table);
98
99
        $tableDiff->changedForeignKeys[] = $foreignKey;
100
101
        $this->alterTable($tableDiff);
102
    }
103
104
    /**
105
     * {@inheritdoc}
106
     */
107
    public function dropForeignKey($foreignKey, $table) : void
108
    {
109
        $table = $this->ensureTable($table);
110
111
        $tableDiff = $this->getTableDiffForAlterForeignKey($table);
112
113
        if (is_string($foreignKey)) {
114
            $tableDiff->removedForeignKeys[] = $table->getForeignKey($foreignKey);
115
        } else {
116
            $tableDiff->removedForeignKeys[] = $foreignKey;
117
        }
118
119
        $this->alterTable($tableDiff);
120
    }
121
122
    /**
123
     * {@inheritdoc}
124
     */
125 69
    public function listTableForeignKeys(string $table, ?string $database = null) : array
126
    {
127 69
        if ($database === null) {
128 69
            $database = $this->_conn->getDatabase();
129
        }
130 69
        $sql              = $this->_platform->getListTableForeignKeysSQL($table, $database);
131 69
        $tableForeignKeys = $this->_conn->fetchAll($sql);
132
133 69
        if (! empty($tableForeignKeys)) {
134 69
            $createSql = $this->getCreateTableSQL($table);
135
136 69
            if ($createSql !== null && preg_match_all(
137
                '#
138
                    (?:CONSTRAINT\s+([^\s]+)\s+)?
139
                    (?:FOREIGN\s+KEY[^\)]+\)\s*)?
140
                    REFERENCES\s+[^\s]+\s+(?:\([^\)]+\))?
141
                    (?:
142
                        [^,]*?
143
                        (NOT\s+DEFERRABLE|DEFERRABLE)
144
                        (?:\s+INITIALLY\s+(DEFERRED|IMMEDIATE))?
145
                    )?#isx',
146 69
                $createSql,
147 69
                $match
148
            )) {
149 69
                $names      = array_reverse($match[1]);
150 69
                $deferrable = array_reverse($match[2]);
151 69
                $deferred   = array_reverse($match[3]);
152
            } else {
153
                $names = $deferrable = $deferred = [];
154
            }
155
156 69
            foreach ($tableForeignKeys as $key => $value) {
157 69
                $id                                        = $value['id'];
158 69
                $tableForeignKeys[$key]['constraint_name'] = isset($names[$id]) && $names[$id] !== '' ? $names[$id] : $id;
159 69
                $tableForeignKeys[$key]['deferrable']      = isset($deferrable[$id]) && strtolower($deferrable[$id]) === 'deferrable';
160 69
                $tableForeignKeys[$key]['deferred']        = isset($deferred[$id]) && strtolower($deferred[$id]) === 'deferred';
161
            }
162
        }
163
164 69
        return $this->_getPortableTableForeignKeysList($tableForeignKeys);
165
    }
166
167
    /**
168
     * {@inheritdoc}
169
     */
170 139
    protected function _getPortableTableDefinition(array $table) : string
171
    {
172 139
        return $table['name'];
173
    }
174
175
    /**
176
     * {@inheritdoc}
177
     *
178
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
179
     */
180 132
    protected function _getPortableTableIndexesList(array $tableIndexRows, string $tableName) : array
181
    {
182 132
        $indexBuffer = [];
183
184
        // fetch primary
185 132
        $stmt       = $this->_conn->executeQuery(sprintf(
186 2
            'PRAGMA TABLE_INFO (%s)',
187 132
            $this->_conn->quote($tableName)
188
        ));
189 132
        $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
190
191
        usort($indexArray, static function ($a, $b) {
192 80
            if ($a['pk'] === $b['pk']) {
193 80
                return $a['cid'] - $b['cid'];
194
            }
195
196 70
            return $a['pk'] - $b['pk'];
197 132
        });
198 132
        foreach ($indexArray as $indexColumnRow) {
199 132
            if ($indexColumnRow['pk'] === '0') {
200 82
                continue;
201
            }
202
203 120
            $indexBuffer[] = [
204 120
                'key_name' => 'primary',
205
                'primary' => true,
206
                'non_unique' => false,
207 120
                'column_name' => $indexColumnRow['name'],
208
            ];
209
        }
210
211
        // fetch regular indexes
212 132
        foreach ($tableIndexRows as $tableIndex) {
213
            // Ignore indexes with reserved names, e.g. autoindexes
214 66
            if (strpos($tableIndex['name'], 'sqlite_') === 0) {
215 66
                continue;
216
            }
217
218 58
            $keyName           = $tableIndex['name'];
219 58
            $idx               = [];
220 58
            $idx['key_name']   = $keyName;
221 58
            $idx['primary']    = false;
222 58
            $idx['non_unique'] = ! $tableIndex['unique'];
223
224 58
                $stmt       = $this->_conn->executeQuery(sprintf(
225
                    'PRAGMA INDEX_INFO (%s)',
226 58
                    $this->_conn->quote($keyName)
227
                ));
228 58
                $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
229
230 58
            foreach ($indexArray as $indexColumnRow) {
231 58
                $idx['column_name'] = $indexColumnRow['name'];
232 58
                $indexBuffer[]      = $idx;
233
            }
234
        }
235
236 132
        return parent::_getPortableTableIndexesList($indexBuffer, $tableName);
237
    }
238
239
    /**
240
     * {@inheritdoc}
241
     */
242 132
    protected function _getPortableTableColumnList(string $table, string $database, array $tableColumns) : array
243
    {
244 132
        $list = parent::_getPortableTableColumnList($table, $database, $tableColumns);
245
246
        // find column with autoincrement
247 132
        $autoincrementColumn = null;
248 132
        $autoincrementCount  = 0;
249
250 132
        foreach ($tableColumns as $tableColumn) {
251 132
            if ($tableColumn['pk'] === '0') {
252 82
                continue;
253
            }
254
255 120
            $autoincrementCount++;
256 120
            if ($autoincrementColumn !== null || strtolower($tableColumn['type']) !== 'integer') {
257 58
                continue;
258
            }
259
260 120
            $autoincrementColumn = $tableColumn['name'];
261
        }
262
263 132
        if ($autoincrementCount === 1 && $autoincrementColumn !== null) {
0 ignored issues
show
introduced by
The condition $autoincrementColumn !== null is always false.
Loading history...
264 120
            foreach ($list as $column) {
265 120
                if ($autoincrementColumn !== $column->getName()) {
266 70
                    continue;
267
                }
268
269 120
                $column->setAutoincrement(true);
270
            }
271
        }
272
273
        // inspect column collation and comments
274 132
        $createSql = $this->getCreateTableSQL($table) ?? '';
275
276 132
        foreach ($list as $columnName => $column) {
277 132
            $type = $column->getType();
278
279 132
            if ($type instanceof StringType || $type instanceof TextType) {
280 80
                $column->setPlatformOption('collation', $this->parseColumnCollationFromSQL($columnName, $createSql) ?: 'BINARY');
281
            }
282
283 132
            $comment = $this->parseColumnCommentFromSQL($columnName, $createSql);
284
285 132
            $type = $this->extractDoctrineTypeFromComment($comment);
286
287 132
            if ($type !== null) {
288 44
                $column->setType(Type::getType($type));
289
            }
290
291 132
            $column->setComment($comment);
292
        }
293
294 132
        return $list;
295
    }
296
297
    /**
298
     * {@inheritdoc}
299
     */
300 132
    protected function _getPortableTableColumnDefinition(array $tableColumn) : Column
301
    {
302 132
        preg_match('/^([^()]*)\\s*(\\(((\\d+)(,\\s*(\\d+))?)\\))?/', $tableColumn['type'], $matches);
303
304 132
        $dbType = trim(strtolower($matches[1]));
305
306 132
        $length = $precision = $unsigned = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $unsigned is dead and can be removed.
Loading history...
307 132
        $fixed  = $unsigned = false;
308 132
        $scale  = 0;
309
310 132
        if (count($matches) >= 6) {
311 57
            $precision = (int) $matches[4];
312 57
            $scale     = (int) $matches[6];
313 132
        } elseif (count($matches) >= 4) {
314 80
            $length = (int) $matches[4];
315
        }
316
317 132
        if (strpos($dbType, ' unsigned') !== false) {
318 32
            $dbType   = str_replace(' unsigned', '', $dbType);
319 32
            $unsigned = true;
320
        }
321
322 132
        $type    = $this->_platform->getDoctrineTypeMapping($dbType);
323 132
        $default = $tableColumn['dflt_value'];
324 132
        if ($default === 'NULL') {
325 80
            $default = null;
326
        }
327
328 132
        if ($default !== null) {
329
            // SQLite returns the default value as a literal expression, so we need to parse it
330 82
            if (preg_match('/^\'(.*)\'$/s', $default, $matches)) {
331 81
                $default = str_replace("''", "'", $matches[1]);
332
            }
333
        }
334
335 132
        $notnull = (bool) $tableColumn['notnull'];
336
337 132
        if (! isset($tableColumn['name'])) {
338
            $tableColumn['name'] = '';
339
        }
340
341 132
        if ($dbType === 'char') {
342 56
            $fixed = true;
343
        }
344
345
        $options = [
346 132
            'length'   => $length,
347 132
            'unsigned' => $unsigned,
348 132
            'fixed'    => $fixed,
349 132
            'notnull'  => $notnull,
350 132
            'default'  => $default,
351 132
            'precision' => $precision,
352 132
            'scale'     => $scale,
353
            'autoincrement' => false,
354
        ];
355
356 132
        return new Column($tableColumn['name'], Type::getType($type), $options);
357
    }
358
359
    /**
360
     * {@inheritdoc}
361
     */
362 48
    protected function _getPortableViewDefinition(array $view) : View
363
    {
364 48
        return new View($view['name'], $view['sql']);
365
    }
366
367
    /**
368
     * {@inheritdoc}
369
     */
370 69
    protected function _getPortableTableForeignKeysList(array $tableForeignKeys) : array
371
    {
372 69
        $list = [];
373 69
        foreach ($tableForeignKeys as $value) {
374 69
            $value = array_change_key_case($value, CASE_LOWER);
375 69
            $name  = $value['constraint_name'];
376 69
            if (! isset($list[$name])) {
377 69
                if (! isset($value['on_delete']) || $value['on_delete'] === 'RESTRICT') {
378
                    $value['on_delete'] = null;
379
                }
380 69
                if (! isset($value['on_update']) || $value['on_update'] === 'RESTRICT') {
381
                    $value['on_update'] = null;
382
                }
383
384 69
                $list[$name] = [
385 69
                    'name' => $name,
386
                    'local' => [],
387
                    'foreign' => [],
388 69
                    'foreignTable' => $value['table'],
389 69
                    'onDelete' => $value['on_delete'],
390 69
                    'onUpdate' => $value['on_update'],
391 69
                    'deferrable' => $value['deferrable'],
392 69
                    'deferred'=> $value['deferred'],
393
                ];
394
            }
395 69
            $list[$name]['local'][]   = $value['from'];
396 69
            $list[$name]['foreign'][] = $value['to'];
397
        }
398
399 69
        $result = [];
400 69
        foreach ($list as $constraint) {
401 69
            $result[] = new ForeignKeyConstraint(
402 69
                array_values($constraint['local']),
403 69
                $constraint['foreignTable'],
404 69
                array_values($constraint['foreign']),
405 69
                $constraint['name'],
406
                [
407 69
                    'onDelete' => $constraint['onDelete'],
408 69
                    'onUpdate' => $constraint['onUpdate'],
409 69
                    'deferrable' => $constraint['deferrable'],
410 69
                    'deferred'=> $constraint['deferred'],
411
                ]
412
            );
413
        }
414
415 69
        return $result;
416
    }
417
418
    private function getTableDiffForAlterForeignKey(Table $table) : TableDiff
419
    {
420
        $tableDiff            = new TableDiff($table->getName());
421
        $tableDiff->fromTable = $table;
422
423
        return $tableDiff;
424
    }
425
426
    /**
427
     * @param string|Table $table
428
     */
429
    private function ensureTable($table) : Table
430
    {
431
        if (is_string($table)) {
432
            $table = $this->listTableDetails($table);
433
        }
434
435
        return $table;
436
    }
437
438 840
    private function parseColumnCollationFromSQL(string $column, string $sql) : ?string
439
    {
440 840
        $pattern = '{(?:\W' . preg_quote($column) . '\W|\W' . preg_quote($this->_platform->quoteSingleIdentifier($column))
441 840
            . '\W)[^,(]+(?:\([^()]+\)[^,]*)?(?:(?:DEFAULT|CHECK)\s*(?:\(.*?\))?[^,]*)*COLLATE\s+["\']?([^\s,"\')]+)}is';
442
443 840
        if (preg_match($pattern, $sql, $match) !== 1) {
444 805
            return null;
445
        }
446
447 823
        return $match[1];
448
    }
449
450 610
    private function parseColumnCommentFromSQL(string $column, string $sql) : ?string
451
    {
452 610
        $pattern = '{[\s(,](?:\W' . preg_quote($this->_platform->quoteSingleIdentifier($column)) . '\W|\W' . preg_quote($column)
453 610
            . '\W)(?:\(.*?\)|[^,(])*?,?((?:(?!\n))(?:\s*--[^\n]*\n?)+)}i';
454
455 610
        if (preg_match($pattern, $sql, $match) !== 1) {
456 575
            return null;
457
        }
458
459 595
        $comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n"));
460
461 595
        return $comment === '' ? null : $comment;
462
    }
463
464 132
    private function getCreateTableSQL(string $table) : ?string
465
    {
466 132
        return $this->_conn->fetchColumn(
467
            <<<'SQL'
468 132
SELECT sql
469
  FROM (
470
      SELECT *
471
        FROM sqlite_master
472
   UNION ALL
473
      SELECT *
474
        FROM sqlite_temp_master
475
  )
476
WHERE type = 'table'
477
AND name = ?
478
SQL
479
            ,
480 132
            [$table]
481 132
        ) ?: null;
482
    }
483
}
484