SqliteSchemaManager.php 12.9 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 23
use Doctrine\DBAL\DBALException;

romanb's avatar
romanb committed
24
/**
Benjamin Morel's avatar
Benjamin Morel committed
25
 * Sqlite SchemaManager.
romanb's avatar
romanb committed
26
 *
Benjamin Morel's avatar
Benjamin Morel committed
27 28 29 30 31
 * @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
32
 */
33
class SqliteSchemaManager extends AbstractSchemaManager
34
{
romanb's avatar
romanb committed
35 36 37 38
    /**
     * {@inheritdoc}
     */
    public function dropDatabase($database)
39
    {
40 41
        if (file_exists($database)) {
            unlink($database);
42 43 44
        }
    }

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

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 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
    /**
     * {@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'");
            $createSql = isset($createSql[0]['sql']) ? $createSql[0]['sql'] : '';
119 120 121 122 123 124 125 126 127 128 129
            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)) {

130
                $names = array_reverse($match[1]);
131 132
                $deferrable = array_reverse($match[2]);
                $deferred = array_reverse($match[3]);
133
            } else {
134
                $names = $deferrable = $deferred = array();
135 136 137 138 139
            }

            foreach ($tableForeignKeys as $key => $value) {
                $id = $value['id'];
                $tableForeignKeys[$key]['constraint_name'] = isset($names[$id]) && '' != $names[$id] ? $names[$id] : $id;
140 141
                $tableForeignKeys[$key]['deferrable'] = isset($deferrable[$id]) && 'deferrable' == strtolower($deferrable[$id]) ? true : false;
                $tableForeignKeys[$key]['deferred'] = isset($deferred[$id]) && 'deferred' == strtolower($deferred[$id]) ? true : false;
142 143 144 145 146 147
            }
        }

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

Benjamin Morel's avatar
Benjamin Morel committed
148 149 150
    /**
     * {@inheritdoc}
     */
151 152 153 154 155
    protected function _getPortableTableDefinition($table)
    {
        return $table['name'];
    }

156
    /**
Benjamin Morel's avatar
Benjamin Morel committed
157 158
     * {@inheritdoc}
     *
159 160 161 162 163 164 165 166
     * @license New BSD License
     * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
     */
    protected function _getPortableTableIndexesList($tableIndexes, $tableName=null)
    {
        $indexBuffer = array();

        // fetch primary
Steve Müller's avatar
Steve Müller committed
167
        $stmt = $this->_conn->executeQuery("PRAGMA TABLE_INFO ('$tableName')");
168
        $indexArray = $stmt->fetchAll(\PDO::FETCH_ASSOC);
Steve Müller's avatar
Steve Müller committed
169
        foreach ($indexArray as $indexColumnRow) {
170
            if ($indexColumnRow['pk'] != "0") {
171 172 173 174 175 176 177 178 179 180
                $indexBuffer[] = array(
                    'key_name' => 'primary',
                    'primary' => true,
                    'non_unique' => false,
                    'column_name' => $indexColumnRow['name']
                );
            }
        }

        // fetch regular indexes
Steve Müller's avatar
Steve Müller committed
181
        foreach ($tableIndexes as $tableIndex) {
182 183 184 185 186 187 188
            // Ignore indexes with reserved names, e.g. autoindexes
            if (strpos($tableIndex['name'], 'sqlite_') !== 0) {
                $keyName = $tableIndex['name'];
                $idx = array();
                $idx['key_name'] = $keyName;
                $idx['primary'] = false;
                $idx['non_unique'] = $tableIndex['unique']?false:true;
189

Steve Müller's avatar
Steve Müller committed
190
                $stmt = $this->_conn->executeQuery("PRAGMA INDEX_INFO ('{$keyName}')");
191
                $indexArray = $stmt->fetchAll(\PDO::FETCH_ASSOC);
192

Steve Müller's avatar
Steve Müller committed
193
                foreach ($indexArray as $indexColumnRow) {
194 195 196
                    $idx['column_name'] = $indexColumnRow['name'];
                    $indexBuffer[] = $idx;
                }
197 198 199 200 201 202
            }
        }

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

Benjamin Morel's avatar
Benjamin Morel committed
203 204 205
    /**
     * {@inheritdoc}
     */
206 207 208 209 210 211 212 213
    protected function _getPortableTableIndexDefinition($tableIndex)
    {
        return array(
            'name' => $tableIndex['name'],
            'unique' => (bool) $tableIndex['unique']
        );
    }

Benjamin Morel's avatar
Benjamin Morel committed
214 215 216
    /**
     * {@inheritdoc}
     */
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    protected function _getPortableTableColumnList($table, $database, $tableColumns)
    {
        $list = parent::_getPortableTableColumnList($table, $database, $tableColumns);
        $autoincrementColumn = null;
        $autoincrementCount = 0;
        foreach ($tableColumns as $tableColumn) {
            if ('1' == $tableColumn['pk']) {
                $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);
                }
            }
        }

        return $list;
    }

