Failed Conditions
Pull Request — master (#3512)
by David
15:05
created

SqliteSchemaManager::parseTableCommentFromSQL()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

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