Passed
Pull Request — develop (#3565)
by Jonathan
10:02
created

_getPortableTableIndexDefinition()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
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 5
ccs 0
cts 3
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\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($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($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($table, $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 156
    protected function _getPortableTableDefinition(array $table) : string
158
    {
159 156
        return $table['name'];
160
    }
161
162
    /**
163
     * {@inheritdoc}
164
     *
165
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
166
     */
167 149
    protected function _getPortableTableIndexesList(array $tableIndexRows, string $tableName) : array
168
    {
169 149
        $indexBuffer = [];
170
171
        // fetch primary
172 149
        $stmt       = $this->_conn->executeQuery(sprintf(
173 2
            'PRAGMA TABLE_INFO (%s)',
174 149
            $this->_conn->quote($tableName)
175
        ));
176 149
        $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
177
178
        usort($indexArray, static function ($a, $b) {
179 93
            if ($a['pk'] === $b['pk']) {
180 93
                return $a['cid'] - $b['cid'];
181
            }
182
183 76
            return $a['pk'] - $b['pk'];
184 149
        });
185 149
        foreach ($indexArray as $indexColumnRow) {
186 149
            if ($indexColumnRow['pk'] === '0') {
187 95
                continue;
188
            }
189
190 130
            $indexBuffer[] = [
191 130
                'key_name' => 'primary',
192
                'primary' => true,
193
                'non_unique' => false,
194 130
                'column_name' => $indexColumnRow['name'],
195
            ];
196
        }
197
198
        // fetch regular indexes
199 149
        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 149
        return parent::_getPortableTableIndexesList($indexBuffer, $tableName);
224
    }
225
226
    /**
227
     * {@inheritdoc}
228
     */
229
    protected function _getPortableTableIndexDefinition($tableIndex)
230
    {
231
        return [
232
            'name' => $tableIndex['name'],
233
            'unique' => (bool) $tableIndex['unique'],
234
        ];
235
    }
236
237
    /**
238
     * {@inheritdoc}
239
     */
240 149
    protected function _getPortableTableColumnList($table, $database, $tableColumns) : array
241
    {
242 149
        $list = parent::_getPortableTableColumnList($table, $database, $tableColumns);
243
244
        // find column with autoincrement
245 149
        $autoincrementColumn = null;
246 149
        $autoincrementCount  = 0;
247
248 149
        foreach ($tableColumns as $tableColumn) {
249 149
            if ($tableColumn['pk'] === '0') {
250 95
                continue;
251
            }
252
253 130
            $autoincrementCount++;
254 130
            if ($autoincrementColumn !== null || strtolower($tableColumn['type']) !== 'integer') {
255 64
                continue;
256
            }
257
258 130
            $autoincrementColumn = $tableColumn['name'];
259
        }
260
261 149
        if ($autoincrementCount === 1 && $autoincrementColumn !== null) {
0 ignored issues
show
introduced by
The condition $autoincrementColumn !== null is always false.
Loading history...
262 130
            foreach ($list as $column) {
263 130
                if ($autoincrementColumn !== $column->getName()) {
264 76
                    continue;
265
                }
266
267 130
                $column->setAutoincrement(true);
268
            }
269
        }
270
271
        // inspect column collation and comments
272 149
        $createSql = $this->getCreateTableSQL($table) ?? '';
273
274 149
        foreach ($list as $columnName => $column) {
275 149
            $type = $column->getType();
276
277 149
            if ($type instanceof StringType || $type instanceof TextType) {
278 93
                $column->setPlatformOption('collation', $this->parseColumnCollationFromSQL($columnName, $createSql) ?: 'BINARY');
279
            }
280
281 149
            $comment = $this->parseColumnCommentFromSQL($columnName, $createSql);
282
283 149
            $type = $this->extractDoctrineTypeFromComment($comment);
284
285 149
            if ($type !== null) {
286 50
                $column->setType(Type::getType($type));
287
            }
288
289 149
            $column->setComment($comment);
290
        }
291
292 149
        return $list;
293
    }
294
295
    /**
296
     * {@inheritdoc}
297
     */
298 149
    protected function _getPortableTableColumnDefinition($tableColumn) : Column
299
    {
300 149
        preg_match('/^([^()]*)\\s*(\\(((\\d+)(,\\s*(\\d+))?)\\))?/', $tableColumn['type'], $matches);
301
302 149
        $dbType = trim(strtolower($matches[1]));
303
304 149
        $length = $precision = $unsigned = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $unsigned is dead and can be removed.
Loading history...
305 149
        $fixed  = $unsigned = false;
306 149
        $scale  = 0;
307
308 149
        if (count($matches) >= 6) {
309 63
            $precision = (int) $matches[4];
310 63
            $scale     = (int) $matches[6];
311 149
        } elseif (count($matches) >= 4) {
312 93
            $length = (int) $matches[4];
313
        }
314
315 149
        if (strpos($dbType, ' unsigned') !== false) {
316 36
            $dbType   = str_replace(' unsigned', '', $dbType);
317 36
            $unsigned = true;
318
        }
319
320 149
        $type    = $this->_platform->getDoctrineTypeMapping($dbType);
321 149
        $default = $tableColumn['dflt_value'];
322 149
        if ($default === 'NULL') {
323 93
            $default = null;
324
        }
325
326 149
        if ($default !== null) {
327
            // SQLite returns the default value as a literal expression, so we need to parse it
328 95
            if (preg_match('/^\'(.*)\'$/s', $default, $matches)) {
329 94
                $default = str_replace("''", "'", $matches[1]);
330
            }
331
        }
332
333 149
        $notnull = (bool) $tableColumn['notnull'];
334
335 149
        if (! isset($tableColumn['name'])) {
336
            $tableColumn['name'] = '';
337
        }
338
339 149
        if ($dbType === 'char') {
340 62
            $fixed = true;
341
        }
342
343
        $options = [
344 149
            'length'   => $length,
345 149
            'unsigned' => $unsigned,
346 149
            'fixed'    => $fixed,
347 149
            'notnull'  => $notnull,
348 149
            'default'  => $default,
349 149
            'precision' => $precision,
350 149
            'scale'     => $scale,
351
            'autoincrement' => false,
352
        ];
353
354 149
        return new Column($tableColumn['name'], Type::getType($type), $options);
355
    }
356
357
    /**
358
     * {@inheritdoc}
359
     */
360 54
    protected function _getPortableViewDefinition(array $view) : ?View
361
    {
362 54
        return new View($view['name'], $view['sql']);
363
    }
364
365
    /**
366
     * {@inheritdoc}
367
     */
368 75
    protected function _getPortableTableForeignKeysList(array $tableForeignKeys) : array
369
    {
370 75
        $list = [];
371 75
        foreach ($tableForeignKeys as $value) {
372 75
            $value = array_change_key_case($value, CASE_LOWER);
373 75
            $name  = $value['constraint_name'];
374 75
            if (! isset($list[$name])) {
375 75
                if (! isset($value['on_delete']) || $value['on_delete'] === 'RESTRICT') {
376
                    $value['on_delete'] = null;
377
                }
378 75
                if (! isset($value['on_update']) || $value['on_update'] === 'RESTRICT') {
379
                    $value['on_update'] = null;
380
                }
381
382 75
                $list[$name] = [
383 75
                    'name' => $name,
384
                    'local' => [],
385
                    'foreign' => [],
386 75
                    'foreignTable' => $value['table'],
387 75
                    'onDelete' => $value['on_delete'],
388 75
                    'onUpdate' => $value['on_update'],
389 75
                    'deferrable' => $value['deferrable'],
390 75
                    'deferred'=> $value['deferred'],
391
                ];
392
            }
393 75
            $list[$name]['local'][]   = $value['from'];
394 75
            $list[$name]['foreign'][] = $value['to'];
395
        }
396
397 75
        $result = [];
398 75
        foreach ($list as $constraint) {
399 75
            $result[] = new ForeignKeyConstraint(
400 75
                array_values($constraint['local']),
401 75
                $constraint['foreignTable'],
402 75
                array_values($constraint['foreign']),
403 75
                $constraint['name'],
404
                [
405 75
                    'onDelete' => $constraint['onDelete'],
406 75
                    'onUpdate' => $constraint['onUpdate'],
407 75
                    'deferrable' => $constraint['deferrable'],
408 75
                    'deferred'=> $constraint['deferred'],
409
                ]
410
            );
411
        }
412
413 75
        return $result;
414
    }
415
416
    /**
417
     * @param Table|string $table
418
     *
419
     * @throws DBALException
420
     */
421
    private function getTableDiffForAlterForeignKey($table) : TableDiff
422
    {
423
        if (! $table instanceof Table) {
424
            $tableDetails = $this->tryMethod('listTableDetails', $table);
425
426
            if ($tableDetails === false) {
427
                throw new DBALException(sprintf('Sqlite schema manager requires to modify foreign keys table definition "%s".', $table));
428
            }
429
430
            $table = $tableDetails;
431
        }
432
433
        $tableDiff            = new TableDiff($table->getName());
434
        $tableDiff->fromTable = $table;
435
436
        return $tableDiff;
437
    }
438
439 1019
    private function parseColumnCollationFromSQL(string $column, string $sql) : ?string
440
    {
441 1019
        $pattern = '{(?:\W' . preg_quote($column) . '\W|\W' . preg_quote($this->_platform->quoteSingleIdentifier($column))
442 1019
            . '\W)[^,(]+(?:\([^()]+\)[^,]*)?(?:(?:DEFAULT|CHECK)\s*(?:\(.*?\))?[^,]*)*COLLATE\s+["\']?([^\s,"\')]+)}is';
443
444 1019
        if (preg_match($pattern, $sql, $match) !== 1) {
445 956
            return null;
446
        }
447
448 995
        return $match[1];
449
    }
450
451 691
    private function parseColumnCommentFromSQL(string $column, string $sql) : ?string
452
    {
453 691
        $pattern = '{[\s(,](?:\W' . preg_quote($this->_platform->quoteSingleIdentifier($column)) . '\W|\W' . preg_quote($column)
454 691
            . '\W)(?:\(.*?\)|[^,(])*?,?((?:(?!\n))(?:\s*--[^\n]*\n?)+)}i';
455
456 691
        if (preg_match($pattern, $sql, $match) !== 1) {
457 680
            return null;
458
        }
459
460 676
        $comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n"));
461
462 676
        return $comment === '' ? null : $comment;
463
    }
464
465 149
    private function getCreateTableSQL(string $table) : ?string
466
    {
467 149
        return $this->_conn->fetchColumn(
468
            <<<'SQL'
469 149
SELECT sql
470
  FROM (
471
      SELECT *
472
        FROM sqlite_master
473
   UNION ALL
474
      SELECT *
475
        FROM sqlite_temp_master
476
  )
477
WHERE type = 'table'
478
AND name = ?
479
SQL
480
            ,
481 149
            [$table]
482 149
        ) ?: null;
483
    }
484
}
485