Completed
Pull Request — develop (#3565)
by Jonathan
61:48
created

_getPortableTableIndexesList()   B

Complexity

Conditions 7
Paths 12

Size

Total Lines 57
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 7.1429

Importance

Changes 0
Metric Value
eloc 33
dl 0
loc 57
ccs 24
cts 28
cp 0.8571
rs 8.4586
c 0
b 0
f 0
cc 7
nc 12
nop 2
crap 7.1429

How to fix   Long Method   

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