Failed Conditions
Pull Request — develop (#3581)
by Jonathan
12:44
created

getTableDiffForAlterForeignKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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