Completed
Push — master ( 82fd5d...94ba9d )
by Marco
16s queued 12s
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 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
    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 1
    public function listTableForeignKeys($table, $database = null)
112
    {
113 1
        if ($database === null) {
114 1
            $database = $this->_conn->getDatabase();
115
        }
116 1
        $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 1
        $tableForeignKeys = $this->_conn->fetchAll($sql);
118
119 1
        if (! empty($tableForeignKeys)) {
120 1
            $createSql = $this->getCreateTableSQL($table);
121
122 1
            if ($createSql !== null && preg_match_all(
123 1
                '#
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 1
                $createSql,
133 1
                $match
134
            )) {
135 1
                $names      = array_reverse($match[1]);
136 1
                $deferrable = array_reverse($match[2]);
137 1
                $deferred   = array_reverse($match[3]);
138
            } else {
139
                $names = $deferrable = $deferred = [];
140
            }
141
142 1
            foreach ($tableForeignKeys as $key => $value) {
143 1
                $id                                        = $value['id'];
144 1
                $tableForeignKeys[$key]['constraint_name'] = isset($names[$id]) && $names[$id] !== '' ? $names[$id] : $id;
145 1
                $tableForeignKeys[$key]['deferrable']      = isset($deferrable[$id]) && strtolower($deferrable[$id]) === 'deferrable';
146 1
                $tableForeignKeys[$key]['deferred']        = isset($deferred[$id]) && strtolower($deferred[$id]) === 'deferred';
147
            }
148
        }
149
150 1
        return $this->_getPortableTableForeignKeysList($tableForeignKeys);
151
    }
152
153
    /**
154
     * {@inheritdoc}
155
     */
156 101
    protected function _getPortableTableDefinition($table)
157
    {
158 101
        return $table['name'];
159
    }
160
161
    /**
162
     * {@inheritdoc}
163
     *
164
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
165
     */
166 69
    protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
