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