SqliteSchemaManager.php 16.2 KB
Newer Older
romanb's avatar
romanb committed
1 2
<?php

3
namespace Doctrine\DBAL\Schema;
romanb's avatar
romanb committed
4

5
use Doctrine\DBAL\DBALException;
6
use Doctrine\DBAL\DriverManager;
7
use Doctrine\DBAL\FetchMode;
8 9
use Doctrine\DBAL\Types\StringType;
use Doctrine\DBAL\Types\TextType;
10
use Doctrine\DBAL\Types\Type;
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
use function array_change_key_case;
use function array_map;
use function array_reverse;
use function array_values;
use function explode;
use function file_exists;
use function preg_match;
use function preg_match_all;
use function preg_quote;
use function preg_replace;
use function rtrim;
use function sprintf;
use function str_replace;
use function strpos;
use function strtolower;
use function trim;
use function unlink;
use function usort;
Grégoire Paris's avatar
Grégoire Paris committed
29
use const CASE_LOWER;
30

romanb's avatar
romanb committed
31
/**
Benjamin Morel's avatar
Benjamin Morel committed
32
 * Sqlite SchemaManager.
romanb's avatar
romanb committed
33
 */
34
class SqliteSchemaManager extends AbstractSchemaManager
35
{
romanb's avatar
romanb committed
36 37 38 39
    /**
     * {@inheritdoc}
     */
    public function dropDatabase($database)
40
    {
41 42
        if (! file_exists($database)) {
            return;
43
        }
44 45

        unlink($database);
46 47
    }

romanb's avatar
romanb committed
48 49 50 51
    /**
     * {@inheritdoc}
     */
    public function createDatabase($database)
52
    {
53 54
        $params  = $this->_conn->getParams();
        $driver  = $params['driver'];
55
        $options = [
jwage's avatar
jwage committed
56
            'driver' => $driver,
57
            'path' => $database,
58
        ];
59
        $conn    = DriverManager::getConnection($options);
jwage's avatar
jwage committed
60 61
        $conn->connect();
        $conn->close();
62 63
    }

64 65 66 67 68
    /**
     * {@inheritdoc}
     */
    public function renameTable($name, $newName)
    {
69
        $tableDiff            = new TableDiff($name);
70
        $tableDiff->fromTable = $this->listTableDetails($name);
71
        $tableDiff->newName   = $newName;
72 73 74 75 76 77 78 79
        $this->alterTable($tableDiff);
    }

    /**
     * {@inheritdoc}
     */
    public function createForeignKey(ForeignKeyConstraint $foreignKey, $table)
    {
Sergei Morozov's avatar
Sergei Morozov committed
80
        $tableDiff                     = $this->getTableDiffForAlterForeignKey($table);
81 82 83 84 85 86 87 88 89 90
        $tableDiff->addedForeignKeys[] = $foreignKey;

        $this->alterTable($tableDiff);
    }

    /**
     * {@inheritdoc}
     */
    public function dropAndCreateForeignKey(ForeignKeyConstraint $foreignKey, $table)
    {
Sergei Morozov's avatar
Sergei Morozov committed
91
        $tableDiff                       = $this->getTableDiffForAlterForeignKey($table);
92 93 94 95 96 97 98 99 100 101
        $tableDiff->changedForeignKeys[] = $foreignKey;

        $this->alterTable($tableDiff);
    }

    /**
     * {@inheritdoc}
     */
    public function dropForeignKey($foreignKey, $table)
    {
Sergei Morozov's avatar
Sergei Morozov committed
102
        $tableDiff                       = $this->getTableDiffForAlterForeignKey($table);
103 104 105 106 107 108 109 110 111 112
        $tableDiff->removedForeignKeys[] = $foreignKey;

        $this->alterTable($tableDiff);
    }

    /**
     * {@inheritdoc}
     */
    public function listTableForeignKeys($table, $database = null)
    {
113
        if ($database === null) {
114 115
            $database = $this->_conn->getDatabase();
        }
Grégoire Paris's avatar
Grégoire Paris committed
116

117
        $sql              = $this->_platform->getListTableForeignKeysSQL($table, $database);
118 119
        $tableForeignKeys = $this->_conn->fetchAll($sql);

120
        if (! empty($tableForeignKeys)) {
121
            $createSql = $this->getCreateTableSQL($table);
122

123
            if ($createSql !== null && preg_match_all(
124
                '#
125 126 127 128 129 130 131 132
                    (?:CONSTRAINT\s+([^\s]+)\s+)?
                    (?:FOREIGN\s+KEY[^\)]+\)\s*)?
                    REFERENCES\s+[^\s]+\s+(?:\([^\)]+\))?
                    (?:
                        [^,]*?
                        (NOT\s+DEFERRABLE|DEFERRABLE)
                        (?:\s+INITIALLY\s+(DEFERRED|IMMEDIATE))?
                    )?#isx',
133 134 135 136
                $createSql,
                $match
            )) {
                $names      = array_reverse($match[1]);
137
                $deferrable = array_reverse($match[2]);
138
                $deferred   = array_reverse($match[3]);
139
            } else {
140
                $names = $deferrable = $deferred = [];
141 142 143
            }

            foreach ($tableForeignKeys as $key => $value) {
144 145
                $id                                        = $value['id'];
                $tableForeignKeys[$key]['constraint_name'] = isset($names[$id]) && $names[$id] !== '' ? $names[$id] : $id;
146 147
                $tableForeignKeys[$key]['deferrable']      = isset($deferrable[$id]) && strtolower($deferrable[$id]) === 'deferrable';
                $tableForeignKeys[$key]['deferred']        = isset($deferred[$id]) && strtolower($deferred[$id]) === 'deferred';
148 149 150 151 152 153
            }
        }

        return $this->_getPortableTableForeignKeysList($tableForeignKeys);
    }