Benjamin Morel's avatar
Benjamin Morel committed
242 243 244
    /**
     * {@inheritdoc}
     */
245 246 247 248 249 250 251 252 253 254 255 256 257
    protected function _getPortableTableColumnDefinition($tableColumn)
    {
        $e = explode('(', $tableColumn['type']);
        $tableColumn['type'] = $e[0];
        if (isset($e[1])) {
            $length = trim($e[1], ')');
            $tableColumn['length'] = $length;
        }

        $dbType = strtolower($tableColumn['type']);
        $length = isset($tableColumn['length']) ? $tableColumn['length'] : null;
        $unsigned = (boolean) isset($tableColumn['unsigned']) ? $tableColumn['unsigned'] : false;
        $fixed = false;
258
        $type = $this->_platform->getDoctrineTypeMapping($dbType);
259 260 261 262
        $default = $tableColumn['dflt_value'];
        if  ($default == 'NULL') {
            $default = null;
        }
263 264 265 266
        if ($default !== null) {
            // SQLite returns strings wrapped in single quotes, so we need to strip them
            $default = preg_replace("/^'(.*)'$/", '\1', $default);
        }
267 268 269 270 271 272
        $notnull = (bool) $tableColumn['notnull'];

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

273 274 275
        $precision = null;
        $scale = null;

276 277
        switch ($dbType) {
            case 'char':
278
                $fixed = true;
279 280 281 282 283 284
                break;
            case 'float':
            case 'double':
            case 'real':
            case 'decimal':
            case 'numeric':
285
                if (isset($tableColumn['length'])) {
286 287
                    if (strpos($tableColumn['length'], ',') === false) {
                        $tableColumn['length'] .= ",0";
Steve Müller's avatar
Steve Müller committed
288
                    }
289
                    list($precision, $scale) = array_map('trim', explode(',', $tableColumn['length']));
290
                }
291 292 293 294
                $length = null;
                break;
        }

295
        $options = array(
296 297 298 299 300 301 302
            'length'   => $length,
            'unsigned' => (bool) $unsigned,
            'fixed'    => $fixed,
            'notnull'  => $notnull,
            'default'  => $default,
            'precision' => $precision,
            'scale'     => $scale,
303
            'autoincrement' => false,
304
        );
305

306
        return new Column($tableColumn['name'], \Doctrine\DBAL\Types\Type::getType($type), $options);
307
    }
308

Benjamin Morel's avatar
Benjamin Morel committed
309 310 311
    /**
     * {@inheritdoc}
     */
312 313 314 315
    protected function _getPortableViewDefinition($view)
    {
        return new View($view['name'], $view['sql']);
    }
316

Benjamin Morel's avatar
Benjamin Morel committed
317 318 319
    /**
     * {@inheritdoc}
     */
320 321 322
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
    {
        $list = array();
Benjamin Morel's avatar
Benjamin Morel committed
323
        foreach ($tableForeignKeys as $value) {
324
            $value = array_change_key_case($value, CASE_LOWER);
325 326
            $name = $value['constraint_name'];
            if ( ! isset($list[$name])) {
327 328 329 330 331 332 333
                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;
                }

334 335
                $list[$name] = array(
                    'name' => $name,
336 337 338 339 340
                    'local' => array(),
                    'foreign' => array(),
                    'foreignTable' => $value['table'],
                    'onDelete' => $value['on_delete'],
                    'onUpdate' => $value['on_update'],
341 342
                    'deferrable' => $value['deferrable'],
                    'deferred'=> $value['deferred'],
343 344
                );
            }
345 346
            $list[$name]['local'][] = $value['from'];
            $list[$name]['foreign'][] = $value['to'];
347 348 349
        }

        $result = array();
Steve Müller's avatar
Steve Müller committed
350
        foreach ($list as $constraint) {
351 352 353 354 355 356
            $result[] = new ForeignKeyConstraint(
                array_values($constraint['local']), $constraint['foreignTable'],
                array_values($constraint['foreign']), $constraint['name'],
                array(
                    'onDelete' => $constraint['onDelete'],
                    'onUpdate' => $constraint['onUpdate'],
357 358
                    'deferrable' => $constraint['deferrable'],
                    'deferred'=> $constraint['deferred'],
359 360 361 362 363 364 365
                )
            );
        }

        return $result;
    }

Benjamin Morel's avatar
Benjamin Morel committed
366 367 368 369 370 371 372 373
    /**
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey
     * @param \Doctrine\DBAL\Schema\Table|string         $table
     *
     * @return \Doctrine\DBAL\Schema\TableDiff
     *
     * @throws \Doctrine\DBAL\DBALException
     */
374 375 376 377 378
    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
379
                throw new DBALException(sprintf('Sqlite schema manager requires to modify foreign keys table definition "%s".', $table));
380 381 382 383 384 385 386 387 388 389
            }

            $table = $tableDetails;
        }

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

        return $tableDiff;
    }
390
}