SqliteSchemaManager.php 15 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 29
use const CASE_LOWER;
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;
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)
    {
80
        $tableDiff                     = $this->getTableDiffForAlterForeignKey($foreignKey, $table);
81 82 83 84 85 86 87 88 89 90
        $tableDiff->addedForeignKeys[] = $foreignKey;

        $this->alterTable($tableDiff);
    }

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

        $this->alterTable($tableDiff);
    }

    /**
     * {@inheritdoc}
     */
    public function dropForeignKey($foreignKey, $table)
    {
102
        $tableDiff                       = $this->getTableDiffForAlterForeignKey($foreignKey, $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();
        }
116
        $sql              = $this->_platform->getListTableForeignKeysSQL($table, $database);
117 118
        $tableForeignKeys = $this->_conn->fetchAll($sql);

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

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

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

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

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

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

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

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

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

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

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

            $keyName           = $tableIndex['name'];
            $idx               = [];
            $idx['key_name']   = $keyName;
            $idx['primary']    = false;
            $idx['non_unique'] = $tableIndex['unique']?false:true;

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

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

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

Benjamin Morel's avatar
Benjamin Morel committed
225 226 227
    /**
     * {@inheritdoc}
     */
228 229
    protected function _getPortableTableIndexDefinition($tableIndex)
    {
230
        return [
231
            'name' => $tableIndex['name'],
232
            'unique' => (bool) $tableIndex['unique'],
233
        ];
234 235
    }

Benjamin Morel's avatar
Benjamin Morel committed
236 237 238
    /**
     * {@inheritdoc}
     */
239 240 241
    protected function _getPortableTableColumnList($table, $database, $tableColumns)
    {
        $list = parent::_getPortableTableColumnList($table, $database, $tableColumns);
242 243

        // find column with autoincrement
244
        $autoincrementColumn = null;
245
        $autoincrementCount  = 0;
246

247
        foreach ($tableColumns as $tableColumn) {
248 249 250 251 252 253 254
            if ($tableColumn['pk'] === '0') {
                continue;
            }

            $autoincrementCount++;
            if ($autoincrementColumn !== null || strtolower($tableColumn['type']) !== 'integer') {
                continue;
255
            }
256 257

            $autoincrementColumn = $tableColumn['name'];
258 259
        }

260
        if ($autoincrementCount === 1 && $autoincrementColumn !== null) {
261
            foreach ($list as $column) {
262 263
                if ($autoincrementColumn !== $column->getName()) {
                    continue;
264
                }
265 266

                $column->setAutoincrement(true);
267 268 269
            }
        }

270
        // inspect column collation and comments
271
        $createSql = $this->getCreateTableSQL($table) ?? '';
272 273 274 275 276 277 278

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

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

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

282 283 284
            if ($comment === null) {
                continue;
            }
Steve Müller's avatar
Steve Müller committed
285

286
            $type = $this->extractDoctrineTypeFromComment($comment, null);
Steve Müller's avatar
Steve Müller committed
287

288 289
            if ($type !== null) {
                $column->setType(Type::getType($type));
290

291
                $comment = $this->removeDoctrineTypeFromComment($comment, $type);
292
            }
293 294

            $column->setComment($comment);
295 296
        }

297 298 299
        return $list;
    }

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

Gabriel Caruso's avatar
Gabriel Caruso committed
312 313
        $dbType   = strtolower($tableColumn['type']);
        $length   = $tableColumn['length'] ?? null;
314 315 316
        $unsigned = false;

        if (strpos($dbType, ' unsigned') !== false) {
317
            $dbType   = str_replace(' unsigned', '', $dbType);
318 319 320
            $unsigned = true;
        }

321 322
        $fixed   = false;
        $type    = $this->_platform->getDoctrineTypeMapping($dbType);
323
        $default = $tableColumn['dflt_value'];
324
        if ($default === 'NULL') {
325 326
            $default = null;
        }
327
        if ($default !== null) {
328 329
            // SQLite returns strings wrapped in single quotes, so we need to strip them
            $default = preg_replace("/^'(.*)'$/", '\1', $default);
330
        }
331 332
        $notnull = (bool) $tableColumn['notnull'];

333
        if (! isset($tableColumn['name'])) {
334 335 336
            $tableColumn['name'] = '';
        }

337
        $precision = null;
338
        $scale     = null;
339

340 341
        switch ($dbType) {
            case 'char':
342
                $fixed = true;
343 344 345 346 347 348
                break;
            case 'float':
            case 'double':
            case 'real':
            case 'decimal':
            case 'numeric':
349
                if (isset($tableColumn['length'])) {
350
                    if (strpos($tableColumn['length'], ',') === false) {
351
                        $tableColumn['length'] .= ',0';
Steve Müller's avatar
Steve Müller committed
352
                    }
353
                    [$precision, $scale] = array_map('trim', explode(',', $tableColumn['length']));
354
                }
355 356 357 358
                $length = null;
                break;
        }