Benjamin Morel's avatar
Benjamin Morel committed
154 155 156
    /**
     * {@inheritdoc}
     */
157 158 159 160 161
    protected function _getPortableTableDefinition($table)
    {
        return $table['name'];
    }

162
    /**
Benjamin Morel's avatar
Benjamin Morel committed
163 164
     * {@inheritdoc}
     *
165 166
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
     */
167
    protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
168
    {
169
        $indexBuffer = [];
170 171

        // fetch primary
172 173 174 175
        $stmt       = $this->_conn->executeQuery(sprintf(
            'PRAGMA TABLE_INFO (%s)',
            $this->_conn->quote($tableName)
        ));
176
        $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
177

178 179
        usort($indexArray, static function ($a, $b) {
            if ($a['pk'] === $b['pk']) {
180 181
                return $a['cid'] - $b['cid'];
            }
182

183 184
            return $a['pk'] - $b['pk'];
        });
Steve Müller's avatar
Steve Müller committed
185
        foreach ($indexArray as $indexColumnRow) {
186 187
            if ($indexColumnRow['pk'] === '0') {
                continue;
188
            }
189 190 191 192 193 194 195

            $indexBuffer[] = [
                'key_name' => 'primary',
                'primary' => true,
                'non_unique' => false,
                'column_name' => $indexColumnRow['name'],
            ];
196 197 198
        }

        // fetch regular indexes
Steve Müller's avatar
Steve Müller committed
199
        foreach ($tableIndexes as $tableIndex) {
200
            // Ignore indexes with reserved names, e.g. autoindexes
201 202 203 204 205 206 207 208
            if (strpos($tableIndex['name'], 'sqlite_') === 0) {
                continue;
            }

            $keyName           = $tableIndex['name'];
            $idx               = [];
            $idx['key_name']   = $keyName;
            $idx['primary']    = false;
209
            $idx['non_unique'] = ! $tableIndex['unique'];
210

211 212 213 214 215
                $stmt       = $this->_conn->executeQuery(sprintf(
                    'PRAGMA INDEX_INFO (%s)',
                    $this->_conn->quote($keyName)
                ));
                $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
216 217 218 219

            foreach ($indexArray as $indexColumnRow) {
                $idx['column_name'] = $indexColumnRow['name'];
                $indexBuffer[]      = $idx;
220 221 222 223 224 225
            }
        }

        return parent::_getPortableTableIndexesList($indexBuffer, $tableName);
    }

