SqliteSchemaManager.php 15.7 KB
Newer Older
romanb's avatar
romanb committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
Benjamin Eberlei's avatar
Benjamin Eberlei committed
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
romanb's avatar
romanb committed
18 19
 */

20
namespace Doctrine\DBAL\Schema;
romanb's avatar
romanb committed
21

22
use Doctrine\DBAL\DBALException;
23
use Doctrine\DBAL\FetchMode;
24 25
use Doctrine\DBAL\Types\StringType;
use Doctrine\DBAL\Types\TextType;
26
use Doctrine\DBAL\Types\Type;
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
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;
46

romanb's avatar
romanb committed
47
/**
Benjamin Morel's avatar
Benjamin Morel committed
48
 * Sqlite SchemaManager.
romanb's avatar
romanb committed
49
 *
Benjamin Morel's avatar
Benjamin Morel committed
50 51 52 53 54
 * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
 * @author Jonathan H. Wage <jonwage@gmail.com>
 * @author Martin Hasoň <martin.hason@gmail.com>
 * @since  2.0
romanb's avatar
romanb committed
55
 */
56
class SqliteSchemaManager extends AbstractSchemaManager
57
{
romanb's avatar
romanb committed
58 59 60 61
    /**
     * {@inheritdoc}
     */
    public function dropDatabase($database)
62
    {
63 64
        if (file_exists($database)) {
            unlink($database);
65 66 67
        }
    }

romanb's avatar
romanb committed
68 69 70 71
    /**
     * {@inheritdoc}
     */
    public function createDatabase($database)
72
    {
jwage's avatar
jwage committed
73 74
        $params = $this->_conn->getParams();
        $driver = $params['driver'];
75
        $options = [
jwage's avatar
jwage committed
76 77
            'driver' => $driver,
            'path' => $database
78
        ];
jwage's avatar
jwage committed
79 80 81
        $conn = \Doctrine\DBAL\DriverManager::getConnection($options);
        $conn->connect();
        $conn->close();
82 83
    }

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    /**
     * {@inheritdoc}
     */
    public function renameTable($name, $newName)
    {
        $tableDiff = new TableDiff($name);
        $tableDiff->fromTable = $this->listTableDetails($name);
        $tableDiff->newName = $newName;
        $this->alterTable($tableDiff);
    }

    /**
     * {@inheritdoc}
     */
    public function createForeignKey(ForeignKeyConstraint $foreignKey, $table)
    {
        $tableDiff = $this->getTableDiffForAlterForeignKey($foreignKey, $table);
        $tableDiff->addedForeignKeys[] = $foreignKey;

        $this->alterTable($tableDiff);
    }

    /**
     * {@inheritdoc}
     */
    public function dropAndCreateForeignKey(ForeignKeyConstraint $foreignKey, $table)
    {
        $tableDiff = $this->getTableDiffForAlterForeignKey($foreignKey, $table);
        $tableDiff->changedForeignKeys[] = $foreignKey;

        $this->alterTable($tableDiff);
    }

    /**
     * {@inheritdoc}
     */
    public function dropForeignKey($foreignKey, $table)
    {
        $tableDiff = $this->getTableDiffForAlterForeignKey($foreignKey, $table);
        $tableDiff->removedForeignKeys[] = $foreignKey;

        $this->alterTable($tableDiff);
    }

    /**
     * {@inheritdoc}
     */
    public function listTableForeignKeys($table, $database = null)
    {
        if (null === $database) {
            $database = $this->_conn->getDatabase();
        }
        $sql = $this->_platform->getListTableForeignKeysSQL($table, $database);
        $tableForeignKeys = $this->_conn->fetchAll($sql);

        if ( ! empty($tableForeignKeys)) {
            $createSql = $this->_conn->fetchAll("SELECT sql FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type = 'table' AND name = '$table'");
141
            $createSql = $createSql[0]['sql'] ?? '';
142

143 144 145 146 147 148 149 150 151 152 153
            if (preg_match_all('#
                    (?:CONSTRAINT\s+([^\s]+)\s+)?
                    (?:FOREIGN\s+KEY[^\)]+\)\s*)?
                    REFERENCES\s+[^\s]+\s+(?:\([^\)]+\))?
                    (?:
                        [^,]*?
                        (NOT\s+DEFERRABLE|DEFERRABLE)
                        (?:\s+INITIALLY\s+(DEFERRED|IMMEDIATE))?
                    )?#isx',
                    $createSql, $match)) {

154
                $names = array_reverse($match[1]);
155 156
                $deferrable = array_reverse($match[2]);
                $deferred = array_reverse($match[3]);
157
            } else {
158
                $names = $deferrable = $deferred = [];
159 160 161 162 163
            }

            foreach ($tableForeignKeys as $key => $value) {
                $id = $value['id'];
                $tableForeignKeys[$key]['constraint_name'] = isset($names[$id]) && '' != $names[$id] ? $names[$id] : $id;
164 165
                $tableForeignKeys[$key]['deferrable']      = isset($deferrable[$id]) && strtolower($deferrable[$id]) === 'deferrable';
                $tableForeignKeys[$key]['deferred']        = isset($deferred[$id]) && strtolower($deferred[$id]) === 'deferred';
166 167 168 169 170 171
            }
        }

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

