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