Failed Conditions
Push — 3.0.x ( 655b6b...430dce )
by Grégoire
16:57 queued 12:22
created

SqliteSchemaManager::createForeignKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
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 function array_change_key_case;
12
use function array_map;
13
use function array_reverse;
14
use function array_values;
15
use function explode;
16
use function file_exists;
17
use function preg_match;
18
use function preg_match_all;
19
use function preg_quote;
20
use function preg_replace;
21
use function rtrim;
22
use function sprintf;
23
use function str_replace;
24
use function strpos;
25
use function strtolower;
26
use function trim;
27
use function unlink;
28
use function usort;
29
use const CASE_LOWER;
30
31
/**
32
 * Sqlite SchemaManager.
33
 */
34
class SqliteSchemaManager extends AbstractSchemaManager
35
{
36
    /**
37
     * {@inheritdoc}
38
     */
39 2
    public function dropDatabase($database)
40
    {
41 2
        if (! file_exists($database)) {
42 1
            return;
43
        }
44
45 2
        unlink($database);
46 2
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51 2
    public function createDatabase($database)
52
    {
53 2
        $params  = $this->_conn->getParams();
54 2
        $driver  = $params['driver'];
55
        $options = [
56 2
            'driver' => $driver,
57 2
            'path' => $database,
58
        ];
59 2
        $conn    = DriverManager::getConnection($options);
60 2
        $conn->connect();
61 2
        $conn->close();
62 2
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67 1
    public function renameTable($name, $newName)
68
    {
69 1
        $tableDiff            = new TableDiff($name);
70 1
        $tableDiff->fromTable = $this->listTableDetails($name);
71 1
        $tableDiff->newName   = $newName;
72 1
        $this->alterTable($tableDiff);
73 1
    }
74
75
    /**
76
     * {@inheritdoc}
77
     */
78 2
    public function createForeignKey(ForeignKeyConstraint $foreignKey, $table)
79
    {
80 2
        $tableDiff                     = $this->getTableDiffForAlterForeignKey($table);
81 2
        $tableDiff->addedForeignKeys[] = $foreignKey;
82
83 2
        $this->alterTable($tableDiff);
84 2
    }
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 99
    public function listTableForeignKeys($table, $database = null)
112
    {
113 99
        if ($database === null) {
114 99
            $database = $this->_conn->getDatabase();
115
        }
116
117 99
        $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

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