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