Completed
Pull Request — master (#3512)
by David
16:25
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 0
Metric Value
eloc 10
dl 0
loc 17
ccs 7
cts 7
cp 1
rs 9.9332
c 0
b 0
f 0
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 89
    public function dropDatabase($database)
40
    {
41 89
        if (! file_exists($database)) {
42 88
            return;
43
        }
44
45 89
        unlink($database);
46 89
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51 89
    public function createDatabase($database)
52
    {
53 89
        $params  = $this->_conn->getParams();
54 89
        $driver  = $params['driver'];
55
        $options = [
56 89
            'driver' => $driver,
57 89
            'path' => $database,
58
        ];
59 89
        $conn    = DriverManager::getConnection($options);
60 89
        $conn->connect();
61 89
        $conn->close();
62 89
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67 87
    public function renameTable($name, $newName)
68
    {
69 87
        $tableDiff            = new TableDiff($name);
70 87
        $tableDiff->fromTable = $this->listTableDetails($name);
71 87
        $tableDiff->newName   = $newName;
72 87
        $this->alterTable($tableDiff);
73 87
    }
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 86
    public function listTableForeignKeys($table, $database = null)
112
    {
113 86
        if ($database === null) {
114 86
            $database = $this->_conn->getDatabase();
115
        }
116 86
        $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 86
        $tableForeignKeys = $this->_conn->fetchAll($sql);
118
119 86
        if (! empty($tableForeignKeys)) {
120 86
            $createSql = $this->getCreateTableSQL($table);
121
122 86
            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 86
                $createSql,
133 86
                $match
134
            )) {
135 86
                $names      = array_reverse($match[1]);
136 86
                $deferrable = array_reverse($match[2]);
137 86
                $deferred   = array_reverse($match[3]);
138
            } else {
139
                $names = $deferrable = $deferred = [];
140
            }
141
142 86
            foreach ($tableForeignKeys as $key => $value) {
143 86
                $id                                        = $value['id'];
144 86
                $tableForeignKeys[$key]['constraint_name'] = isset($names[$id]) && $names[$id] !== '' ? $names[$id] : $id;
145 86
                $tableForeignKeys[$key]['deferrable']      = isset($deferrable[$id]) && strtolower($deferrable[$id]) === 'deferrable';
146 86
                $tableForeignKeys[$key]['deferred']        = isset($deferred[$id]) && strtolower($deferred[$id]) === 'deferred';
147
            }
148
        }
149
150 86
        return $this->_getPortableTableForeignKeysList($tableForeignKeys);
151
    }
152
153
    /**
154
     * {@inheritdoc}
155
     */
156 151
    protected function _getPortableTableDefinition($table)
157
    {
158 151
        return $table['name'];
159
    }
160
161
    /**
162
     * {@inheritdoc}
163
     *
164
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
165
     */
166 144
    protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
167
    {
168 144
        $indexBuffer = [];
169
170
        // fetch primary
171 144
        $stmt       = $this->_conn->executeQuery(sprintf(
172 4
            'PRAGMA TABLE_INFO (%s)',
173 144
            $this->_conn->quote($tableName)
174
        ));
175 144
        $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
176
177
        usort($indexArray, static function ($a, $b) {
178 87
            if ($a['pk'] === $b['pk']) {
179 87
                return $a['cid'] - $b['cid'];
180
            }
181
182 87
            return $a['pk'] - $b['pk'];
183 144
        });
184 144
        foreach ($indexArray as $indexColumnRow) {
185 144
            if ($indexColumnRow['pk'] === '0') {
186 92
                continue;
187
            }
188
189 139
            $indexBuffer[] = [
190 139
                'key_name' => 'primary',
191
                'primary' => true,
192
                'non_unique' => false,
193 139
                'column_name' => $indexColumnRow['name'],
194
            ];
195
        }
196
197
        // fetch regular indexes
198 144
        foreach ($tableIndexes as $tableIndex) {
199
            // Ignore indexes with reserved names, e.g. autoindexes
200 83
            if (strpos($tableIndex['name'], 'sqlite_') === 0) {
201 83
                continue;
202
            }
203
204 74
            $keyName           = $tableIndex['name'];
205 74
            $idx               = [];
206 74
            $idx['key_name']   = $keyName;
207 74
            $idx['primary']    = false;
208 74
            $idx['non_unique'] = ! $tableIndex['unique'];
209
210 74
                $stmt       = $this->_conn->executeQuery(sprintf(
211
                    'PRAGMA INDEX_INFO (%s)',
212 74
                    $this->_conn->quote($keyName)
213
                ));
214 74
                $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
215
216 74
            foreach ($indexArray as $indexColumnRow) {
217 74
                $idx['column_name'] = $indexColumnRow['name'];
218 74
                $indexBuffer[]      = $idx;
219
            }
220
        }
221
222 144
        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 144
    protected function _getPortableTableColumnList($table, $database, $tableColumns)
240
    {
241 144
        $list = parent::_getPortableTableColumnList($table, $database, $tableColumns);
242
243
        // find column with autoincrement
244 144
        $autoincrementColumn = null;
245 144
        $autoincrementCount  = 0;
246
247 144
        foreach ($tableColumns as $tableColumn) {
248 144
            if ($tableColumn['pk'] === '0') {
249 92
                continue;
250
            }
251
252 139
            $autoincrementCount++;
253 139
            if ($autoincrementColumn !== null || strtolower($tableColumn['type']) !== 'integer') {
254 74
                continue;
255
            }
256
257 139
            $autoincrementColumn = $tableColumn['name'];
258
        }
259
260 144
        if ($autoincrementCount === 1 && $autoincrementColumn !== null) {
0 ignored issues
show
introduced by
The condition $autoincrementColumn !== null is always false.
Loading history...
261 139
            foreach ($list as $column) {
262 139
                if ($autoincrementColumn !== $column->getName()) {
263 87
                    continue;
264
                }
265
266 139
                $column->setAutoincrement(true);
267
            }
268
        }
269
270
        // inspect column collation and comments
271 144
        $createSql = $this->getCreateTableSQL($table) ?? '';
272
273 144
        foreach ($list as $columnName => $column) {
274 144
            $type = $column->getType();
275
276 144
            if ($type instanceof StringType || $type instanceof TextType) {
277 87
                $column->setPlatformOption('collation', $this->parseColumnCollationFromSQL($columnName, $createSql) ?: 'BINARY');
278
            }
279
280 144
            $comment = $this->parseColumnCommentFromSQL($columnName, $createSql);
281
282 144
            if ($comment === null) {
283 144
                continue;
284
            }
285
286 61
            $type = $this->extractDoctrineTypeFromComment($comment, '');
287
288 61
            if ($type !== '') {
289 60
                $column->setType(Type::getType($type));
290
291 60
                $comment = $this->removeDoctrineTypeFromComment($comment, $type);
292
            }
293
294 61
            $column->setComment($comment);
295
        }
296
297 144
        return $list;
298
    }
299
300
    /**
301
     * {@inheritdoc}
302
     */
303 144
    protected function _getPortableTableColumnDefinition($tableColumn)
304
    {
305 144
        $parts               = explode('(', $tableColumn['type']);
306 144
        $tableColumn['type'] = trim($parts[0]);
307 144
        if (isset($parts[1])) {
308 87
            $length                = trim($parts[1], ')');
309 87
            $tableColumn['length'] = $length;
310
        }
311
312 144
        $dbType   = strtolower($tableColumn['type']);
313 144
        $length   = $tableColumn['length'] ?? null;
314 144
        $unsigned = false;
315
316 144
        if (strpos($dbType, ' unsigned') !== false) {
317 36
            $dbType   = str_replace(' unsigned', '', $dbType);
318 36
            $unsigned = true;
319
        }
320
321 144
        $fixed   = false;
322 144
        $type    = $this->_platform->getDoctrineTypeMapping($dbType);
323 144
        $default = $tableColumn['dflt_value'];
324 144
        if ($default === 'NULL') {
325 73
            $default = null;
326
        }
327 144
        if ($default !== null) {
328
            // SQLite returns strings wrapped in single quotes, so we need to strip them
329 92
            $default = preg_replace("/^'(.*)'$/", '\1', $default);
330
        }
331 144
        $notnull = (bool) $tableColumn['notnull'];
332
333 144
        if (! isset($tableColumn['name'])) {
334
            $tableColumn['name'] = '';
335
        }
336
337 144
        $precision = null;
338 144
        $scale     = null;
339
340 144
        switch ($dbType) {
341 4
            case 'char':
342 72
                $fixed = true;
343 72
                break;
344 4
            case 'float':
345 4
            case 'double':
346 4
            case 'real':
347 4
            case 'decimal':
348 4
            case 'numeric':
349 73
                if (isset($tableColumn['length'])) {
350 73
                    if (strpos($tableColumn['length'], ',') === false) {
351
                        $tableColumn['length'] .= ',0';
352
                    }
353 73
                    [$precision, $scale] = array_map('trim', explode(',', $tableColumn['length']));
354
                }
355 73
                $length = null;
356 73
                break;
357
        }
358
359
        $options = [
360 144
            'length'   => $length,
361 144
            'unsigned' => (bool) $unsigned,
362 144
            'fixed'    => $fixed,
363 144
            'notnull'  => $notnull,
364 144
            'default'  => $default,
365 144
            'precision' => $precision,
366 144
            'scale'     => $scale,
367
            'autoincrement' => false,
368
        ];
369
370 144
        return new Column($tableColumn['name'], Type::getType($type), $options);
371
    }
372
373
    /**
374
     * {@inheritdoc}
375
     */
376 64
    protected function _getPortableViewDefinition($view)
377
    {
378 64
        return new View($view['name'], $view['sql']);
379
    }
380
381
    /**
382
     * {@inheritdoc}
383
     */
384 86
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
385
    {
386 86
        $list = [];
387 86
        foreach ($tableForeignKeys as $value) {
388 86
            $value = array_change_key_case($value, CASE_LOWER);
389 86
            $name  = $value['constraint_name'];
390 86
            if (! isset($list[$name])) {
391 86
                if (! isset($value['on_delete']) || $value['on_delete'] === 'RESTRICT') {
392
                    $value['on_delete'] = null;
393
                }
394 86
                if (! isset($value['on_update']) || $value['on_update'] === 'RESTRICT') {
395
                    $value['on_update'] = null;
396
                }
397
398 86
                $list[$name] = [
399 86
                    'name' => $name,
400
                    'local' => [],
401
                    'foreign' => [],
402 86
                    'foreignTable' => $value['table'],
403 86
                    'onDelete' => $value['on_delete'],
404 86
                    'onUpdate' => $value['on_update'],
405 86
                    'deferrable' => $value['deferrable'],
406 86
                    'deferred'=> $value['deferred'],
407
                ];
408
            }
409 86
            $list[$name]['local'][]   = $value['from'];
410 86
            $list[$name]['foreign'][] = $value['to'];
411
        }
412
413 86
        $result = [];
414 86
        foreach ($list as $constraint) {
415 86
            $result[] = new ForeignKeyConstraint(
416 86
                array_values($constraint['local']),
417 86
                $constraint['foreignTable'],
418 86
                array_values($constraint['foreign']),
419 86
                $constraint['name'],
420
                [
421 86
                    'onDelete' => $constraint['onDelete'],
422 86
                    'onUpdate' => $constraint['onUpdate'],
423 86
                    'deferrable' => $constraint['deferrable'],
424 86
                    'deferred'=> $constraint['deferred'],
425
                ]
426
            );
427
        }
428
429 86
        return $result;
430
    }
431
432
    /**
433
     * @param Table|string $table
434
     *
435
     * @return TableDiff
436
     *
437
     * @throws DBALException
438
     */
439
    private function getTableDiffForAlterForeignKey($table)
440
    {
441
        if (! $table instanceof Table) {
442
            $tableDetails = $this->tryMethod('listTableDetails', $table);
443
444
            if ($tableDetails === false) {
445
                throw new DBALException(sprintf('Sqlite schema manager requires to modify foreign keys table definition "%s".', $table));
446
            }
447
448
            $table = $tableDetails;
449
        }
450
451
        $tableDiff            = new TableDiff($table->getName());
452
        $tableDiff->fromTable = $table;
453
454
        return $tableDiff;
455
    }
456
457 959
    private function parseColumnCollationFromSQL(string $column, string $sql) : ?string
458
    {
459 959
        $pattern = '{(?:\W' . preg_quote($column) . '\W|\W' . preg_quote($this->_platform->quoteSingleIdentifier($column))
460 959
            . '\W)[^,(]+(?:\([^()]+\)[^,]*)?(?:(?:DEFAULT|CHECK)\s*(?:\(.*?\))?[^,]*)*COLLATE\s+["\']?([^\s,"\')]+)}is';
461
462 959
        if (preg_match($pattern, $sql, $match) !== 1) {
463 889
            return null;
464
        }
465
466 947
        return $match[1];
467
    }
468
469 144
    private function parseTableCommentFromSQL(string $table, string $sql) : ?string
470
    {
471
        $pattern = '/\s* # Allow whitespace characters at start of line
472
CREATE\sTABLE # Match "CREATE TABLE"
473 144
(?:\W"' . preg_quote($this->_platform->quoteSingleIdentifier($table), '/') . '"\W|\W' . preg_quote($table, '/')
474 144
            . '\W) # Match table name (quoted and unquoted)
475
( # Start capture
476
   (?:\s*--[^\n]*\n?)+ # Capture anything that starts with whitespaces followed by -- until the end of the line(s)
477
)/ix';
478
479 144
        if (preg_match($pattern, $sql, $match) !== 1) {
480 144
            return null;
481
        }
482
483 37
        $comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n"));
484
485 37
        return $comment === '' ? null : $comment;
486
    }
487
488 668
    private function parseColumnCommentFromSQL(string $column, string $sql) : ?string
489
    {
490 668
        $pattern = '{[\s(,](?:\W' . preg_quote($this->_platform->quoteSingleIdentifier($column)) . '\W|\W' . preg_quote($column)
491 668
            . '\W)(?:\(.*?\)|[^,(])*?,?((?:(?!\n))(?:\s*--[^\n]*\n?)+)}i';
492
493 668
        if (preg_match($pattern, $sql, $match) !== 1) {
494 646
            return null;
495
        }
496
497 611
        $comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n"));
498
499 611
        return $comment === '' ? null : $comment;
500
    }
501
502 144
    private function getCreateTableSQL(string $table) : ?string
503
    {
504 144
        return $this->_conn->fetchColumn(
505
            <<<'SQL'
506 144
SELECT sql
507
  FROM (
508
      SELECT *
509
        FROM sqlite_master
510
   UNION ALL
511
      SELECT *
512
        FROM sqlite_temp_master
513
  )
514
WHERE type = 'table'
515
AND name = ?
516
SQL
517
            ,
518 144
            [$table]
519 144
        ) ?: null;
520
    }
521
522
    /**
523
     * @param string $tableName
524
     */
525 144
    public function listTableDetails($tableName) : Table
526
    {
527 144
        $table = parent::listTableDetails($tableName);
528
529 144
        $tableCreateSql = $this->getCreateTableSQL($tableName) ?? '';
530
531 144
        $comment = $this->parseTableCommentFromSQL($tableName, $tableCreateSql);
532
533 144
        if ($comment !== null) {
534 37
            $table->addOption('comment', $comment);
535
        }
536
537 144
        return $table;
538
    }
539
}
540