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