Failed Conditions
Push — develop ( c067f0...c4478a )
by Sergei
10:16
created

SqliteSchemaManager::getCreateTableSQL()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 18
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 18
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 1
nop 1
crap 2
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 4
    public function dropDatabase($database)
40
    {
41 4
        if (! file_exists($database)) {
42 2
            return;
43
        }
44
45 4
        unlink($database);
46 4
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51 4
    public function createDatabase($database)
52
    {
53 4
        $params  = $this->_conn->getParams();
54 4
        $driver  = $params['driver'];
55
        $options = [
56 4
            'driver' => $driver,
57 4
            'path' => $database,
58
        ];
59 4
        $conn    = DriverManager::getConnection($options);
60 4
        $conn->connect();
61 4
        $conn->close();
62 4
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67 2
    public function renameTable($name, $newName)
68
    {
69 2
        $tableDiff            = new TableDiff($name);
70 2
        $tableDiff->fromTable = $this->listTableDetails($name);
71 2
        $tableDiff->newName   = $newName;
72 2
        $this->alterTable($tableDiff);
73 2
    }
74
75
    /**
76
     * {@inheritdoc}
77
     */
78
    public function createForeignKey(ForeignKeyConstraint $foreignKey, $table)
79
    {
80
        $tableDiff                     = $this->getTableDiffForAlterForeignKey($foreignKey, $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($foreignKey, $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($foreignKey, $table);
103
        $tableDiff->removedForeignKeys[] = $foreignKey;
104
105
        $this->alterTable($tableDiff);
106
    }
107
108
    /**
109
     * {@inheritdoc}
110
     */
111 2
    public function listTableForeignKeys($table, $database = null)
112
    {
113 2
        if ($database === null) {
114 2
            $database = $this->_conn->getDatabase();
115
        }
116 2
        $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 2
        $tableForeignKeys = $this->_conn->fetchAll($sql);
118
119 2
        if (! empty($tableForeignKeys)) {
120 2
            $createSql = $this->getCreateTableSQL($table);
121
122 2
            if ($createSql !== null && preg_match_all(
123 2
                '#
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 2
                $createSql,
133 2
                $match
134
            )) {
135 2
                $names      = array_reverse($match[1]);
136 2
                $deferrable = array_reverse($match[2]);
137 2
                $deferred   = array_reverse($match[3]);
138
            } else {
139
                $names = $deferrable = $deferred = [];
140
            }
141
142 2
            foreach ($tableForeignKeys as $key => $value) {
143 2
                $id                                        = $value['id'];
144 2
                $tableForeignKeys[$key]['constraint_name'] = isset($names[$id]) && $names[$id] !== '' ? $names[$id] : $id;
145 2
                $tableForeignKeys[$key]['deferrable']      = isset($deferrable[$id]) && strtolower($deferrable[$id]) === 'deferrable';
146 2
                $tableForeignKeys[$key]['deferred']        = isset($deferred[$id]) && strtolower($deferred[$id]) === 'deferred';
147
            }
148
        }
149
150 2
        return $this->_getPortableTableForeignKeysList($tableForeignKeys);
151
    }
152
153
    /**
154
     * {@inheritdoc}
155
     */
156 164
    protected function _getPortableTableDefinition($table)
157
    {
158 164
        return $table['name'];
159
    }
160
161
    /**
162
     * {@inheritdoc}
163
     *
164
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
165
     */
166 100
    protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
167
    {
168 100
        $indexBuffer = [];
169
170
        // fetch primary
171 100
        $stmt       = $this->_conn->executeQuery(sprintf(
172 100
            'PRAGMA TABLE_INFO (%s)',
173 100
            $this->_conn->quote($tableName)
174
        ));
175 100
        $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
176
177
        usort($indexArray, static function ($a, $b) {
178 44
            if ($a['pk'] === $b['pk']) {
179 36
                return $a['cid'] - $b['cid'];
180
            }
181
182 24
            return $a['pk'] - $b['pk'];
183 100
        });
184 100
        foreach ($indexArray as $indexColumnRow) {
185 100
            if ($indexColumnRow['pk'] === '0') {
186 44
                continue;
187
            }
188
189 76
            $indexBuffer[] = [
190 76
                'key_name' => 'primary',
191
                'primary' => true,
192
                'non_unique' => false,
193 76
                'column_name' => $indexColumnRow['name'],
194
            ];
195
        }
196
197
        // fetch regular indexes
198 100
        foreach ($tableIndexes as $tableIndex) {
199
            // Ignore indexes with reserved names, e.g. autoindexes
200 16
            if (strpos($tableIndex['name'], 'sqlite_') === 0) {
201 10
                continue;
202
            }
203
204 12
            $keyName           = $tableIndex['name'];
205 12
            $idx               = [];
206 12
            $idx['key_name']   = $keyName;
207 12
            $idx['primary']    = false;
208 12
            $idx['non_unique'] = $tableIndex['unique']?false:true;
209
210 12
                $stmt       = $this->_conn->executeQuery(sprintf(
211 12
                    'PRAGMA INDEX_INFO (%s)',
212 12
                    $this->_conn->quote($keyName)
213
                ));
214 12
                $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
215
216 12
            foreach ($indexArray as $indexColumnRow) {
217 12
                $idx['column_name'] = $indexColumnRow['name'];
218 12
                $indexBuffer[]      = $idx;
219
            }
220
        }
221
222 100
        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 114
    protected function _getPortableTableColumnList($table, $database, $tableColumns)
240
    {
241 114
        $list = parent::_getPortableTableColumnList($table, $database, $tableColumns);
242
243
        // find column with autoincrement
244 114
        $autoincrementColumn = null;
245 114
        $autoincrementCount  = 0;
246
247 114
        foreach ($tableColumns as $tableColumn) {
248 114
            if ($tableColumn['pk'] === '0') {
249 56
                continue;
250
            }
251
252 82
            $autoincrementCount++;
253 82
            if ($autoincrementColumn !== null || strtolower($tableColumn['type']) !== 'integer') {
254 6
                continue;
255
            }
256
257 82
            $autoincrementColumn = $tableColumn['name'];
258
        }
259
260 114
        if ($autoincrementCount === 1 && $autoincrementColumn !== null) {
0 ignored issues
show
introduced by
The condition $autoincrementColumn !== null is always false.
Loading history...
261 80
            foreach ($list as $column) {
262 80
                if ($autoincrementColumn !== $column->getName()) {
263 24
                    continue;
264
                }
265
266 80
                $column->setAutoincrement(true);
267
            }
268
        }
269
270
        // inspect column collation and comments
271 114
        $createSql = $this->getCreateTableSQL($table) ?? '';
272
273 114
        foreach ($list as $columnName => $column) {
274 114
            $type = $column->getType();
275
276 114
            if ($type instanceof StringType || $type instanceof TextType) {
277 32
                $column->setPlatformOption('collation', $this->parseColumnCollationFromSQL($columnName, $createSql) ?: 'BINARY');
278
            }
279
280 114
            $comment = $this->parseColumnCommentFromSQL($columnName, $createSql);
281
282 114
            if ($comment === null) {
283 104
                continue;
284
            }
285
286 32
            $type = $this->extractDoctrineTypeFromComment($comment, null);
287
288 32
            if ($type !== null) {
289 8
                $column->setType(Type::getType($type));
290
291 8
                $comment = $this->removeDoctrineTypeFromComment($comment, $type);
292
            }
293
294 32
            $column->setComment($comment);
295
        }
296
297 114
        return $list;
298
    }
299
300
    /**
301
     * {@inheritdoc}
302
     */
303 114
    protected function _getPortableTableColumnDefinition($tableColumn)
304
    {
305 114
        $parts               = explode('(', $tableColumn['type']);
306 114
        $tableColumn['type'] = trim($parts[0]);
307 114
        if (isset($parts[1])) {
308 24
            $length                = trim($parts[1], ')');
309 24
            $tableColumn['length'] = $length;
310
        }
311
312 114
        $dbType   = strtolower($tableColumn['type']);
313 114
        $length   = $tableColumn['length'] ?? null;
314 114
        $unsigned = false;
315
316 114
        if (strpos($dbType, ' unsigned') !== false) {
317 2
            $dbType   = str_replace(' unsigned', '', $dbType);
318 2
            $unsigned = true;
319
        }
320
321 114
        $fixed   = false;
322 114
        $type    = $this->_platform->getDoctrineTypeMapping($dbType);
323 114
        $default = $tableColumn['dflt_value'];
324 114
        if ($default === 'NULL') {
325 8
            $default = null;
326
        }
327 114
        if ($default !== null) {
328
            // SQLite returns strings wrapped in single quotes, so we need to strip them
329 12
            $default = preg_replace("/^'(.*)'$/", '\1', $default);
330
        }
331 114
        $notnull = (bool) $tableColumn['notnull'];
332
333 114
        if (! isset($tableColumn['name'])) {
334
            $tableColumn['name'] = '';
335
        }
336
337 114
        $precision = null;
338 114
        $scale     = null;
339
340 114
        switch ($dbType) {
341 114
            case 'char':
342 6
                $fixed = true;
343 6
                break;
344 112
            case 'float':
345 112
            case 'double':
346 112
            case 'real':
347 112
            case 'decimal':
348 112
            case 'numeric':
349 8
                if (isset($tableColumn['length'])) {
350 8
                    if (strpos($tableColumn['length'], ',') === false) {
351
                        $tableColumn['length'] .= ',0';
352
                    }
353 8
                    [$precision, $scale] = array_map('trim', explode(',', $tableColumn['length']));
354
                }
355 8
                $length = null;
356 8
                break;
357
        }
358
359
        $options = [
360 114
            'length'   => $length,
361 114
            'unsigned' => (bool) $unsigned,
362 114
            'fixed'    => $fixed,
363 114
            'notnull'  => $notnull,
364 114
            'default'  => $default,
365 114
            'precision' => $precision,
366 114
            'scale'     => $scale,
367
            'autoincrement' => false,
368
        ];
369
370 114
        return new Column($tableColumn['name'], Type::getType($type), $options);
371
    }
372
373
    /**
374
     * {@inheritdoc}
375
     */
376 2
    protected function _getPortableViewDefinition($view)
377
    {
378 2
        return new View($view['name'], $view['sql']);
379
    }
380
381
    /**
382
     * {@inheritdoc}
383
     */
384 2
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
385
    {
386 2
        $list = [];
387 2
        foreach ($tableForeignKeys as $value) {
388 2
            $value = array_change_key_case($value, CASE_LOWER);
389 2
            $name  = $value['constraint_name'];
390 2
            if (! isset($list[$name])) {
391 2
                if (! isset($value['on_delete']) || $value['on_delete'] === 'RESTRICT') {
392
                    $value['on_delete'] = null;
393
                }
394 2
                if (! isset($value['on_update']) || $value['on_update'] === 'RESTRICT') {
395
                    $value['on_update'] = null;
396
                }
397
398 2
                $list[$name] = [
399 2
                    'name' => $name,
400
                    'local' => [],
401
                    'foreign' => [],
402 2
                    'foreignTable' => $value['table'],
403 2
                    'onDelete' => $value['on_delete'],
404 2
                    'onUpdate' => $value['on_update'],
405 2
                    'deferrable' => $value['deferrable'],
406 2
                    'deferred'=> $value['deferred'],
407
                ];
408
            }
409 2
            $list[$name]['local'][]   = $value['from'];
410 2
            $list[$name]['foreign'][] = $value['to'];
411
        }
412
413 2
        $result = [];
414 2
        foreach ($list as $constraint) {
415 2
            $result[] = new ForeignKeyConstraint(
416 2
                array_values($constraint['local']),
417 2
                $constraint['foreignTable'],
418 2
                array_values($constraint['foreign']),
419 2
                $constraint['name'],
420
                [
421 2
                    'onDelete' => $constraint['onDelete'],
422 2
                    'onUpdate' => $constraint['onUpdate'],
423 2
                    'deferrable' => $constraint['deferrable'],
424 2
                    'deferred'=> $constraint['deferred'],
425
                ]
426
            );
427
        }
428
429 2
        return $result;
430
    }
431
432
    /**
433
     * @param Table|string $table
434
     *
435
     * @return TableDiff
436
     *
437
     * @throws DBALException
438
     */
439
    private function getTableDiffForAlterForeignKey(ForeignKeyConstraint $foreignKey, $table)
0 ignored issues
show
Unused Code introduced by
The parameter $foreignKey is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

439
    private function getTableDiffForAlterForeignKey(/** @scrutinizer ignore-unused */ ForeignKeyConstraint $foreignKey, $table)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
440
    {
441
        if (! $table instanceof Table) {
442
            $tableDetails = $this->tryMethod('listTableDetails', $table);
443
            if ($table === false) {
0 ignored issues
show
introduced by
The condition $table === false is always false.
Loading history...
444
                throw new DBALException(sprintf('Sqlite schema manager requires to modify foreign keys table definition "%s".', $table));
445
            }
446
447
            $table = $tableDetails;
448
        }
449
450
        $tableDiff            = new TableDiff($table->getName());
451
        $tableDiff->fromTable = $table;
0 ignored issues
show
Documentation Bug introduced by
It seems like $table can also be of type false. However, the property $fromTable is declared as type Doctrine\DBAL\Schema\Table. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
452
453
        return $tableDiff;
454
    }
455
456 336
    private function parseColumnCollationFromSQL(string $column, string $sql) : ?string
457
    {
458 336
        $pattern = '{(?:\W' . preg_quote($column) . '\W|\W' . preg_quote($this->_platform->quoteSingleIdentifier($column))
459 336
            . '\W)[^,(]+(?:\([^()]+\)[^,]*)?(?:(?:DEFAULT|CHECK)\s*(?:\(.*?\))?[^,]*)*COLLATE\s+["\']?([^\s,"\')]+)}is';
460
461 336
        if (preg_match($pattern, $sql, $match) !== 1) {
462 127
            return null;
463
        }
464
465 215
        return $match[1];
466
    }
467
468 532
    private function parseColumnCommentFromSQL(string $column, string $sql) : ?string
469
    {
470 532
        $pattern = '{[\s(,](?:\W' . preg_quote($this->_platform->quoteSingleIdentifier($column)) . '\W|\W' . preg_quote($column)
471 532
            . '\W)(?:\(.*?\)|[^,(])*?,?((?:(?!\n))(?:\s*--[^\n]*\n?)+)}i';
472
473 532
        if (preg_match($pattern, $sql, $match) !== 1) {
474 313
            return null;
475
        }
476
477 241
        $comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n"));
478
479 241
        return $comment === '' ? null : $comment;
480
    }
481
482 116
    private function getCreateTableSQL(string $table) : ?string
483
    {
484 116
        return $this->_conn->fetchColumn(
485
            <<<'SQL'
486 116
SELECT sql
487
  FROM (
488
      SELECT *
489
        FROM sqlite_master
490
   UNION ALL
491
      SELECT *
492
        FROM sqlite_temp_master
493
  )
494
WHERE type = 'table'
495
AND name = ?
496
SQL
497
            ,
498 116
            [$table]
499 116
        ) ?: null;
500
    }
501
}
502