Failed Conditions
Pull Request — master (#3546)
by Sergei
14:16
created

getTableDiffForAlterForeignKey()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 16
ccs 0
cts 9
cp 0
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 12
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
    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 84
    public function listTableForeignKeys($table, $database = null)
112
    {
113 84
        if ($database === null) {
114 84
            $database = $this->_conn->getDatabase();
115
        }
116 84
        $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 84
        $tableForeignKeys = $this->_conn->fetchAll($sql);
118
119 84
        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 84
        return $this->_getPortableTableForeignKeysList($tableForeignKeys);
151
    }
152
153
    /**
154
     * {@inheritdoc}
155
     */
156 163
    protected function _getPortableTableDefinition($table)
157
    {
158 163
        return $table['name'];
159
    }
160
161
    /**
162
     * {@inheritdoc}
163
     *
164
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
165
     */
166 156
    protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
167
    {
168 156
        $indexBuffer = [];
169
170
        // fetch primary
171 156
        $stmt       = $this->_conn->executeQuery(sprintf(
172 4
            'PRAGMA TABLE_INFO (%s)',
173 156
            $this->_conn->quote($tableName)
174
        ));
175 156
        $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
176
177
        usort($indexArray, static function ($a, $b) {
178 102
            if ($a['pk'] === $b['pk']) {
179 102
                return $a['cid'] - $b['cid'];
180
            }
181
182 85
            return $a['pk'] - $b['pk'];
183 156
        });
184 156
        foreach ($indexArray as $indexColumnRow) {
185 156
            if ($indexColumnRow['pk'] === '0') {
186 104
                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 156
        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 156
        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 156
    protected function _getPortableTableColumnList($table, $database, $tableColumns)
240
    {
241 156
        $list = parent::_getPortableTableColumnList($table, $database, $tableColumns);
242
243
        // find column with autoincrement
244 156
        $autoincrementColumn = null;
245 156
        $autoincrementCount  = 0;
246
247 156
        foreach ($tableColumns as $tableColumn) {
248 156
            if ($tableColumn['pk'] === '0') {
249 104
                continue;
250
            }
251
252 137
            $autoincrementCount++;
253 137
            if ($autoincrementColumn !== null || strtolower($tableColumn['type']) !== 'integer') {
254 72
                continue;
255
            }
256
257 137
            $autoincrementColumn = $tableColumn['name'];
258
        }
259
260 156
        if ($autoincrementCount === 1 && $autoincrementColumn !== null) {
0 ignored issues
show
introduced by
The condition $autoincrementColumn !== null is always false.
Loading history...
261 137
            foreach ($list as $column) {
262 137
                if ($autoincrementColumn !== $column->getName()) {
263 85
                    continue;
264
                }
265
266 137
                $column->setAutoincrement(true);
267
            }
268
        }
269
270
        // inspect column collation and comments
271 156
        $createSql = $this->getCreateTableSQL($table) ?? '';
272
273 156
        foreach ($list as $columnName => $column) {
274 156
            $type = $column->getType();
275
276 156
            if ($type instanceof StringType || $type instanceof TextType) {
277 102
                $column->setPlatformOption('collation', $this->parseColumnCollationFromSQL($columnName, $createSql) ?: 'BINARY');
278
            }
279
280 156
            $comment = $this->parseColumnCommentFromSQL($columnName, $createSql);
281
282 156
            if ($comment === null) {
283 156
                continue;
284
            }
285
286 102
            $type = $this->extractDoctrineTypeFromComment($comment, '');
287
288 102
            if ($type !== '') {
289 58
                $column->setType(Type::getType($type));
290
291 58
                $comment = $this->removeDoctrineTypeFromComment($comment, $type);
292
            }
293
294 102
            $column->setComment($comment);
295
        }
296
297 156
        return $list;
298
    }
299
300
    /**
301
     * {@inheritdoc}
302
     */
303 156
    protected function _getPortableTableColumnDefinition($tableColumn)
304
    {
305 156
        $parts               = explode('(', $tableColumn['type']);
306 156
        $tableColumn['type'] = trim($parts[0]);
307 156
        if (isset($parts[1])) {
308 102
            $length                = trim($parts[1], ')');
309 102
            $tableColumn['length'] = $length;
310
        }
311
312 156
        $dbType   = strtolower($tableColumn['type']);
313 156
        $length   = $tableColumn['length'] ?? null;
314 156
        $unsigned = false;
315
316 156
        if (strpos($dbType, ' unsigned') !== false) {
317 36
            $dbType   = str_replace(' unsigned', '', $dbType);
318 36
            $unsigned = true;
319
        }
320
321 156
        $fixed   = false;
322 156
        $type    = $this->_platform->getDoctrineTypeMapping($dbType);
323 156
        $default = $tableColumn['dflt_value'];
324 156
        if ($default === 'NULL') {
325 102
            $default = null;
326
        }
327
328 156
        if ($default !== null) {
329
            // SQLite returns the default value as a literal expression, so we need to parse it
330 104
            if (preg_match('/^\'(.*)\'$/s', $default, $matches)) {
331 103
                $default = str_replace("''", "'", $matches[1]);
332
            }
333
        }
334
335 156
        $notnull = (bool) $tableColumn['notnull'];
336
337 156
        if (! isset($tableColumn['name'])) {
338
            $tableColumn['name'] = '';
339
        }
340
341 156
        $precision = null;
342 156
        $scale     = null;
343
344 156
        switch ($dbType) {
345 4
            case 'char':
346 70
                $fixed = true;
347 70
                break;
348 4
            case 'float':
349 4
            case 'double':
350 4
            case 'real':
351 4
            case 'decimal':
352 4
            case 'numeric':
353 71
                if (isset($tableColumn['length'])) {
354 71
                    if (strpos($tableColumn['length'], ',') === false) {
355
                        $tableColumn['length'] .= ',0';
356
                    }
357 71
                    [$precision, $scale] = array_map('trim', explode(',', $tableColumn['length']));
358
                }
359 71
                $length = null;
360 71
                break;
361
        }
362
363
        $options = [
364 156
            'length'   => $length,
365 156
            'unsigned' => (bool) $unsigned,
366 156
            'fixed'    => $fixed,
367 156
            'notnull'  => $notnull,
368 156
            'default'  => $default,
369 156
            'precision' => $precision,
370 156
            'scale'     => $scale,
371
            'autoincrement' => false,
372
        ];
373
374 156
        return new Column($tableColumn['name'], Type::getType($type), $options);
375
    }
376
377
    /**
378
     * {@inheritdoc}
379
     */
380 62
    protected function _getPortableViewDefinition($view)
381
    {
382 62
        return new View($view['name'], $view['sql']);
383
    }
384
385
    /**
386
     * {@inheritdoc}
387
     */
388 84
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
389
    {
390 84
        $list = [];
391 84
        foreach ($tableForeignKeys as $value) {
392 84
            $value = array_change_key_case($value, CASE_LOWER);
393 84
            $name  = $value['constraint_name'];
394 84
            if (! isset($list[$name])) {
395 84
                if (! isset($value['on_delete']) || $value['on_delete'] === 'RESTRICT') {
396
                    $value['on_delete'] = null;
397
                }
398 84
                if (! isset($value['on_update']) || $value['on_update'] === 'RESTRICT') {
399
                    $value['on_update'] = null;
400
                }
401
402 84
                $list[$name] = [
403 84
                    'name' => $name,
404
                    'local' => [],
405
                    'foreign' => [],
406 84
                    'foreignTable' => $value['table'],
407 84
                    'onDelete' => $value['on_delete'],
408 84
                    'onUpdate' => $value['on_update'],
409 84
                    'deferrable' => $value['deferrable'],
410 84
                    'deferred'=> $value['deferred'],
411
                ];
412
            }
413 84
            $list[$name]['local'][]   = $value['from'];
414 84
            $list[$name]['foreign'][] = $value['to'];
415
        }
416
417 84
        $result = [];
418 84
        foreach ($list as $constraint) {
419 84
            $result[] = new ForeignKeyConstraint(
420 84
                array_values($constraint['local']),
421 84
                $constraint['foreignTable'],
422 84
                array_values($constraint['foreign']),
423 84
                $constraint['name'],
424
                [
425 84
                    'onDelete' => $constraint['onDelete'],
426 84
                    'onUpdate' => $constraint['onUpdate'],
427 84
                    'deferrable' => $constraint['deferrable'],
428 84
                    'deferred'=> $constraint['deferred'],
429
                ]
430
            );
431
        }
432
433 84
        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 974
    private function parseColumnCollationFromSQL(string $column, string $sql) : ?string
462
    {
463 974
        $pattern = '{(?:\W' . preg_quote($column) . '\W|\W' . preg_quote($this->_platform->quoteSingleIdentifier($column))
464 974
            . '\W)[^,(]+(?:\([^()]+\)[^,]*)?(?:(?:DEFAULT|CHECK)\s*(?:\(.*?\))?[^,]*)*COLLATE\s+["\']?([^\s,"\')]+)}is';
465
466 974
        if (preg_match($pattern, $sql, $match) !== 1) {
467 904
            return null;
468
        }
469
470 945
        return $match[1];
471
    }
472
473 680
    private function parseColumnCommentFromSQL(string $column, string $sql) : ?string
474
    {
475 680
        $pattern = '{[\s(,](?:\W' . preg_quote($this->_platform->quoteSingleIdentifier($column)) . '\W|\W' . preg_quote($column)
476 680
            . '\W)(?:\(.*?\)|[^,(])*?,?((?:(?!\n))(?:\s*--[^\n]*\n?)+)}i';
477
478 680
        if (preg_match($pattern, $sql, $match) !== 1) {
479 658
            return null;
480
        }
481
482 652
        $comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n"));
483
484 652
        return $comment === '' ? null : $comment;
485
    }
486
487 156
    private function getCreateTableSQL(string $table) : ?string
488
    {
489 156
        return $this->_conn->fetchColumn(
490
            <<<'SQL'
491 156
SELECT sql
492
  FROM (
493
      SELECT *
494
        FROM sqlite_master
495
   UNION ALL
496
      SELECT *
497
        FROM sqlite_temp_master
498
  )
499
WHERE type = 'table'
500
AND name = ?
501
SQL
502
            ,
503 156
            [$table]
504 156
        ) ?: null;
505
    }
506
}
507