Benjamin Morel's avatar
Benjamin Morel committed
226
    /**
227
     * @deprecated
228
     *
229 230
     * @param array<string, mixed> $tableIndex
     *
231
     * @return array<string, bool|string>
Benjamin Morel's avatar
Benjamin Morel committed
232
     */
233 234
    protected function _getPortableTableIndexDefinition($tableIndex)
    {
235
        return [
236
            'name' => $tableIndex['name'],
237
            'unique' => (bool) $tableIndex['unique'],
238
        ];
239 240
    }

Benjamin Morel's avatar
Benjamin Morel committed
241 242 243
    /**
     * {@inheritdoc}
     */
244 245 246
    protected function _getPortableTableColumnList($table, $database, $tableColumns)
    {
        $list = parent::_getPortableTableColumnList($table, $database, $tableColumns);
247 248

        // find column with autoincrement
249
        $autoincrementColumn = null;
250
        $autoincrementCount  = 0;
251

252
        foreach ($tableColumns as $tableColumn) {
253 254 255 256 257 258 259
            if ($tableColumn['pk'] === '0') {
                continue;
            }

            $autoincrementCount++;
            if ($autoincrementColumn !== null || strtolower($tableColumn['type']) !== 'integer') {
                continue;
260
            }
261 262

            $autoincrementColumn = $tableColumn['name'];
263 264
        }

265
        if ($autoincrementCount === 1 && $autoincrementColumn !== null) {
266
            foreach ($list as $column) {
267 268
                if ($autoincrementColumn !== $column->getName()) {
                    continue;
269
                }
270 271

                $column->setAutoincrement(true);
272 273 274
            }
        }

275
        // inspect column collation and comments
276
        $createSql = $this->getCreateTableSQL($table) ?? '';
277 278 279 280 281 282 283

        foreach ($list as $columnName => $column) {
            $type = $column->getType();

            if ($type instanceof StringType || $type instanceof TextType) {
                $column->setPlatformOption('collation', $this->parseColumnCollationFromSQL($columnName, $createSql) ?: 'BINARY');
            }
284 285

            $comment = $this->parseColumnCommentFromSQL($columnName, $createSql);
Steve Müller's avatar
Steve Müller committed
286

287 288 289
            if ($comment === null) {
                continue;
            }
Steve Müller's avatar
Steve Müller committed
290

Sergei Morozov's avatar
Sergei Morozov committed
291
            $type = $this->extractDoctrineTypeFromComment($comment, '');
Steve Müller's avatar
Steve Müller committed
292

Sergei Morozov's avatar
Sergei Morozov committed
293
            if ($type !== '') {
294
                $column->setType(Type::getType($type));
295

296
                $comment = $this->removeDoctrineTypeFromComment($comment, $type);
297
            }
298 299

            $column->setComment($comment);
300 301
        }

302 303 304
        return $list;
    }

Benjamin Morel's avatar
Benjamin Morel committed
305 306 307
    /**
     * {@inheritdoc}
     */
