Failed Conditions
Pull Request — develop (#3348)
by Sergei
10:40
created

SqliteSchemaManager::dropDatabase()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\DBAL\Schema;
6
7
use Doctrine\DBAL\DBALException;
8
use Doctrine\DBAL\DriverManager;
9
use Doctrine\DBAL\FetchMode;
10
use Doctrine\DBAL\Types\StringType;
11
use Doctrine\DBAL\Types\TextType;
12
use Doctrine\DBAL\Types\Type;
13
use const CASE_LOWER;
14
use function array_change_key_case;
15
use function array_reverse;
16
use function array_values;
17
use function count;
18
use function file_exists;
19
use function preg_match;
20
use function preg_match_all;
21
use function preg_quote;
22
use function preg_replace;
23
use function rtrim;
24
use function sprintf;
25
use function strpos;
26
use function strtolower;
27
use function unlink;
28
use function usort;
29
30
/**
31
 * Sqlite SchemaManager.
32
 */
33
class SqliteSchemaManager extends AbstractSchemaManager
34
{
35
    /**
36
     * {@inheritdoc}
37
     */
38 86
    public function dropDatabase(string $database) : void
39
    {
40 86
        if (! file_exists($database)) {
41 85
            return;
42
        }
43
44 86
        unlink($database);
45 86
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50 86
    public function createDatabase(string $database) : void
51
    {
52 86
        $params  = $this->_conn->getParams();
53 86
        $driver  = $params['driver'];
54
        $options = [
55 86
            'driver' => $driver,
56 86
            'path' => $database,
57
        ];
58 86
        $conn    = DriverManager::getConnection($options);
59 86
        $conn->connect();
60 86
        $conn->close();
61 86
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66 84
    public function renameTable(string $name, string $newName) : void
67
    {
68 84
        $tableDiff            = new TableDiff($name);
69 84
        $tableDiff->fromTable = $this->listTableDetails($name);
70 84
        $tableDiff->newName   = $newName;
71 84
        $this->alterTable($tableDiff);
72 84
    }
73
74
    /**
75
     * {@inheritdoc}
76
     */
77
    public function createForeignKey(ForeignKeyConstraint $foreignKey, $table) : void
78
    {
79
        $tableDiff                     = $this->getTableDiffForAlterForeignKey($table);
80
        $tableDiff->addedForeignKeys[] = $foreignKey;
81
82
        $this->alterTable($tableDiff);
83
    }
84
85
    /**
86
     * {@inheritdoc}
87
     */
88
    public function dropAndCreateForeignKey(ForeignKeyConstraint $foreignKey, $table) : void
89
    {
90
        $tableDiff                       = $this->getTableDiffForAlterForeignKey($table);
91
        $tableDiff->changedForeignKeys[] = $foreignKey;
92
93
        $this->alterTable($tableDiff);
94
    }
95
96
    /**
97
     * {@inheritdoc}
98
     */
99
    public function dropForeignKey($foreignKey, $table) : void
100
    {
101
        $tableDiff                       = $this->getTableDiffForAlterForeignKey($table);
102
        $tableDiff->removedForeignKeys[] = $foreignKey;
103
104
        $this->alterTable($tableDiff);
105
    }
106
107
    /**
108
     * {@inheritdoc}
109
     */
110 83
    public function listTableForeignKeys(string $table, ?string $database = null) : array
111
    {
112 83
        if ($database === null) {
113 83
            $database = $this->_conn->getDatabase();
114
        }
115 83
        $sql              = $this->_platform->getListTableForeignKeysSQL($table, $database);
116 83
        $tableForeignKeys = $this->_conn->fetchAll($sql);
117
118 83
        if (! empty($tableForeignKeys)) {
119 83
            $createSql = $this->getCreateTableSQL($table);
120
121 83
            if ($createSql !== null && preg_match_all(
122
                '#
123
                    (?:CONSTRAINT\s+([^\s]+)\s+)?
124
                    (?:FOREIGN\s+KEY[^\)]+\)\s*)?
125
                    REFERENCES\s+[^\s]+\s+(?:\([^\)]+\))?
126
                    (?:
127
                        [^,]*?
128
                        (NOT\s+DEFERRABLE|DEFERRABLE)
129
                        (?:\s+INITIALLY\s+(DEFERRED|IMMEDIATE))?
130
                    )?#isx',
131 83
                $createSql,
132 83
                $match
133
            )) {
134 83
                $names      = array_reverse($match[1]);
135 83
                $deferrable = array_reverse($match[2]);
136 83
                $deferred   = array_reverse($match[3]);
137
            } else {
138
                $names = $deferrable = $deferred = [];
139
            }
140
141 83
            foreach ($tableForeignKeys as $key => $value) {
142 83
                $id                                        = $value['id'];
143 83
                $tableForeignKeys[$key]['constraint_name'] = isset($names[$id]) && $names[$id] !== '' ? $names[$id] : $id;
144 83
                $tableForeignKeys[$key]['deferrable']      = isset($deferrable[$id]) && strtolower($deferrable[$id]) === 'deferrable';
145 83
                $tableForeignKeys[$key]['deferred']        = isset($deferred[$id]) && strtolower($deferred[$id]) === 'deferred';
146
            }
147
        }
148
149 83
        return $this->_getPortableTableForeignKeysList($tableForeignKeys);
150
    }
151
152
    /**
153
     * {@inheritdoc}
154
     */
155 148
    protected function _getPortableTableDefinition($table) : string
156
    {
157 148
        return $table['name'];
158
    }
159
160
    /**
161
     * {@inheritdoc}
162
     *
163
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
164
     */
165 141
    protected function _getPortableTableIndexesList(array $tableIndexRows, string $tableName) : array
166
    {
167 141
        $indexBuffer = [];
168
169
        // fetch primary
170 141
        $stmt       = $this->_conn->executeQuery(sprintf(
171 2
            'PRAGMA TABLE_INFO (%s)',
172 141
            $this->_conn->quote($tableName)
173
        ));
174 141
        $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
175
176
        usort($indexArray, static function ($a, $b) {
177 84
            if ($a['pk'] === $b['pk']) {
178 84
                return $a['cid'] - $b['cid'];
179
            }
180
181 84
            return $a['pk'] - $b['pk'];
182 141
        });
183 141
        foreach ($indexArray as $indexColumnRow) {
184 141
            if ($indexColumnRow['pk'] === '0') {
185 89
                continue;
186
            }
187
188 136
            $indexBuffer[] = [
189 136
                'key_name' => 'primary',
190
                'primary' => true,
191
                'non_unique' => false,
192 136
                'column_name' => $indexColumnRow['name'],
193
            ];
194
        }
195
196
        // fetch regular indexes
197 141
        foreach ($tableIndexRows as $tableIndex) {
198
            // Ignore indexes with reserved names, e.g. autoindexes
199 80
            if (strpos($tableIndex['name'], 'sqlite_') === 0) {
200 80
                continue;
201
            }
202
203 71
            $keyName           = $tableIndex['name'];
204 71
            $idx               = [];
205 71
            $idx['key_name']   = $keyName;
206 71
            $idx['primary']    = false;
207 71
            $idx['non_unique'] = ! $tableIndex['unique'];
208
209 71
                $stmt       = $this->_conn->executeQuery(sprintf(
210
                    'PRAGMA INDEX_INFO (%s)',
211 71
                    $this->_conn->quote($keyName)
212
                ));
213 71
                $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
214
215 71
            foreach ($indexArray as $indexColumnRow) {
216 71
                $idx['column_name'] = $indexColumnRow['name'];
217 71
                $indexBuffer[]      = $idx;
218
            }
219
        }
220
221 141
        return parent::_getPortableTableIndexesList($indexBuffer, $tableName);
222
    }
223
224
    /**
225
     * {@inheritdoc}
226
     */
227
    protected function _getPortableTableIndexDefinition($tableIndex) : array
228
    {
229
        return [
230
            'name' => $tableIndex['name'],
231
            'unique' => (bool) $tableIndex['unique'],
232
        ];
233
    }
234
235
    /**
236
     * {@inheritdoc}
237
     */
238 141
    protected function _getPortableTableColumnList(string $table, ?string $database, array $tableColumns) : array
239
    {
240 141
        $list = parent::_getPortableTableColumnList($table, $database, $tableColumns);
241
242
        // find column with autoincrement
243 141
        $autoincrementColumn = null;
244 141
        $autoincrementCount  = 0;
245
246 141
        foreach ($tableColumns as $tableColumn) {
247 141
            if ($tableColumn['pk'] === '0') {
248 89
                continue;
249
            }
250
251 136
            $autoincrementCount++;
252 136
            if ($autoincrementColumn !== null || strtolower($tableColumn['type']) !== 'integer') {
253 71
                continue;
254
            }
255
256 136
            $autoincrementColumn = $tableColumn['name'];
257
        }
258
259 141
        if ($autoincrementCount === 1 && $autoincrementColumn !== null) {
0 ignored issues
show
introduced by
The condition $autoincrementColumn !== null is always false.
Loading history...
260 136
            foreach ($list as $column) {
261 136
                if ($autoincrementColumn !== $column->getName()) {
262 84
                    continue;
263
                }
264
265 136
                $column->setAutoincrement(true);
266
            }
267
        }
268
269
        // inspect column collation and comments
270 141
        $createSql = $this->getCreateTableSQL($table) ?? '';
271
272 141
        foreach ($list as $columnName => $column) {
273 141
            $type = $column->getType();
274
275 141
            if ($type instanceof StringType || $type instanceof TextType) {
276 84
                $column->setPlatformOption('collation', $this->parseColumnCollationFromSQL($columnName, $createSql) ?: 'BINARY');
277
            }
278
279 141
            $comment = $this->parseColumnCommentFromSQL($columnName, $createSql);
280
281 141
            $type = $this->extractDoctrineTypeFromComment($comment);
282
283 141
            if ($type !== null) {
284 57
                $column->setType(Type::getType($type));
285
            }
286
287 141
            $column->setComment($comment);
288
        }
289
290 141
        return $list;
291
    }
292
293
    /**
294
     * {@inheritdoc}
295
     */
296 141
    protected function _getPortableTableColumnDefinition(array $tableColumn) : Column
297
    {
298 141
        preg_match('/^([^\\s()]*)\\s*(\\(((\\d+)(,\\s*(\\d+))?)\\))?/', $tableColumn['type'], $matches);
299
300 141
        $dbType = strtolower($matches[1]);
301
302 141
        $length = $precision = $scale = $unsigned = $fixed = null;
303
304 141
        if (count($matches) >= 6) {
305 70
            $precision = (int) $matches[4];
306 70
            $scale     = (int) $matches[6];
307 141
        } elseif (count($matches) >= 4) {
308 84
            $length = (int) $matches[4];
309
        }
310
311 141
        if (strpos($tableColumn['type'], ' UNSIGNED') !== false) {
312 36
            $unsigned = true;
313
        }
314
315 141
        $type    = $this->_platform->getDoctrineTypeMapping($dbType);
316 141
        $default = $tableColumn['dflt_value'];
317 141
        if ($default === 'NULL') {
318 70
            $default = null;
319
        }
320 141
        if ($default !== null) {
321
            // SQLite returns strings wrapped in single quotes, so we need to strip them
322 89
            $default = preg_replace("/^'(.*)'$/", '\1', $default);
323
        }
324 141
        $notnull = (bool) $tableColumn['notnull'];
325
326 141
        if (! isset($tableColumn['name'])) {
327
            $tableColumn['name'] = '';
328
        }
329
330 141
        if ($dbType === 'char') {
331 69
            $fixed = true;
332
        }
333
334
        $options = [
335 141
            'length'   => $length,
336 141
            'notnull'  => $notnull,
337 141
            'default'  => $default,
338 141
            'precision' => $precision,
339 141
            'scale'     => $scale,
340
            'autoincrement' => false,
341
        ];
342
343 141
        if ($unsigned !== null) {
344 36
            $options['unsigned'] = $unsigned;
345
        }
346
347 141
        if ($fixed !== null) {
348 69
            $options['fixed'] = $fixed;
349
        }
350
351 141
        return new Column($tableColumn['name'], Type::getType($type), $options);
352
    }
353
354
    /**
355
     * {@inheritdoc}
356
     */
357 61
    protected function _getPortableViewDefinition(array $view) : View
358
    {
359 61
        return new View($view['name'], $view['sql']);
360
    }
361
362
    /**
363
     * {@inheritdoc}
364
     */
365 83
    protected function _getPortableTableForeignKeysList(array $tableForeignKeys) : array
366
    {
367 83
        $list = [];
368 83
        foreach ($tableForeignKeys as $value) {
369 83
            $value = array_change_key_case($value, CASE_LOWER);
370 83
            $name  = $value['constraint_name'];
371 83
            if (! isset($list[$name])) {
372 83
                if (! isset($value['on_delete']) || $value['on_delete'] === 'RESTRICT') {
373
                    $value['on_delete'] = null;
374
                }
375 83
                if (! isset($value['on_update']) || $value['on_update'] === 'RESTRICT') {
376
                    $value['on_update'] = null;
377
                }
378
379 83
                $list[$name] = [
380 83
                    'name' => $name,
381
                    'local' => [],
382
                    'foreign' => [],
383 83
                    'foreignTable' => $value['table'],
384 83
                    'onDelete' => $value['on_delete'],
385 83
                    'onUpdate' => $value['on_update'],
386 83
                    'deferrable' => $value['deferrable'],
387 83
                    'deferred'=> $value['deferred'],
388
                ];
389
            }
390 83
            $list[$name]['local'][] = $value['from'];
391
392 83
            if ($value['to'] === null) {
393 83
                continue;
394
            }
395
396 83
            $list[$name]['foreign'][] = $value['to'];
397
        }
398
399 83
        $result = [];
400 83
        foreach ($list as $constraint) {
401 83
            $result[] = new ForeignKeyConstraint(
402 83
                array_values($constraint['local']),
403 83
                $constraint['foreignTable'],
404 83
                array_values($constraint['foreign']),
405 83
                $constraint['name'],
406
                [
407 83
                    'onDelete' => $constraint['onDelete'],
408 83
                    'onUpdate' => $constraint['onUpdate'],
409 83
                    'deferrable' => $constraint['deferrable'],
410 83
                    'deferred'=> $constraint['deferred'],
411
                ]
412
            );
413
        }
414
415 83
        return $result;
416
    }
417
418
    /**
419
     * @param Table|string $table
420
     *
421
     * @throws DBALException
422
     */
423
    private function getTableDiffForAlterForeignKey($table) : TableDiff
424
    {
425
        if (! $table instanceof Table) {
426
            $tableDetails = $this->tryMethod('listTableDetails', $table);
427
428
            if ($tableDetails === false) {
429
                throw new DBALException(sprintf('Sqlite schema manager requires to modify foreign keys table definition "%s".', $table));
430
            }
431
432
            $table = $tableDetails;
433
        }
434
435
        $tableDiff            = new TableDiff($table->getName());
436
        $tableDiff->fromTable = $table;
437
438
        return $tableDiff;
439
    }
440
441 975
    private function parseColumnCollationFromSQL(string $column, string $sql) : ?string
442
    {
443 975
        $pattern = '{(?:\W' . preg_quote($column) . '\W|\W' . preg_quote($this->_platform->quoteSingleIdentifier($column))
444 975
            . '\W)[^,(]+(?:\([^()]+\)[^,]*)?(?:(?:DEFAULT|CHECK)\s*(?:\(.*?\))?[^,]*)*COLLATE\s+["\']?([^\s,"\')]+)}is';
445
446 975
        if (preg_match($pattern, $sql, $match) !== 1) {
447 914
            return null;
448
        }
449
450 968
        return $match[1];
451
    }
452
453 663
    private function parseColumnCommentFromSQL(string $column, string $sql) : ?string
454
    {
455 663
        $pattern = '{[\s(,](?:\W' . preg_quote($this->_platform->quoteSingleIdentifier($column)) . '\W|\W' . preg_quote($column)
456 663
            . '\W)(?:\(.*?\)|[^,(])*?,?((?:(?!\n))(?:\s*--[^\n]*\n?)+)}i';
457
458 663
        if (preg_match($pattern, $sql, $match) !== 1) {
459 652
            return null;
460
        }
461
462 619
        $comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n"));
463
464 619
        return $comment === '' ? null : $comment;
465
    }
466
467 141
    private function getCreateTableSQL(string $table) : ?string
468
    {
469 141
        return $this->_conn->fetchColumn(
470
            <<<'SQL'
471 141
SELECT sql
472
  FROM (
473
      SELECT *
474
        FROM sqlite_master
475
   UNION ALL
476
      SELECT *
477
        FROM sqlite_temp_master
478
  )
479
WHERE type = 'table'
480
AND name = ?
481
SQL
482
            ,
483 141
            [$table]
484 141
        ) ?: null;
485
    }
486
}
487