167
    {
168 69
        $indexBuffer = [];
169
170
        // fetch primary
171 69
        $stmt       = $this->_conn->executeQuery(sprintf(
172 69
            'PRAGMA TABLE_INFO (%s)',
173 69
            $this->_conn->quote($tableName)
174
        ));
175 69
        $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
176
177
        usort($indexArray, static function ($a, $b) {
178 22
            if ($a['pk'] === $b['pk']) {
179 18
                return $a['cid'] - $b['cid'];
180
            }
181
182 12
            return $a['pk'] - $b['pk'];
183 69
        });
184 69
        foreach ($indexArray as $indexColumnRow) {
185 69
            if ($indexColumnRow['pk'] === '0') {
186 22
                continue;
187
            }
188
189 57
            $indexBuffer[] = [
190 57
                'key_name' => 'primary',
191
                'primary' => true,
192
                'non_unique' => false,
193 57
                'column_name' => $indexColumnRow['name'],
194
            ];
195
        }
196
197
        // fetch regular indexes
198 69
        foreach ($tableIndexes as $tableIndex) {
199
            // Ignore indexes with reserved names, e.g. autoindexes
200 8
            if (strpos($tableIndex['name'], 'sqlite_') === 0) {
201 5
                continue;
202
            }
203
204 6
            $keyName           = $tableIndex['name'];
205 6
            $idx               = [];
206 6
            $idx['key_name']   = $keyName;
207 6
            $idx['primary']    = false;
208 6
            $idx['non_unique'] = $tableIndex['unique']?false:true;
209
210 6
                $stmt       = $this->_conn->executeQuery(sprintf(
211 6
                    'PRAGMA INDEX_INFO (%s)',
212 6
                    $this->_conn->quote($keyName)
213
                ));
214 6
                $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
215
216 6
            foreach ($indexArray as $indexColumnRow) {
217 6
                $idx['column_name'] = $indexColumnRow['name'];
218 6
                $indexBuffer[]      = $idx;
219
            }
220
        }
221
222 69
        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 76
    protected function _getPortableTableColumnList($table, $database, $tableColumns)
240
    {
241 76
        $list = parent::_getPortableTableColumnList($table, $database, $tableColumns);
242
243
        // find column with autoincrement
244 76
        $autoincrementColumn = null;
245 76
        $autoincrementCount  = 0;
246
247 76
        foreach ($tableColumns as $tableColumn) {
248 76
            if ($tableColumn['pk'] === '0') {
249 28
                continue;
250
            }
251
252 60
            $autoincrementCount++;
253 60
            if ($autoincrementColumn !== null || strtolower($tableColumn['type']) !== 'integer') {
254 3
                continue;
255
            }
256
257 60
            $autoincrementColumn = $tableColumn['name'];
258
        }
259
260 76
        if ($autoincrementCount === 1 && $autoincrementColumn !== null) {
0 ignored issues
show
introduced by
The condition $autoincrementColumn !== null is always false.
Loading history...
261 59
            foreach ($list as $column) {
262 59
                if ($autoincrementColumn !== $column->getName()) {
263 12
                    continue;
264
                }
265
266 59
                $column->setAutoincrement(true);
267
            }
268
        }
269
270
        // inspect column collation and comments
271 76
        $createSql = $this->getCreateTableSQL($table) ?? '';
272
273 76
        foreach ($list as $columnName => $column) {
274 76
            $type = $column->getType();
275
276 76
            if ($type instanceof StringType || $type instanceof TextType) {
277 16
                $column->setPlatformOption('collation', $this->parseColumnCollationFromSQL($columnName, $createSql) ?: 'BINARY');
278
            }
279
280 76
            $comment = $this->parseColumnCommentFromSQL($columnName, $createSql);
281
282 76
            if ($comment === null) {
283 71
                continue;
284
            }
285
286 16
            $type = $this->extractDoctrineTypeFromComment($comment, null);
287
288 16
            if ($type !== null) {
289 4
                $column->setType(Type::getType($type));
290
291 4
                $comment = $this->removeDoctrineTypeFromComment($comment, $type);
292
            }
293
294 16
            $column->setComment($comment);
295
        }
296
297 76
        return $list;
298
    }
299
300
    /**
301
     * {@inheritdoc}
302
     */
303 76
    protected function _getPortableTableColumnDefinition($tableColumn)
304
    {
305 76
        $parts               = explode('(', $tableColumn['type']);
306 76
        $tableColumn['type'] = trim($parts[0]);
307 76
        if (isset($parts[1])) {
308 12
            $length                = trim($parts[1], ')');
309 12
            $tableColumn['length'] = $length;
310
        }
311
312 76
        $dbType   = strtolower($tableColumn['type']);
313 76
        $length   = $tableColumn['length'] ?? null;
314 76
        $unsigned = false;
315
316 76
        if (strpos($dbType, ' unsigned') !== false) {
317 1
            $dbType   = str_replace(' unsigned', '', $dbType);
318 1
            $unsigned = true;
319
        }
320
321 76
        $fixed   = false;
322 76
        $type    = $this->_platform->getDoctrineTypeMapping($dbType);
323 76
        $default = $tableColumn['dflt_value'];
324 76
        if ($default === 'NULL') {
325 4
            $default = null;
326
        }
327 76
        if ($default !== null) {
328
            // SQLite returns strings wrapped in single quotes, so we need to strip them
329 6
            $default = preg_replace("/^'(.*)'$/", '\1', $default);
330
        }
331 76
        $notnull = (bool) $tableColumn['notnull'];
332
333 76
        if (! isset($tableColumn['name'])) {
334
            $tableColumn['name'] = '';
335
        }
336
337 76
        $precision = null;
338 76
        $scale     = null;
339
340 2
        switch ($dbType) {
341 76
            case 'char':
342 3
                $fixed = true;
343 3
                break;
344 75
            case 'float':
345 75
            case 'double':
346 75
            case 'real':
347 75
            case 'decimal':
348 75
            case 'numeric':
349 4
                if (isset($tableColumn['length'])) {
350 4
                    if (strpos($tableColumn['length'], ',') === false) {
351
                        $tableColumn['length'] .= ',0';
352
                    }
353 4
                    [$precision, $scale] = array_map('trim', explode(',', $tableColumn['length']));
354
                }
355 4
                $length = null;
356 4
                break;
357
        }
358
359
        $options = [
360 76
            'length'   => $length,
361 76
            'unsigned' => (bool) $unsigned,
362 76
            'fixed'    => $fixed,
363 76
            'notnull'  => $notnull,
364 76
            'default'  => $default,
365 76
            'precision' => $precision,
366 76
            'scale'     => $scale,
367
            'autoincrement' => false,
368
        ];
369
370 76
        return new Column($tableColumn['name'], Type::getType($type), $options);
371
    }
372
373
    /**
374
     * {@inheritdoc}
375
     */
376 1
    protected function _getPortableViewDefinition($view)
377
    {
378 1
        return new View($view['name'], $view['sql']);
379
    }
380
381
    /**
382
     * {@inheritdoc}
383
     */
384 1
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
385
    {
386 1
        $list = [];
387 1
        foreach ($tableForeignKeys as $value) {
388 1
            $value = array_change_key_case($value, CASE_LOWER);
389 1
            $name  = $value['constraint_name'];
390 1
            if (! isset($list[$name])) {
391 1
                if (! isset($value['on_delete']) || $value['on_delete'] === 'RESTRICT') {
392
                    $value['on_delete'] = null;
393
                }
394 1
                if (! isset($value['on_update']) || $value['on_update'] === 'RESTRICT') {
395
                    $value['on_update'] = null;
396
                }
397
398 1
                $list[$name] = [
399 1
                    'name' => $name,
400
                    'local' => [],
401
                    'foreign' => [],
402 1
                    'foreignTable' => $value['table'],
403 1
                    'onDelete' => $value['on_delete'],
404 1
                    'onUpdate' => $value['on_update'],
405 1
                    'deferrable' => $value['deferrable'],
406 1
                    'deferred'=> $value['deferred'],
407
                ];
408
            }
409 1
            $list[$name]['local'][]   = $value['from'];
410 1
            $list[$name]['foreign'][] = $value['to'];
411
        }
412
413 1
        $result = [];
414 1
        foreach ($list as $constraint) {
415 1
            $result[] = new ForeignKeyConstraint(
416 1
                array_values($constraint['local']),
417 1
                $constraint['foreignTable'],
418 1
                array_values($constraint['foreign']),
419 1
                $constraint['name'],
420
                [
421 1
                    'onDelete' => $constraint['onDelete'],
422 1
                    'onUpdate' => $constraint['onUpdate'],
423 1
                    'deferrable' => $constraint['deferrable'],
424 1
                    'deferred'=> $constraint['deferred'],
425
                ]
426
            );
427
        }
428
429 1
        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 320
    private function parseColumnCollationFromSQL(string $column, string $sql) : ?string
457
    {
458 320
        $pattern = '{(?:\W' . preg_quote($column) . '\W|\W' . preg_quote($this->_platform->quoteSingleIdentifier($column))
459 320
            . '\W)[^,(]+(?:\([^()]+\)[^,]*)?(?:(?:DEFAULT|CHECK)\s*(?:\(.*?\))?[^,]*)*COLLATE\s+["\']?([^\s,"\')]+)}is';
460
461 320
        if (preg_match($pattern, $sql, $match) !== 1) {
462 111
            return null;
463
        }
464
465 212
        return $match[1];
466
    }
467
468 494
    private function parseColumnCommentFromSQL(string $column, string $sql) : ?string
469
    {
470 494
        $pattern = '{[\s(,](?:\W' . preg_quote($this->_platform->quoteSingleIdentifier($column)) . '\W|\W' . preg_quote($column)
471 494
            . '\W)(?:\(.*?\)|[^,(])*?,?((?:(?!\n))(?:\s*--[^\n]*\n?)+)}i';
472
473 494
        if (preg_match($pattern, $sql, $match) !== 1) {
474 280
            return null;
475
        }
476
477 225
        $comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n"));
478
479 225
        return $comment === '' ? null : $comment;
480
    }
481
482 77
    private function getCreateTableSQL(string $table) : ?string
483
    {
484 77
        return $this->_conn->fetchColumn(
485
            <<<'SQL'
486 77
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 77
            [$table]
499 77
        ) ?: null;
500
    }
501
}
502