308 309
    protected function _getPortableTableColumnDefinition($tableColumn)
    {
310
        $parts               = explode('(', $tableColumn['type']);
311
        $tableColumn['type'] = trim($parts[0]);
312
        if (isset($parts[1])) {
313
            $length                = trim($parts[1], ')');
314 315 316
            $tableColumn['length'] = $length;
        }

Gabriel Caruso's avatar
Gabriel Caruso committed
317 318
        $dbType   = strtolower($tableColumn['type']);
        $length   = $tableColumn['length'] ?? null;
319 320 321
        $unsigned = false;

        if (strpos($dbType, ' unsigned') !== false) {
322
            $dbType   = str_replace(' unsigned', '', $dbType);
323 324 325
            $unsigned = true;
        }

326 327
        $fixed   = false;
        $type    = $this->_platform->getDoctrineTypeMapping($dbType);
328
        $default = $tableColumn['dflt_value'];
329
        if ($default === 'NULL') {
330 331
            $default = null;
        }
332

333
        if ($default !== null) {
334 335 336 337
            // SQLite returns the default value as a literal expression, so we need to parse it
            if (preg_match('/^\'(.*)\'$/s', $default, $matches)) {
                $default = str_replace("''", "'", $matches[1]);
            }
338
        }
339

340 341
        $notnull = (bool) $tableColumn['notnull'];

342
        if (! isset($tableColumn['name'])) {
343 344 345
            $tableColumn['name'] = '';
        }

346
        $precision = null;
347
        $scale     = null;
348

349 350
        switch ($dbType) {
            case 'char':
351
                $fixed = true;
352 353 354 355 356 357
                break;
            case 'float':
            case 'double':
            case 'real':
            case 'decimal':
            case 'numeric':
358
                if (isset($tableColumn['length'])) {
359
                    if (strpos($tableColumn['length'], ',') === false) {
360
                        $tableColumn['length'] .= ',0';
Steve Müller's avatar
Steve Müller committed
361
                    }
Grégoire Paris's avatar
Grégoire Paris committed
362

363
                    [$precision, $scale] = array_map('trim', explode(',', $tableColumn['length']));
364
                }
Grégoire Paris's avatar
Grégoire Paris committed
365

366 367 368 369
                $length = null;
                break;
        }

370
        $options = [
371 372 373 374 375 376 377
            'length'   => $length,
            'unsigned' => (bool) $unsigned,
            'fixed'    => $fixed,
            'notnull'  => $notnull,
            'default'  => $default,
            'precision' => $precision,
            'scale'     => $scale,
378
            'autoincrement' => false,
379
        ];
380

381
        return new Column($tableColumn['name'], Type::getType($type), $options);
382
    }
383

Benjamin Morel's avatar
Benjamin Morel committed
384 385 386
    /**
     * {@inheritdoc}
     */
387 388 389 390
    protected function _getPortableViewDefinition($view)
    {
        return new View($view['name'], $view['sql']);
    }
391

Benjamin Morel's avatar
Benjamin Morel committed
392 393 394
    /**
     * {@inheritdoc}
     */
395 396
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
    {
397
        $list = [];
Benjamin Morel's avatar
Benjamin Morel committed
398
        foreach ($tableForeignKeys as $value) {
399
            $value = array_change_key_case($value, CASE_LOWER);
400 401 402
            $name  = $value['constraint_name'];
            if (! isset($list[$name])) {
                if (! isset($value['on_delete']) || $value['on_delete'] === 'RESTRICT') {
403 404
                    $value['on_delete'] = null;
                }
Grégoire Paris's avatar
Grégoire Paris committed
405

406
                if (! isset($value['on_update']) || $value['on_update'] === 'RESTRICT') {
407 408 409
                    $value['on_update'] = null;
                }

410
                $list[$name] = [
411
                    'name' => $name,
412 413
                    'local' => [],
                    'foreign' => [],
414 415 416
                    'foreignTable' => $value['table'],
                    'onDelete' => $value['on_delete'],
                    'onUpdate' => $value['on_update'],
417 418
                    'deferrable' => $value['deferrable'],
                    'deferred'=> $value['deferred'],
419
                ];
420
            }
Grégoire Paris's avatar
Grégoire Paris committed
421

422
            $list[$name]['local'][]   = $value['from'];
423
            $list[$name]['foreign'][] = $value['to'];
424 425
        }

426
        $result = [];
Steve Müller's avatar
Steve Müller committed
427
        foreach ($list as $constraint) {
428
            $result[] = new ForeignKeyConstraint(
429 430 431 432
                array_values($constraint['local']),
                $constraint['foreignTable'],
                array_values($constraint['foreign']),
                $constraint['name'],
433
                [
434 435
                    'onDelete' => $constraint['onDelete'],
                    'onUpdate' => $constraint['onUpdate'],
436 437
                    'deferrable' => $constraint['deferrable'],
                    'deferred'=> $constraint['deferred'],
438
                ]
439 440 441 442 443 444
            );
        }

        return $result;
    }