359
        $options = [
360 361 362 363 364 365 366
            'length'   => $length,
            'unsigned' => (bool) $unsigned,
            'fixed'    => $fixed,
            'notnull'  => $notnull,
            'default'  => $default,
            'precision' => $precision,
            'scale'     => $scale,
367
            'autoincrement' => false,
368
        ];
369

370
        return new Column($tableColumn['name'], Type::getType($type), $options);
371
    }
372

Benjamin Morel's avatar
Benjamin Morel committed
373 374 375
    /**
     * {@inheritdoc}
     */
376 377 378 379
    protected function _getPortableViewDefinition($view)
    {
        return new View($view['name'], $view['sql']);
    }
380

Benjamin Morel's avatar
Benjamin Morel committed
381 382 383
    /**
     * {@inheritdoc}
     */
384 385
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
    {
386
        $list = [];
Benjamin Morel's avatar
Benjamin Morel committed
387
        foreach ($tableForeignKeys as $value) {
388
            $value = array_change_key_case($value, CASE_LOWER);
389 390 391
            $name  = $value['constraint_name'];
            if (! isset($list[$name])) {
                if (! isset($value['on_delete']) || $value['on_delete'] === 'RESTRICT') {
392 393
                    $value['on_delete'] = null;
                }
394
                if (! isset($value['on_update']) || $value['on_update'] === 'RESTRICT') {
395 396 397
                    $value['on_update'] = null;
                }

398
                $list[$name] = [
399
                    'name' => $name,
400 401
                    'local' => [],
                    'foreign' => [],
402 403 404
                    'foreignTable' => $value['table'],
                    'onDelete' => $value['on_delete'],
                    'onUpdate' => $value['on_update'],
405 406
                    'deferrable' => $value['deferrable'],
                    'deferred'=> $value['deferred'],
407
                ];
408
            }
409
            $list[$name]['local'][]   = $value['from'];
410
            $list[$name]['foreign'][] = $value['to'];
411 412
        }

413
        $result = [];
Steve Müller's avatar
Steve Müller committed
414
        foreach ($list as $constraint) {
415
            $result[] = new ForeignKeyConstraint(
416 417 418 419
                array_values($constraint['local']),
                $constraint['foreignTable'],
                array_values($constraint['foreign']),
                $constraint['name'],
420
                [
421 422
                    'onDelete' => $constraint['onDelete'],
                    'onUpdate' => $constraint['onUpdate'],
423 424
                    'deferrable' => $constraint['deferrable'],
                    'deferred'=> $constraint['deferred'],
425
                ]
426 427 428 429 430 431
            );
        }

        return $result;
    }

Benjamin Morel's avatar
Benjamin Morel committed
432
    /**
433
     * @param Table|string $table
Benjamin Morel's avatar
Benjamin Morel committed
434
     *
435
     * @return TableDiff
Benjamin Morel's avatar
Benjamin Morel committed
436
     *
437
     * @throws DBALException
Benjamin Morel's avatar
Benjamin Morel committed
438
     */
439 440
    private function getTableDiffForAlterForeignKey(ForeignKeyConstraint $foreignKey, $table)
    {
441
        if (! $table instanceof Table) {
442
            $tableDetails = $this->tryMethod('listTableDetails', $table);
443
            if ($table === false) {
Benjamin Morel's avatar
Benjamin Morel committed
444
                throw new DBALException(sprintf('Sqlite schema manager requires to modify foreign keys table definition "%s".', $table));
445 446 447 448 449
            }

            $table = $tableDetails;
        }

450
        $tableDiff            = new TableDiff($table->getName());
451 452 453 454
        $tableDiff->fromTable = $table;

        return $tableDiff;
    }
455

456
    private function parseColumnCollationFromSQL(string $column, string $sql) : ?string
457
    {
458
        $pattern = '{(?:\W' . preg_quote($column) . '\W|\W' . preg_quote($this->_platform->quoteSingleIdentifier($column))
459
            . '\W)[^,(]+(?:\([^()]+\)[^,]*)?(?:(?:DEFAULT|CHECK)\s*(?:\(.*?\))?[^,]*)*COLLATE\s+["\']?([^\s,"\')]+)}is';
460

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

465
        return $match[1];
466
    }
467

468
    private function parseColumnCommentFromSQL(string $column, string $sql) : ?string
469
    {
470
        $pattern = '{[\s(,](?:\W' . preg_quote($this->_platform->quoteSingleIdentifier($column)) . '\W|\W' . preg_quote($column)
471
            . '\W)(?:\(.*?\)|[^,(])*?,?((?:(?!\n))(?:\s*--[^\n]*\n?)+)}i';
472

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

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

479
        return $comment === '' ? null : $comment;
480
    }
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500

    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;
    }
501
}