Benjamin Morel's avatar
Benjamin Morel committed
172 173 174
    /**
     * {@inheritdoc}
     */
175 176 177 178 179
    protected function _getPortableTableDefinition($table)
    {
        return $table['name'];
    }

180
    /**
Benjamin Morel's avatar
Benjamin Morel committed
181 182
     * {@inheritdoc}
     *
183 184 185 186 187
     * @license New BSD License
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
     */
    protected function _getPortableTableIndexesList($tableIndexes, $tableName=null)
    {
188
        $indexBuffer = [];
189 190

        // fetch primary
Steve Müller's avatar
Steve Müller committed
191
        $stmt = $this->_conn->executeQuery("PRAGMA TABLE_INFO ('$tableName')");
192
        $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
193

194
        usort($indexArray, function($a, $b) {
195 196 197
            if ($a['pk'] == $b['pk']) {
                return $a['cid'] - $b['cid'];
            }
198

199 200
            return $a['pk'] - $b['pk'];
        });
Steve Müller's avatar
Steve Müller committed
201
        foreach ($indexArray as $indexColumnRow) {
202
            if ($indexColumnRow['pk'] != "0") {
203
                $indexBuffer[] = [
204 205 206 207
                    'key_name' => 'primary',
                    'primary' => true,
                    'non_unique' => false,
                    'column_name' => $indexColumnRow['name']
208
                ];
209 210 211 212
            }
        }

        // fetch regular indexes
Steve Müller's avatar
Steve Müller committed
213
        foreach ($tableIndexes as $tableIndex) {
214 215 216
            // Ignore indexes with reserved names, e.g. autoindexes
            if (strpos($tableIndex['name'], 'sqlite_') !== 0) {
                $keyName = $tableIndex['name'];
217
                $idx = [];
218 219 220
                $idx['key_name'] = $keyName;
                $idx['primary'] = false;
                $idx['non_unique'] = $tableIndex['unique']?false:true;
221

Steve Müller's avatar
Steve Müller committed
222
                $stmt = $this->_conn->executeQuery("PRAGMA INDEX_INFO ('{$keyName}')");
223
                $indexArray = $stmt->fetchAll(FetchMode::ASSOCIATIVE);
224

Steve Müller's avatar
Steve Müller committed
225
                foreach ($indexArray as $indexColumnRow) {
226 227 228
                    $idx['column_name'] = $indexColumnRow['name'];
                    $indexBuffer[] = $idx;
                }
229 230 231 232 233 234
            }
        }

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

Benjamin Morel's avatar
Benjamin Morel committed
235 236 237
    /**
     * {@inheritdoc}
     */
238 239
    protected function _getPortableTableIndexDefinition($tableIndex)
    {
240
        return [
241 242
            'name' => $tableIndex['name'],
            'unique' => (bool) $tableIndex['unique']
243
        ];
244 245
    }

Benjamin Morel's avatar
Benjamin Morel committed
246 247 248
    /**
     * {@inheritdoc}
     */
249 250 251
    protected function _getPortableTableColumnList($table, $database, $tableColumns)
    {
        $list = parent::_getPortableTableColumnList($table, $database, $tableColumns);
252 253

        // find column with autoincrement
254 255
        $autoincrementColumn = null;
        $autoincrementCount = 0;
256

257
        foreach ($tableColumns as $tableColumn) {
258
            if ('0' != $tableColumn['pk']) {
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
                $autoincrementCount++;
                if (null === $autoincrementColumn && 'integer' == strtolower($tableColumn['type'])) {
                    $autoincrementColumn = $tableColumn['name'];
                }
            }
        }

        if (1 == $autoincrementCount && null !== $autoincrementColumn) {
            foreach ($list as $column) {
                if ($autoincrementColumn == $column->getName()) {
                    $column->setAutoincrement(true);
                }
            }
        }

274
        // inspect column collation and comments
275
        $createSql = $this->_conn->fetchAll("SELECT sql FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type = 'table' AND name = '$table'");
276
        $createSql = $createSql[0]['sql'] ?? '';
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
            if ($comment !== null) {
288
                $type = $this->extractDoctrineTypeFromComment($comment, null);
Steve Müller's avatar
Steve Müller committed
289

290 291
                if (null !== $type) {
                    $column->setType(Type::getType($type));
Steve Müller's avatar
Steve Müller committed
292

293 294 295 296 297
                    $comment = $this->removeDoctrineTypeFromComment($comment, $type);
                }

                $column->setComment($comment);
            }
298 299
        }

300 301 302
        return $list;
    }

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

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

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

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

        if ( ! isset($tableColumn['name'])) {
            $tableColumn['name'] = '';
        }

340 341 342
        $precision = null;
        $scale = null;

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

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

373
        return new Column($tableColumn['name'], \Doctrine\DBAL\Types\Type::getType($type), $options);
374
    }
375

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

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

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

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

        return $result;
    }

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

            $table = $tableDetails;
        }

        $tableDiff = new TableDiff($table->getName());
        $tableDiff->fromTable = $table;

        return $tableDiff;
    }
457

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

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

467
        return $match[1];
468
    }
469

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

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

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

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