Benjamin Morel's avatar
Benjamin Morel committed
445
    /**
446
     * @param Table|string $table
Benjamin Morel's avatar
Benjamin Morel committed
447
     *
448
     * @return TableDiff
Benjamin Morel's avatar
Benjamin Morel committed
449
     *
450
     * @throws DBALException
Benjamin Morel's avatar
Benjamin Morel committed
451
     */
Sergei Morozov's avatar
Sergei Morozov committed
452
    private function getTableDiffForAlterForeignKey($table)
453
    {
454
        if (! $table instanceof Table) {
455
            $tableDetails = $this->tryMethod('listTableDetails', $table);
Sergei Morozov's avatar
Sergei Morozov committed
456 457

            if ($tableDetails === false) {
Benjamin Morel's avatar
Benjamin Morel committed
458
                throw new DBALException(sprintf('Sqlite schema manager requires to modify foreign keys table definition "%s".', $table));
459 460 461 462 463
            }

            $table = $tableDetails;
        }

464
        $tableDiff            = new TableDiff($table->getName());
465 466 467 468
        $tableDiff->fromTable = $table;

        return $tableDiff;
    }
469

470
    private function parseColumnCollationFromSQL(string $column, string $sql) : ?string
471
    {
472
        $pattern = '{(?:\W' . preg_quote($column) . '\W|\W' . preg_quote($this->_platform->quoteSingleIdentifier($column))
473
            . '\W)[^,(]+(?:\([^()]+\)[^,]*)?(?:(?:DEFAULT|CHECK)\s*(?:\(.*?\))?[^,]*)*COLLATE\s+["\']?([^\s,"\')]+)}is';
474

475 476
        if (preg_match($pattern, $sql, $match) !== 1) {
            return null;
477 478
        }

479
        return $match[1];
480
    }
481

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
    private function parseTableCommentFromSQL(string $table, string $sql) : ?string
    {
        $pattern = '/\s* # Allow whitespace characters at start of line
CREATE\sTABLE # Match "CREATE TABLE"
(?:\W"' . preg_quote($this->_platform->quoteSingleIdentifier($table), '/') . '"\W|\W' . preg_quote($table, '/')
            . '\W) # Match table name (quoted and unquoted)
( # Start capture
   (?:\s*--[^\n]*\n?)+ # Capture anything that starts with whitespaces followed by -- until the end of the line(s)
)/ix';

        if (preg_match($pattern, $sql, $match) !== 1) {
            return null;
        }

        $comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n"));

        return $comment === '' ? null : $comment;
    }

501
    private function parseColumnCommentFromSQL(string $column, string $sql) : ?string
502
    {
503
        $pattern = '{[\s(,](?:\W' . preg_quote($this->_platform->quoteSingleIdentifier($column)) . '\W|\W' . preg_quote($column)
504
            . '\W)(?:\([^)]*?\)|[^,(])*?,?((?:(?!\n))(?:\s*--[^\n]*\n?)+)}i';
505

506 507
        if (preg_match($pattern, $sql, $match) !== 1) {
            return null;
508 509
        }

510 511
        $comment = preg_replace('{^\s*--}m', '', rtrim($match[1], "\n"));

512
        return $comment === '' ? null : $comment;
513
    }
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533

    private function getCreateTableSQL(string $table) : ?string
    {
        return $this->_conn->fetchColumn(
            <<<'SQL'
SELECT sql
  FROM (
      SELECT *
        FROM sqlite_master
   UNION ALL
      SELECT *
        FROM sqlite_temp_master
  )
WHERE type = 'table'
AND name = ?
SQL
            ,
            [$table]
        ) ?: null;
    }
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551

    /**
     * @param string $tableName
     */
    public function listTableDetails($tableName) : Table
    {
        $table = parent::listTableDetails($tableName);

        $tableCreateSql = $this->getCreateTableSQL($tableName) ?? '';

        $comment = $this->parseTableCommentFromSQL($tableName, $tableCreateSql);

        if ($comment !== null) {
            $table->addOption('comment', $comment);
        }

        return $table;
    }
552
}