Completed
Pull Request — 2.11.x (#3956)
by David
14:33
created

_getPortableTableColumnDefinition()   F

Complexity

Conditions 15
Paths 816

Size

Total Lines 72
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 46
CRAP Score 15.0163

Importance

Changes 0
Metric Value
eloc 49
dl 0
loc 72
ccs 46
cts 48
cp 0.9583
rs 2.0055
c 0
b 0
f 0
cc 15
nc 816
nop 1
crap 15.0163

How to fix   Long Method    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
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 83
    public function dropDatabase($database)
40
    {
41 83
        if (! file_exists($database)) {
42 82
            return;
43
        }
44
45 83
        unlink($database);
46 83
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51 83
    public function createDatabase($database)
52
    {
53 83
        $params  = $this->_conn->getParams();
54 83
        $driver  = $params['driver'];
55
        $options = [
56 83
            'driver' => $driver,
57 83
            'path' => $database,
58
        ];
59 83
        $conn    = DriverManager::getConnection($options);
60 83
        $conn->connect();
61 83
        $conn->close();
62 83
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67 81
    public function renameTable($name, $newName)
68
    {
69 81
        $tableDiff            = new TableDiff($name);
70 81
        $tableDiff->fromTable = $this->listTableDetails($name);
71 81
        $tableDiff->newName   = $newName;
72 81
        $this->alterTable($tableDiff);
73 81
    }
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 80
    public function listTableForeignKeys($table, $database = null)
112
    {
113 80
        if ($database === null) {
114 80
            $database = $this->_conn->getDatabase();
115
        }
116 80
        $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 80
        $tableForeignKeys = $this->_conn->fetchAll($sql);
118
119 80
        if (! empty($tableForeignKeys)) {
120 80
            $createSql = $this->getCreateTableSQL($table);
121
122 80
            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 80
                $createSql,
133 80
                $match
134
            )) {
135 80
                $names      = array_reverse($match[1]);
136 80
                $deferrable = array_reverse($match[2]);
137 80
                $deferred   = array_reverse($match[3]);
138
            } else {
139
                $names = $deferrable = $deferred = [];
140
            }
141
142 80
            foreach ($tableForeignKeys as $key => $value) {
143 80
                $id                                        = $value['id'];
144 80
                $tableForeignKeys[$key]['constraint_name'] = isset($names[$id]) && $names[$id] !== '' ? $names[$id] : $id;
145 80
                $tableForeignKeys[$key]['deferrable']      = isset($deferrable[$id]) && strtolower($deferrable[$id]) === 'deferrable';
146 80
                $tableForeignKeys[$key]['deferred']        = isset($deferred[$id]) && strtolower($deferred[$id]) === 'deferred';
147
            }
148
        }
149
150 80
        return $this->_getPortableTableForeignKeysList($tableForeignKeys);
151
    }
152
153
    /**
154
     * {@inheritdoc}
155
     */
156 149
    protected function _getPortableTableDefinition($table)
157
    {
158 149
        return $table['name'];
159
    }
160
161
    /**
162
     * {@inheritdoc}
163
     *
164
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
165
     */
166 142
    protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
167
    {
168 142
        $indexBuffer = [];
169
170
        // fetch primary
171 142
        $stmt       = $this->_conn->executeQuery(sprintf(
172 2
            'PRAGMA TABLE_INFO (%s)',
173 142
            $this->_conn->quote($tableName)
174
        ));
175 142
        $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
176
177
        usort($indexArray, static function ($a, $b) {
178 90
            if ($a['pk'] === $b['pk']) {
179 90
                return $a['cid'] - $b['cid'];
180
            }
181
182 81
            return $a['pk'] - $b['pk'];
183 142
        });
184 142
        foreach ($indexArray as $indexColumnRow) {
185 142
            if ($indexColumnRow['pk'] === '0') {
186 92
                continue;
187
            }
188
189 131
            $indexBuffer[] = [
190 131
                'key_name' => 'primary',
191
                'primary' => true,
192
                'non_unique' => false,
193 131
                'column_name' => $indexColumnRow['name'],
194
            ];
195
        }
196
197
        // fetch regular indexes
198 142
        foreach ($tableIndexes as $tableIndex) {
199
            // Ignore indexes with reserved names, e.g. autoindexes
200 77
            if (strpos($tableIndex['name'], 'sqlite_') === 0) {
201 77
                continue;
202
            }
203
204 67
            $keyName           = $tableIndex['name'];
205 67
            $idx               = [];
206 67
            $idx['key_name']   = $keyName;
207 67
            $idx['primary']    = false;
208 67
            $idx['non_unique'] = ! $tableIndex['unique'];
209
210 67
                $stmt       = $this->_conn->executeQuery(sprintf(
211
                    'PRAGMA INDEX_INFO (%s)',
212 67
                    $this->_conn->quote($keyName)
213
                ));
214 67
                $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
215
216 67
            foreach ($indexArray as $indexColumnRow) {
217 67
                $idx['column_name'] = $indexColumnRow['name'];
218 67
                $indexBuffer[]      = $idx;
219
            }
220
        }
221
222 142
        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 142
    protected function _getPortableTableColumnList($table, $database, $tableColumns)
244
    {
245 142
        $list = parent::_getPortableTableColumnList($table, $database, $tableColumns);
246
247
        // find column with autoincrement
248 142
        $autoincrementColumn = null;
249 142
        $autoincrementCount  = 0;
250
251 142
        foreach ($tableColumns as $tableColumn) {
252 142
            if ($tableColumn['pk'] === '0') {
253 92
                continue;
254
            }
255
256 131
            $autoincrementCount++;
257 131
            if ($autoincrementColumn !== null || strtolower($tableColumn['type']) !== 'integer') {
258 67
                continue;
259
            }
260
261 131
            $autoincrementColumn = $tableColumn['name'];
262
        }
263
264 142
        if ($autoincrementCount === 1 && $autoincrementColumn !== null) {
0 ignored issues
show
introduced by
The condition $autoincrementColumn !== null is always false.
Loading history...
265 131
            foreach ($list as $column) {
266 131
                if ($autoincrementColumn !== $column->getName()) {
267 81
                    continue;
268
                }
269
270 131
                $column->setAutoincrement(true);
271
            }
272
        }
273
274
        // inspect column collation and comments
275 142
        $createSql = $this->getCreateTableSQL($table) ?? '';
276
277 142
        foreach ($list as $columnName => $column) {
278 142
            $type = $column->getType();
279
280 142
            if ($type instanceof StringType || $type instanceof TextType) {
281 90
                $column->setPlatformOption('collation', $this->parseColumnCollationFromSQL($columnName, $createSql) ?: 'BINARY');
282
            }
283
284 142
            $comment = $this->parseColumnCommentFromSQL($columnName, $createSql);
285
286 142
            if ($comment === null) {
287 142
                continue;
288
            }
289
290 90
            $type = $this->extractDoctrineTypeFromComment($comment, '');
291
292 90
            if ($type !== '') {
293 53
                $column->setType(Type::getType($type));
294
295 53
                $comment = $this->removeDoctrineTypeFromComment($comment, $type);
296
            }
297
298 90
            $column->setComment($comment);
299
        }
300
301 142
        return $list;
302
    }
303
304
    /**
305
     * {@inheritdoc}
306
     */
307 142
    protected function _getPortableTableColumnDefinition($tableColumn)
308
    {
309 142
        $parts               = explode('(', $tableColumn['type']);
310 142
        $tableColumn['type'] = trim($parts[0]);
311 142
        if (isset($parts[1])) {
312 90
            $length                = trim($parts[1], ')');
313 90
            $tableColumn['length'] = $length;
314
        }
315
316 142
        $dbType   = strtolower($tableColumn['type']);
317 142
        $length   = $tableColumn['length'] ?? null;
318 142
        $unsigned = false;
319
320 142
        if (strpos($dbType, ' unsigned') !== false) {
321 32
            $dbType   = str_replace(' unsigned', '', $dbType);
322 32
            $unsigned = true;
323
        }
324
325 142
        $fixed   = false;
326 142
        $type    = $this->_platform->getDoctrineTypeMapping($dbType);
327 142
        $default = $tableColumn['dflt_value'];
328 142
        if ($default === 'NULL') {
329 90
            $default = null;
330
        }
331
332 142
        if ($default !== null) {
333
            // SQLite returns the default value as a literal expression, so we need to parse it
334 92
            if (preg_match('/^\'(.*)\'$/s', $default, $matches)) {
335 91
                $default = str_replace("''", "'", $matches[1]);
336
            }
337
        }
338
339 142
        $notnull = (bool) $tableColumn['notnull'];
340
341 142
        if (! isset($tableColumn['name'])) {
342
            $tableColumn['name'] = '';
343
        }
344
345 142
        $precision = null;
346 142
        $scale     = null;
347
348 2
        switch ($dbType) {
349 142
            case 'char':
350 65
                $fixed = true;
351 65
                break;
352 142
            case 'float':
353 142
            case 'double':
354 142
            case 'real':
355 142
            case 'decimal':
356 142
            case 'numeric':
357 66
                if (isset($tableColumn['length'])) {
358 66
                    if (strpos($tableColumn['length'], ',') === false) {
359
                        $tableColumn['length'] .= ',0';
360
                    }
361 66
                    [$precision, $scale] = array_map('trim', explode(',', $tableColumn['length']));
362
                }
363 66
                $length = null;
364 66
                break;
365
        }
366
367
        $options = [
368 142
            'length'   => $length,
369 142
            'unsigned' => (bool) $unsigned,
370 142
            'fixed'    => $fixed,
371 142
            'notnull'  => $notnull,
372 142
            'default'  => $default,
373 142
            'precision' => $precision,
374 142
            'scale'     => $scale,
375
            'autoincrement' => false,
376
        ];
377
378 142
        return new Column($tableColumn['name'], Type::getType($type), $options);
379
    }
380
381
    /**
382
     * {@inheritdoc}
383
     */
384 57
    protected function _getPortableViewDefinition($view)
385
    {
386 57
        return new View($view['name'], $view['sql']);
387
    }
388
389
    /**
390
     * {@inheritdoc}
391
     */
392 80
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
393
    {
394 80
        $list = [];
395 80
        foreach ($tableForeignKeys as $value) {
396 80
            $value = array_change_key_case($value, CASE_LOWER);
397 80
            $name  = $value['constraint_name'];
398 80
            if (! isset($list[$name])) {
399 80
                if (! isset($value['on_delete']) || $value['on_delete'] === 'RESTRICT') {
400
                    $value['on_delete'] = null;
401
                }
402 80
                if (! isset($value['on_update']) || $value['on_update'] === 'RESTRICT') {
403
                    $value['on_update'] = null;
404
                }
405
406 80
                $list[$name] = [
407 80
                    'name' => $name,
408
                    'local' => [],
409
                    'foreign' => [],
410 80
                    'foreignTable' => $value['table'],
411 80
                    'onDelete' => $value['on_delete'],
412 80
                    'onUpdate' => $value['on_update'],
413 80
                    'deferrable' => $value['deferrable'],
414 80
                    'deferred'=> $value['deferred'],
415
                ];
416
            }
417 80
            $list[$name]['local'][]   = $value['from'];
418 80
            $list[$name]['foreign'][] = $value['to'];
419
        }
420
421 80
        $result = [];
422 80
        foreach ($list as $constraint) {
423 80
            $result[] = new ForeignKeyConstraint(
424 80
                array_values($constraint['local']),
425 80
                $constraint['foreignTable'],
426 80
                array_values($constraint['foreign']),
427 80
                $constraint['name'],
428
                [
429 80
                    'onDelete' => $constraint['onDelete'],
430 80
                    'onUpdate' => $constraint['onUpdate'],
431 80
                    'deferrable' => $constraint['deferrable'],
432 80
                    'deferred'=> $constraint['deferred'],
433
                ]
434
            );
435
        }
436
437 80
        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 850
    private function parseColumnCollationFromSQL(string $column, string $sql) : ?string
466
    {
467 850
        $pattern = '{(?:\W' . preg_quote($column) . '\W|\W' . preg_quote($this->_platform->quoteSingleIdentifier($column))
468 850
            . '\W)[^,(]+(?:\([^()]+\)[^,]*)?(?:(?:DEFAULT|CHECK)\s*(?:\(.*?\))?[^,]*)*COLLATE\s+["\']?([^\s,"\')]+)}is';
469
470 850
        if (preg_match($pattern, $sql, $match) !== 1) {
471 815
            return null;
472
        }
473
474 834
        return $match[1];
475
    }
476
477 142
    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 142
(?:\W"' . preg_quote($this->_platform->quoteSingleIdentifier($table), '/') . '"\W|\W' . preg_quote($table, '/')
482 142
            . '\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 142
        if (preg_match($pattern, $sql, $match) !== 1) {
488 142
            return null;
489
        }
490
491 33
        $comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n"));
492
493 33
        return $comment === '' ? null : $comment;
494
    }
495
496 620
    private function parseColumnCommentFromSQL(string $column, string $sql) : ?string
497
    {
498 620
        $pattern = '{[\s(,](?:\W' . preg_quote($this->_platform->quoteSingleIdentifier($column)) . '\W|\W' . preg_quote($column)
499 620
            . '\W)(?:\([^)]*?\)|[^,(])*?,?((?:(?!\n))(?:\s*--[^\n]*\n?)+)}i';
500
501 620
        if (preg_match($pattern, $sql, $match) !== 1) {
502 585
            return null;
503
        }
504
505 605
        $comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n"));
506
507 605
        return $comment === '' ? null : $comment;
508
    }
509
510 142
    private function getCreateTableSQL(string $table) : ?string
511
    {
512 142
        return $this->_conn->fetchColumn(
513
            <<<'SQL'
514 142
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 142
            [$table]
527 142
        ) ?: null;
528
    }
529
530
    /**
531
     * @param string $tableName
532
     */
533 142
    public function listTableDetails($tableName) : Table
534
    {
535 142
        $table = parent::listTableDetails($tableName);
536
537 142
        $tableCreateSql = $this->getCreateTableSQL($tableName) ?? '';
538
539 142
        $comment = $this->parseTableCommentFromSQL($tableName, $tableCreateSql);
540
541 142
        if ($comment !== null) {
542 33
            $table->addOption('comment', $comment);
543
        }
544
545 142
        return $table;
546
    }
547
}
548