AbstractSchemaManager.php 30.4 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\Events;
use Doctrine\DBAL\Event\SchemaColumnDefinitionEventArgs;
24
use Doctrine\DBAL\Event\SchemaIndexDefinitionEventArgs;
25 26
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Platforms\AbstractPlatform;
27

romanb's avatar
romanb committed
28
/**
29
 * Base class for schema managers. Schema managers are used to inspect and/or
30
 * modify the database schema/structure.
romanb's avatar
romanb committed
31
 *
Benjamin Morel's avatar
Benjamin Morel committed
32 33 34 35 36 37
 * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
 * @author Roman Borschel <roman@code-factory.org>
 * @author Jonathan H. Wage <jonwage@gmail.com>
 * @author Benjamin Eberlei <kontakt@beberlei.de>
 * @since  2.0
romanb's avatar
romanb committed
38
 */
39
abstract class AbstractSchemaManager
romanb's avatar
romanb committed
40
{
41
    /**
Benjamin Morel's avatar
Benjamin Morel committed
42
     * Holds instance of the Doctrine connection for this schema manager.
43
     *
44
     * @var \Doctrine\DBAL\Connection
45
     */
romanb's avatar
romanb committed
46 47
    protected $_conn;

48
    /**
Benjamin Morel's avatar
Benjamin Morel committed
49
     * Holds instance of the database platform used for this schema manager.
50
     *
51
     * @var \Doctrine\DBAL\Platforms\AbstractPlatform
52 53 54 55
     */
    protected $_platform;

    /**
Benjamin Morel's avatar
Benjamin Morel committed
56
     * Constructor. Accepts the Connection instance to manage the schema for.
57
     *
Benjamin Morel's avatar
Benjamin Morel committed
58 59
     * @param \Doctrine\DBAL\Connection                      $conn
     * @param \Doctrine\DBAL\Platforms\AbstractPlatform|null $platform
60
     */
61
    public function __construct(\Doctrine\DBAL\Connection $conn, AbstractPlatform $platform = null)
62
    {
63 64
        $this->_conn     = $conn;
        $this->_platform = $platform ?: $this->_conn->getDatabasePlatform();
65 66
    }

67
    /**
Benjamin Morel's avatar
Benjamin Morel committed
68
     * Returns the associated platform.
69
     *
70
     * @return \Doctrine\DBAL\Platforms\AbstractPlatform
71 72 73 74 75 76
     */
    public function getDatabasePlatform()
    {
        return $this->_platform;
    }

77
    /**
Benjamin Morel's avatar
Benjamin Morel committed
78
     * Tries any method on the schema manager. Normally a method throws an
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
     * exception when your DBMS doesn't support it or if an error occurs.
     * This method allows you to try and method on your SchemaManager
     * instance and will return false if it does not work or is not supported.
     *
     * <code>
     * $result = $sm->tryMethod('dropView', 'view_name');
     * </code>
     *
     * @return mixed
     */
    public function tryMethod()
    {
        $args = func_get_args();
        $method = $args[0];
        unset($args[0]);
        $args = array_values($args);

        try {
            return call_user_func_array(array($this, $method), $args);
        } catch (\Exception $e) {
            return false;
        }
    }

romanb's avatar
romanb committed
103
    /**
Benjamin Morel's avatar
Benjamin Morel committed
104
     * Lists the available databases for this connection.
romanb's avatar
romanb committed
105
     *
Benjamin Morel's avatar
Benjamin Morel committed
106
     * @return array
romanb's avatar
romanb committed
107 108 109
     */
    public function listDatabases()
    {
110
        $sql = $this->_platform->getListDatabasesSQL();
111 112 113 114

        $databases = $this->_conn->fetchAll($sql);

        return $this->_getPortableDatabasesList($databases);
romanb's avatar
romanb committed
115 116
    }

117 118 119 120 121 122 123 124 125 126 127 128 129 130
    /**
     * Returns a list of all namespaces in the current database.
     *
     * @return array
     */
    public function listNamespaceNames()
    {
        $sql = $this->_platform->getListNamespacesSQL();

        $namespaces = $this->_conn->fetchAll($sql);

        return $this->getPortableNamespacesList($namespaces);
    }

romanb's avatar
romanb committed
131
    /**
Benjamin Morel's avatar
Benjamin Morel committed
132 133 134
     * Lists the available sequences for this connection.
     *
     * @param string|null $database
romanb's avatar
romanb committed
135
     *
Benjamin Morel's avatar
Benjamin Morel committed
136
     * @return \Doctrine\DBAL\Schema\Sequence[]
romanb's avatar
romanb committed
137
     */
138
    public function listSequences($database = null)
romanb's avatar
romanb committed
139
    {
140 141 142
        if (is_null($database)) {
            $database = $this->_conn->getDatabase();
        }
143
        $sql = $this->_platform->getListSequencesSQL($database);
144 145 146

        $sequences = $this->_conn->fetchAll($sql);

147
        return $this->filterAssetNames($this->_getPortableSequencesList($sequences));
romanb's avatar
romanb committed
148 149 150
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
151
     * Lists the columns for a given table.
romanb's avatar
romanb committed
152
     *
153 154 155 156 157 158 159
     * In contrast to other libraries and to the old version of Doctrine,
     * this column definition does try to contain the 'primary' field for
     * the reason that it is not portable accross different RDBMS. Use
     * {@see listTableIndexes($tableName)} to retrieve the primary key
     * of a table. We're a RDBMS specifies more details these are held
     * in the platformDetails array.
     *
Benjamin Morel's avatar
Benjamin Morel committed
160 161 162 163
     * @param string      $table    The name of the table.
     * @param string|null $database
     *
     * @return \Doctrine\DBAL\Schema\Column[]
romanb's avatar
romanb committed
164
     */
165
    public function listTableColumns($table, $database = null)
romanb's avatar
romanb committed
166
    {
167
        if ( ! $database) {
168 169 170 171
            $database = $this->_conn->getDatabase();
        }

        $sql = $this->_platform->getListTableColumnsSQL($table, $database);
172 173 174

        $tableColumns = $this->_conn->fetchAll($sql);

175
        return $this->_getPortableTableColumnList($table, $database, $tableColumns);
romanb's avatar
romanb committed
176 177 178
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
179
     * Lists the indexes for a given table returning an array of Index instances.
romanb's avatar
romanb committed
180
     *
181 182
     * Keys of the portable indexes list are all lower-cased.
     *
Benjamin Morel's avatar
Benjamin Morel committed
183 184 185
     * @param string $table The name of the table.
     *
     * @return \Doctrine\DBAL\Schema\Index[]
romanb's avatar
romanb committed
186 187 188
     */
    public function listTableIndexes($table)
    {
189
        $sql = $this->_platform->getListTableIndexesSQL($table, $this->_conn->getDatabase());
190 191 192

        $tableIndexes = $this->_conn->fetchAll($sql);

193
        return $this->_getPortableTableIndexesList($tableIndexes, $table);
romanb's avatar
romanb committed
194 195
    }

196
    /**
Benjamin Morel's avatar
Benjamin Morel committed
197
     * Returns true if all the given tables exist.
198
     *
199
     * @param array $tableNames
Benjamin Morel's avatar
Benjamin Morel committed
200 201
     *
     * @return boolean
202 203 204
     */
    public function tablesExist($tableNames)
    {
205
        $tableNames = array_map('strtolower', (array) $tableNames);
Benjamin Morel's avatar
Benjamin Morel committed
206

207 208 209
        return count($tableNames) == count(\array_intersect($tableNames, array_map('strtolower', $this->listTableNames())));
    }

romanb's avatar
romanb committed
210
    /**
Benjamin Morel's avatar
Benjamin Morel committed
211
     * Returns a list of all tables in the current database.
romanb's avatar
romanb committed
212
     *
213
     * @return array
romanb's avatar
romanb committed
214
     */
215
    public function listTableNames()
romanb's avatar
romanb committed
216
    {
217
        $sql = $this->_platform->getListTablesSQL();
218 219

        $tables = $this->_conn->fetchAll($sql);
220
        $tableNames = $this->_getPortableTablesList($tables);
Benjamin Morel's avatar
Benjamin Morel committed
221

222 223
        return $this->filterAssetNames($tableNames);
    }
224

225
    /**
Benjamin Morel's avatar
Benjamin Morel committed
226
     * Filters asset names if they are configured to return only a subset of all
227 228 229
     * the found elements.
     *
     * @param array $assetNames
Benjamin Morel's avatar
Benjamin Morel committed
230
     *
231 232 233 234 235
     * @return array
     */
    protected function filterAssetNames($assetNames)
    {
        $filterExpr = $this->getFilterSchemaAssetsExpression();
236
        if ( ! $filterExpr) {
237 238
            return $assetNames;
        }
Benjamin Morel's avatar
Benjamin Morel committed
239

240
        return array_values(
241 242
            array_filter($assetNames, function ($assetName) use ($filterExpr) {
                $assetName = ($assetName instanceof AbstractAsset) ? $assetName->getName() : $assetName;
243

244
                return preg_match($filterExpr, $assetName);
245 246 247 248
            })
        );
    }

Benjamin Morel's avatar
Benjamin Morel committed
249 250 251
    /**
     * @return string|null
     */
252 253 254
    protected function getFilterSchemaAssetsExpression()
    {
        return $this->_conn->getConfiguration()->getFilterSchemaAssetsExpression();
255 256 257
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
258
     * Lists the tables for this connection.
259
     *
Benjamin Morel's avatar
Benjamin Morel committed
260
     * @return \Doctrine\DBAL\Schema\Table[]
261 262 263 264
     */
    public function listTables()
    {
        $tableNames = $this->listTableNames();
265

266
        $tables = array();
267
        foreach ($tableNames as $tableName) {
268
            $tables[] = $this->listTableDetails($tableName);
269 270 271
        }

        return $tables;
romanb's avatar
romanb committed
272 273
    }

274
    /**
Benjamin Morel's avatar
Benjamin Morel committed
275 276 277
     * @param string $tableName
     *
     * @return \Doctrine\DBAL\Schema\Table
278 279 280 281 282 283 284 285 286 287
     */
    public function listTableDetails($tableName)
    {
        $columns = $this->listTableColumns($tableName);
        $foreignKeys = array();
        if ($this->_platform->supportsForeignKeyConstraints()) {
            $foreignKeys = $this->listTableForeignKeys($tableName);
        }
        $indexes = $this->listTableIndexes($tableName);

288
        return new Table($tableName, $columns, $indexes, $foreignKeys, false, array());
289 290
    }

romanb's avatar
romanb committed
291
    /**
Benjamin Morel's avatar
Benjamin Morel committed
292
     * Lists the views this connection has.
romanb's avatar
romanb committed
293
     *
Benjamin Morel's avatar
Benjamin Morel committed
294
     * @return \Doctrine\DBAL\Schema\View[]
romanb's avatar
romanb committed
295
     */
296
    public function listViews()
romanb's avatar
romanb committed
297
    {
298
        $database = $this->_conn->getDatabase();
299
        $sql = $this->_platform->getListViewsSQL($database);
300 301 302
        $views = $this->_conn->fetchAll($sql);

        return $this->_getPortableViewsList($views);
romanb's avatar
romanb committed
303 304
    }

305
    /**
Benjamin Morel's avatar
Benjamin Morel committed
306 307 308 309
     * Lists the foreign keys for the given table.
     *
     * @param string      $table    The name of the table.
     * @param string|null $database
310
     *
Benjamin Morel's avatar
Benjamin Morel committed
311
     * @return \Doctrine\DBAL\Schema\ForeignKeyConstraint[]
312 313 314 315 316 317
     */
    public function listTableForeignKeys($table, $database = null)
    {
        if (is_null($database)) {
            $database = $this->_conn->getDatabase();
        }
318
        $sql = $this->_platform->getListTableForeignKeysSQL($table, $database);
319 320 321 322 323
        $tableForeignKeys = $this->_conn->fetchAll($sql);

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

324 325
    /* drop*() Methods */

romanb's avatar
romanb committed
326
    /**
327
     * Drops a database.
328
     *
329
     * NOTE: You can not drop the database this SchemaManager is currently connected to.
romanb's avatar
romanb committed
330
     *
Benjamin Morel's avatar
Benjamin Morel committed
331 332 333
     * @param string $database The name of the database to drop.
     *
     * @return void
romanb's avatar
romanb committed
334
     */
335
    public function dropDatabase($database)
romanb's avatar
romanb committed
336
    {
337
        $this->_execSql($this->_platform->getDropDatabaseSQL($database));
romanb's avatar
romanb committed
338 339 340
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
341 342
     * Drops the given table.
     *
jeroendedauw's avatar
jeroendedauw committed
343
     * @param string $tableName The name of the table to drop.
romanb's avatar
romanb committed
344
     *
Benjamin Morel's avatar
Benjamin Morel committed
345
     * @return void
romanb's avatar
romanb committed
346
     */
jeroendedauw's avatar
jeroendedauw committed
347
    public function dropTable($tableName)
romanb's avatar
romanb committed
348
    {
jeroendedauw's avatar
jeroendedauw committed
349
        $this->_execSql($this->_platform->getDropTableSQL($tableName));
romanb's avatar
romanb committed
350 351 352
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
353
     * Drops the index from the given table.
romanb's avatar
romanb committed
354
     *
Benjamin Morel's avatar
Benjamin Morel committed
355 356 357 358
     * @param \Doctrine\DBAL\Schema\Index|string $index The name of the index.
     * @param \Doctrine\DBAL\Schema\Table|string $table The name of the table.
     *
     * @return void
romanb's avatar
romanb committed
359
     */
360
    public function dropIndex($index, $table)
romanb's avatar
romanb committed
361
    {
Steve Müller's avatar
Steve Müller committed
362
        if ($index instanceof Index) {
363
            $index = $index->getQuotedName($this->_platform);
364 365
        }

366
        $this->_execSql($this->_platform->getDropIndexSQL($index, $table));
romanb's avatar
romanb committed
367 368 369
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
370 371 372 373
     * Drops the constraint from the given table.
     *
     * @param \Doctrine\DBAL\Schema\Constraint   $constraint
     * @param \Doctrine\DBAL\Schema\Table|string $table      The name of the table.
romanb's avatar
romanb committed
374
     *
Benjamin Morel's avatar
Benjamin Morel committed
375
     * @return void
romanb's avatar
romanb committed
376
     */
377
    public function dropConstraint(Constraint $constraint, $table)
romanb's avatar
romanb committed
378
    {
379
        $this->_execSql($this->_platform->getDropConstraintSQL($constraint, $table));
romanb's avatar
romanb committed
380 381 382
    }

    /**
romanb's avatar
romanb committed
383
     * Drops a foreign key from a table.
romanb's avatar
romanb committed
384
     *
Benjamin Morel's avatar
Benjamin Morel committed
385 386 387 388
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint|string $foreignKey The name of the foreign key.
     * @param \Doctrine\DBAL\Schema\Table|string                $table      The name of the table with the foreign key.
     *
     * @return void
romanb's avatar
romanb committed
389
     */
390
    public function dropForeignKey($foreignKey, $table)
romanb's avatar
romanb committed
391
    {
392
        $this->_execSql($this->_platform->getDropForeignKeySQL($foreignKey, $table));
romanb's avatar
romanb committed
393 394 395
    }

    /**
romanb's avatar
romanb committed
396
     * Drops a sequence with a given name.
romanb's avatar
romanb committed
397
     *
romanb's avatar
romanb committed
398
     * @param string $name The name of the sequence to drop.
Benjamin Morel's avatar
Benjamin Morel committed
399 400
     *
     * @return void
romanb's avatar
romanb committed
401
     */
402
    public function dropSequence($name)
romanb's avatar
romanb committed
403
    {
404
        $this->_execSql($this->_platform->getDropSequenceSQL($name));
romanb's avatar
romanb committed
405 406
    }

407
    /**
Benjamin Morel's avatar
Benjamin Morel committed
408
     * Drops a view.
409
     *
Benjamin Morel's avatar
Benjamin Morel committed
410 411 412
     * @param string $name The name of the view.
     *
     * @return void
413 414 415
     */
    public function dropView($name)
    {
416
        $this->_execSql($this->_platform->getDropViewSQL($name));
417 418 419 420
    }

    /* create*() Methods */

romanb's avatar
romanb committed
421
    /**
romanb's avatar
romanb committed
422
     * Creates a new database.
romanb's avatar
romanb committed
423
     *
romanb's avatar
romanb committed
424
     * @param string $database The name of the database to create.
Benjamin Morel's avatar
Benjamin Morel committed
425 426
     *
     * @return void
romanb's avatar
romanb committed
427
     */
romanb's avatar
romanb committed
428
    public function createDatabase($database)
romanb's avatar
romanb committed
429
    {
430
        $this->_execSql($this->_platform->getCreateDatabaseSQL($database));
romanb's avatar
romanb committed
431 432 433
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
434
     * Creates a new table.
romanb's avatar
romanb committed
435
     *
Benjamin Morel's avatar
Benjamin Morel committed
436 437 438
     * @param \Doctrine\DBAL\Schema\Table $table
     *
     * @return void
romanb's avatar
romanb committed
439
     */
440
    public function createTable(Table $table)
romanb's avatar
romanb committed
441
    {
442
        $createFlags = AbstractPlatform::CREATE_INDEXES|AbstractPlatform::CREATE_FOREIGNKEYS;
443
        $this->_execSql($this->_platform->getCreateTableSQL($table, $createFlags));
romanb's avatar
romanb committed
444 445 446
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
447 448 449
     * Creates a new sequence.
     *
     * @param \Doctrine\DBAL\Schema\Sequence $sequence
romanb's avatar
romanb committed
450
     *
Benjamin Morel's avatar
Benjamin Morel committed
451 452 453
     * @return void
     *
     * @throws \Doctrine\DBAL\ConnectionException If something fails at database level.
romanb's avatar
romanb committed
454
     */
455
    public function createSequence($sequence)
romanb's avatar
romanb committed
456
    {
457
        $this->_execSql($this->_platform->getCreateSequenceSQL($sequence));
romanb's avatar
romanb committed
458 459 460
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
461 462 463 464
     * Creates a constraint on a table.
     *
     * @param \Doctrine\DBAL\Schema\Constraint   $constraint
     * @param \Doctrine\DBAL\Schema\Table|string $table
romanb's avatar
romanb committed
465
     *
Benjamin Morel's avatar
Benjamin Morel committed
466
     * @return void
467 468
     */
    public function createConstraint(Constraint $constraint, $table)
romanb's avatar
romanb committed
469
    {
470
        $this->_execSql($this->_platform->getCreateConstraintSQL($constraint, $table));
romanb's avatar
romanb committed
471 472 473
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
474
     * Creates a new index on a table.
romanb's avatar
romanb committed
475
     *
Benjamin Morel's avatar
Benjamin Morel committed
476 477 478 479
     * @param \Doctrine\DBAL\Schema\Index        $index
     * @param \Doctrine\DBAL\Schema\Table|string $table The name of the table on which the index is to be created.
     *
     * @return void
romanb's avatar
romanb committed
480
     */
481
    public function createIndex(Index $index, $table)
romanb's avatar
romanb committed
482
    {
483
        $this->_execSql($this->_platform->getCreateIndexSQL($index, $table));
romanb's avatar
romanb committed
484 485 486
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
487 488 489 490
     * Creates a new foreign key.
     *
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey The ForeignKey instance.
     * @param \Doctrine\DBAL\Schema\Table|string         $table      The name of the table on which the foreign key is to be created.
romanb's avatar
romanb committed
491
     *
Benjamin Morel's avatar
Benjamin Morel committed
492
     * @return void
romanb's avatar
romanb committed
493
     */
494
    public function createForeignKey(ForeignKeyConstraint $foreignKey, $table)
romanb's avatar
romanb committed
495
    {
496
        $this->_execSql($this->_platform->getCreateForeignKeySQL($foreignKey, $table));
romanb's avatar
romanb committed
497 498
    }

499
    /**
Benjamin Morel's avatar
Benjamin Morel committed
500
     * Creates a new view.
501
     *
Benjamin Morel's avatar
Benjamin Morel committed
502 503 504
     * @param \Doctrine\DBAL\Schema\View $view
     *
     * @return void
505
     */
506
    public function createView(View $view)
507
    {
508
        $this->_execSql($this->_platform->getCreateViewSQL($view->getQuotedName($this->_platform), $view->getSql()));
509 510
    }

511 512
    /* dropAndCreate*() Methods */

513
    /**
Benjamin Morel's avatar
Benjamin Morel committed
514
     * Drops and creates a constraint.
515 516 517
     *
     * @see dropConstraint()
     * @see createConstraint()
Benjamin Morel's avatar
Benjamin Morel committed
518 519 520 521 522
     *
     * @param \Doctrine\DBAL\Schema\Constraint   $constraint
     * @param \Doctrine\DBAL\Schema\Table|string $table
     *
     * @return void
523
     */
524
    public function dropAndCreateConstraint(Constraint $constraint, $table)
525
    {
526 527
        $this->tryMethod('dropConstraint', $constraint, $table);
        $this->createConstraint($constraint, $table);
528 529 530
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
531 532 533 534
     * Drops and creates a new index on a table.
     *
     * @param \Doctrine\DBAL\Schema\Index        $index
     * @param \Doctrine\DBAL\Schema\Table|string $table The name of the table on which the index is to be created.
535
     *
Benjamin Morel's avatar
Benjamin Morel committed
536
     * @return void
537
     */
538
    public function dropAndCreateIndex(Index $index, $table)
539
    {
540
        $this->tryMethod('dropIndex', $index->getQuotedName($this->_platform), $table);
541
        $this->createIndex($index, $table);
542 543 544
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
545
     * Drops and creates a new foreign key.
546
     *
Benjamin Morel's avatar
Benjamin Morel committed
547 548 549 550
     * @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey An associative array that defines properties of the foreign key to be created.
     * @param \Doctrine\DBAL\Schema\Table|string         $table      The name of the table on which the foreign key is to be created.
     *
     * @return void
551
     */
552
    public function dropAndCreateForeignKey(ForeignKeyConstraint $foreignKey, $table)
553
    {
554 555
        $this->tryMethod('dropForeignKey', $foreignKey, $table);
        $this->createForeignKey($foreignKey, $table);
556 557 558
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
559 560 561
     * Drops and create a new sequence.
     *
     * @param \Doctrine\DBAL\Schema\Sequence $sequence
562
     *
Benjamin Morel's avatar
Benjamin Morel committed
563 564 565
     * @return void
     *
     * @throws \Doctrine\DBAL\ConnectionException If something fails at database level.
566
     */
567
    public function dropAndCreateSequence(Sequence $sequence)
568
    {
Benjamin Eberlei's avatar
Benjamin Eberlei committed
569 570
        $this->tryMethod('dropSequence', $sequence->getQuotedName($this->_platform));
        $this->createSequence($sequence);
571 572 573
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
574 575 576
     * Drops and creates a new table.
     *
     * @param \Doctrine\DBAL\Schema\Table $table
577
     *
Benjamin Morel's avatar
Benjamin Morel committed
578
     * @return void
579
     */
580
    public function dropAndCreateTable(Table $table)
581
    {
582
        $this->tryMethod('dropTable', $table->getQuotedName($this->_platform));
583
        $this->createTable($table);
584 585 586
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
587
     * Drops and creates a new database.
588 589
     *
     * @param string $database The name of the database to create.
Benjamin Morel's avatar
Benjamin Morel committed
590 591
     *
     * @return void
592 593 594 595 596 597 598 599
     */
    public function dropAndCreateDatabase($database)
    {
        $this->tryMethod('dropDatabase', $database);
        $this->createDatabase($database);
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
600 601 602
     * Drops and creates a new view.
     *
     * @param \Doctrine\DBAL\Schema\View $view
603
     *
Benjamin Morel's avatar
Benjamin Morel committed
604
     * @return void
605
     */
606
    public function dropAndCreateView(View $view)
607
    {
608
        $this->tryMethod('dropView', $view->getQuotedName($this->_platform));
609
        $this->createView($view);
610 611
    }

612 613
    /* alterTable() Methods */

romanb's avatar
romanb committed
614
    /**
Benjamin Morel's avatar
Benjamin Morel committed
615
     * Alters an existing tables schema.
romanb's avatar
romanb committed
616
     *
Benjamin Morel's avatar
Benjamin Morel committed
617 618 619
     * @param \Doctrine\DBAL\Schema\TableDiff $tableDiff
     *
     * @return void
620 621 622
     */
    public function alterTable(TableDiff $tableDiff)
    {
623
        $queries = $this->_platform->getAlterTableSQL($tableDiff);
624
        if (is_array($queries) && count($queries)) {
625
            foreach ($queries as $ddlQuery) {
626 627
                $this->_execSql($ddlQuery);
            }
628
        }
629 630
    }

631
    /**
Benjamin Morel's avatar
Benjamin Morel committed
632 633 634 635
     * Renames a given table to another name.
     *
     * @param string $name    The current name of the table.
     * @param string $newName The new name of the table.
636
     *
Benjamin Morel's avatar
Benjamin Morel committed
637
     * @return void
638 639 640
     */
    public function renameTable($name, $newName)
    {
641 642 643
        $tableDiff = new TableDiff($name);
        $tableDiff->newName = $newName;
        $this->alterTable($tableDiff);
644 645
    }

646 647 648 649 650
    /**
     * Methods for filtering return values of list*() methods to convert
     * the native DBMS data definition to a portable Doctrine definition
     */

Benjamin Morel's avatar
Benjamin Morel committed
651 652 653 654 655
    /**
     * @param array $databases
     *
     * @return array
     */
656 657
    protected function _getPortableDatabasesList($databases)
    {
658
        $list = array();
659
        foreach ($databases as $value) {
660 661 662
            if ($value = $this->_getPortableDatabaseDefinition($value)) {
                $list[] = $value;
            }
663
        }
Benjamin Morel's avatar
Benjamin Morel committed
664

665
        return $list;
666 667
    }

668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
    /**
     * Converts a list of namespace names from the native DBMS data definition to a portable Doctrine definition.
     *
     * @param array $namespaces The list of namespace names in the native DBMS data definition.
     *
     * @return array
     */
    protected function getPortableNamespacesList(array $namespaces)
    {
        $namespacesList = array();

        foreach ($namespaces as $namespace) {
            $namespacesList[] = $this->getPortableNamespaceDefinition($namespace);
        }

        return $namespacesList;
    }

Benjamin Morel's avatar
Benjamin Morel committed
686 687 688 689 690
    /**
     * @param array $database
     *
     * @return mixed
     */
691 692 693 694 695
    protected function _getPortableDatabaseDefinition($database)
    {
        return $database;
    }

696 697 698 699 700 701 702 703 704 705 706 707
    /**
     * Converts a namespace definition from the native DBMS data definition to a portable Doctrine definition.
     *
     * @param array $namespace The native DBMS namespace definition.
     *
     * @return mixed
     */
    protected function getPortableNamespaceDefinition(array $namespace)
    {
        return $namespace;
    }

Benjamin Morel's avatar
Benjamin Morel committed
708 709 710 711 712
    /**
     * @param array $functions
     *
     * @return array
     */
713 714
    protected function _getPortableFunctionsList($functions)
    {
715
        $list = array();
716
        foreach ($functions as $value) {
717 718 719
            if ($value = $this->_getPortableFunctionDefinition($value)) {
                $list[] = $value;
            }
720
        }
Benjamin Morel's avatar
Benjamin Morel committed
721

722
        return $list;
723 724
    }

Benjamin Morel's avatar
Benjamin Morel committed
725 726 727 728 729
    /**
     * @param array $function
     *
     * @return mixed
     */
730 731 732 733 734
    protected function _getPortableFunctionDefinition($function)
    {
        return $function;
    }

Benjamin Morel's avatar
Benjamin Morel committed
735 736 737 738 739
    /**
     * @param array $triggers
     *
     * @return array
     */
740 741
    protected function _getPortableTriggersList($triggers)
    {
742
        $list = array();
743
        foreach ($triggers as $value) {
744 745 746
            if ($value = $this->_getPortableTriggerDefinition($value)) {
                $list[] = $value;
            }
747
        }
Benjamin Morel's avatar
Benjamin Morel committed
748

749
        return $list;
750 751
    }

Benjamin Morel's avatar
Benjamin Morel committed
752 753 754 755 756
    /**
     * @param array $trigger
     *
     * @return mixed
     */
757 758 759 760 761
    protected function _getPortableTriggerDefinition($trigger)
    {
        return $trigger;
    }

Benjamin Morel's avatar
Benjamin Morel committed
762 763 764 765 766
    /**
     * @param array $sequences
     *
     * @return array
     */
767 768
    protected function _getPortableSequencesList($sequences)
    {
769
        $list = array();
770
        foreach ($sequences as $value) {
771 772 773
            if ($value = $this->_getPortableSequenceDefinition($value)) {
                $list[] = $value;
            }
774
        }
Benjamin Morel's avatar
Benjamin Morel committed
775

776
        return $list;
777 778
    }

779 780
    /**
     * @param array $sequence
Benjamin Morel's avatar
Benjamin Morel committed
781 782 783 784
     *
     * @return \Doctrine\DBAL\Schema\Sequence
     *
     * @throws \Doctrine\DBAL\DBALException
785
     */
786 787
    protected function _getPortableSequenceDefinition($sequence)
    {
788
        throw DBALException::notSupported('Sequences');
789 790
    }

791 792 793 794 795
    /**
     * Independent of the database the keys of the column list result are lowercased.
     *
     * The name of the created column instance however is kept in its case.
     *
Benjamin Morel's avatar
Benjamin Morel committed
796 797 798 799
     * @param string $table        The name of the table.
     * @param string $database
     * @param array  $tableColumns
     *
800 801
     * @return array
     */
802
    protected function _getPortableTableColumnList($table, $database, $tableColumns)
803
    {
804 805
        $eventManager = $this->_platform->getEventManager();

806
        $list = array();
807
        foreach ($tableColumns as $tableColumn) {
808
            $column = null;
809 810 811
            $defaultPrevented = false;

            if (null !== $eventManager && $eventManager->hasListeners(Events::onSchemaColumnDefinition)) {
812
                $eventArgs = new SchemaColumnDefinitionEventArgs($tableColumn, $table, $database, $this->_conn);
813 814 815
                $eventManager->dispatchEvent(Events::onSchemaColumnDefinition, $eventArgs);

                $defaultPrevented = $eventArgs->isDefaultPrevented();
816
                $column = $eventArgs->getColumn();
817 818
            }

819
            if ( ! $defaultPrevented) {
820
                $column = $this->_getPortableTableColumnDefinition($tableColumn);
821 822
            }

823 824 825
            if ($column) {
                $name = strtolower($column->getQuotedName($this->_platform));
                $list[$name] = $column;
826
            }
827
        }
Benjamin Morel's avatar
Benjamin Morel committed
828

829
        return $list;
830 831
    }

832
    /**
Benjamin Morel's avatar
Benjamin Morel committed
833
     * Gets Table Column Definition.
834 835
     *
     * @param array $tableColumn
Benjamin Morel's avatar
Benjamin Morel committed
836 837
     *
     * @return \Doctrine\DBAL\Schema\Column
838 839
     */
    abstract protected function _getPortableTableColumnDefinition($tableColumn);
840

841
    /**
Benjamin Morel's avatar
Benjamin Morel committed
842 843 844 845
     * Aggregates and groups the index results according to the required data result.
     *
     * @param array       $tableIndexRows
     * @param string|null $tableName
846 847 848
     *
     * @return array
     */
849
    protected function _getPortableTableIndexesList($tableIndexRows, $tableName=null)
850
    {
851
        $result = array();
Steve Müller's avatar
Steve Müller committed
852
        foreach ($tableIndexRows as $tableIndex) {
853
            $indexName = $keyName = $tableIndex['key_name'];
Steve Müller's avatar
Steve Müller committed
854
            if ($tableIndex['primary']) {
855 856
                $keyName = 'primary';
            }
857
            $keyName = strtolower($keyName);
858

Steve Müller's avatar
Steve Müller committed
859
            if (!isset($result[$keyName])) {
860 861 862 863 864
                $result[$keyName] = array(
                    'name' => $indexName,
                    'columns' => array($tableIndex['column_name']),
                    'unique' => $tableIndex['non_unique'] ? false : true,
                    'primary' => $tableIndex['primary'],
865
                    'flags' => isset($tableIndex['flags']) ? $tableIndex['flags'] : array(),
866
                    'options' => isset($tableIndex['where']) ? array('where' => $tableIndex['where']) : array(),
867 868 869
                );
            } else {
                $result[$keyName]['columns'][] = $tableIndex['column_name'];
870
            }
871
        }
872

873 874
        $eventManager = $this->_platform->getEventManager();

875
        $indexes = array();
Steve Müller's avatar
Steve Müller committed
876
        foreach ($result as $indexKey => $data) {
877 878 879 880 881 882 883 884 885 886 887
            $index = null;
            $defaultPrevented = false;

            if (null !== $eventManager && $eventManager->hasListeners(Events::onSchemaIndexDefinition)) {
                $eventArgs = new SchemaIndexDefinitionEventArgs($data, $tableName, $this->_conn);
                $eventManager->dispatchEvent(Events::onSchemaIndexDefinition, $eventArgs);

                $defaultPrevented = $eventArgs->isDefaultPrevented();
                $index = $eventArgs->getIndex();
            }

888
            if ( ! $defaultPrevented) {
889
                $index = new Index($data['name'], $data['columns'], $data['unique'], $data['primary'], $data['flags'], $data['options']);
890 891 892 893 894
            }

            if ($index) {
                $indexes[$indexKey] = $index;
            }
895 896 897
        }

        return $indexes;
898 899
    }

Benjamin Morel's avatar
Benjamin Morel committed
900 901 902 903 904
    /**
     * @param array $tables
     *
     * @return array
     */
905 906
    protected function _getPortableTablesList($tables)
    {
907
        $list = array();
908
        foreach ($tables as $value) {
909 910 911
            if ($value = $this->_getPortableTableDefinition($value)) {
                $list[] = $value;
            }
912
        }
Benjamin Morel's avatar
Benjamin Morel committed
913

914
        return $list;
915 916
    }

Benjamin Morel's avatar
Benjamin Morel committed
917 918 919 920 921
    /**
     * @param array $table
     *
     * @return array
     */
922 923 924 925 926
    protected function _getPortableTableDefinition($table)
    {
        return $table;
    }

Benjamin Morel's avatar
Benjamin Morel committed
927 928 929 930 931
    /**
     * @param array $users
     *
     * @return array
     */
932 933
    protected function _getPortableUsersList($users)
    {
934
        $list = array();
935
        foreach ($users as $value) {
936 937 938
            if ($value = $this->_getPortableUserDefinition($value)) {
                $list[] = $value;
            }
939
        }
Benjamin Morel's avatar
Benjamin Morel committed
940

941
        return $list;
942 943
    }

Benjamin Morel's avatar
Benjamin Morel committed
944 945 946 947 948
    /**
     * @param array $user
     *
     * @return mixed
     */
949 950 951 952 953
    protected function _getPortableUserDefinition($user)
    {
        return $user;
    }

Benjamin Morel's avatar
Benjamin Morel committed
954 955
    /**
     * @param array $views
956
     *
Benjamin Morel's avatar
Benjamin Morel committed
957 958
     * @return array
     */
959 960
    protected function _getPortableViewsList($views)
    {
961
        $list = array();
962
        foreach ($views as $value) {
963
            if ($view = $this->_getPortableViewDefinition($value)) {
964
                $viewName = strtolower($view->getQuotedName($this->_platform));
965
                $list[$viewName] = $view;
966
            }
967
        }
Benjamin Morel's avatar
Benjamin Morel committed
968

969
        return $list;
970 971
    }

Benjamin Morel's avatar
Benjamin Morel committed
972 973 974 975 976
    /**
     * @param array $view
     *
     * @return mixed
     */
977 978
    protected function _getPortableViewDefinition($view)
    {
979
        return false;
980 981
    }

Benjamin Morel's avatar
Benjamin Morel committed
982 983 984 985 986
    /**
     * @param array $tableForeignKeys
     *
     * @return array
     */
987 988 989
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
    {
        $list = array();
990
        foreach ($tableForeignKeys as $value) {
991 992 993 994
            if ($value = $this->_getPortableTableForeignKeyDefinition($value)) {
                $list[] = $value;
            }
        }
Benjamin Morel's avatar
Benjamin Morel committed
995

996 997 998
        return $list;
    }

Benjamin Morel's avatar
Benjamin Morel committed
999 1000 1001 1002 1003
    /**
     * @param array $tableForeignKey
     *
     * @return mixed
     */
1004 1005 1006 1007
    protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
    {
        return $tableForeignKey;
    }
1008

Benjamin Morel's avatar
Benjamin Morel committed
1009 1010 1011 1012 1013
    /**
     * @param array|string $sql
     *
     * @return void
     */
romanb's avatar
romanb committed
1014
    protected function _execSql($sql)
1015 1016
    {
        foreach ((array) $sql as $query) {
1017
            $this->_conn->executeUpdate($query);
romanb's avatar
romanb committed
1018 1019
        }
    }
1020 1021

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1022
     * Creates a schema instance for the current database.
1023
     *
Benjamin Morel's avatar
Benjamin Morel committed
1024
     * @return \Doctrine\DBAL\Schema\Schema
1025 1026 1027
     */
    public function createSchema()
    {
1028 1029 1030 1031 1032 1033
        $namespaces = array();

        if ($this->_platform->supportsSchemas()) {
            $namespaces = $this->listNamespaceNames();
        }

1034
        $sequences = array();
1035

Steve Müller's avatar
Steve Müller committed
1036
        if ($this->_platform->supportsSequences()) {
1037 1038
            $sequences = $this->listSequences();
        }
1039

1040 1041
        $tables = $this->listTables();

1042
        return new Schema($tables, $sequences, $this->createSchemaConfig(), $namespaces);
1043 1044 1045
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1046
     * Creates the configuration for this schema.
1047
     *
Benjamin Morel's avatar
Benjamin Morel committed
1048
     * @return \Doctrine\DBAL\Schema\SchemaConfig
1049 1050 1051 1052 1053
     */
    public function createSchemaConfig()
    {
        $schemaConfig = new SchemaConfig();
        $schemaConfig->setMaxIdentifierLength($this->_platform->getMaxIdentifierLength());
1054 1055 1056 1057 1058

        $searchPaths = $this->getSchemaSearchPaths();
        if (isset($searchPaths[0])) {
            $schemaConfig->setName($searchPaths[0]);
        }
1059

1060 1061
        $params = $this->_conn->getParams();
        if (isset($params['defaultTableOptions'])) {
1062
            $schemaConfig->setDefaultTableOptions($params['defaultTableOptions']);
1063 1064
        }

1065
        return $schemaConfig;
1066
    }
1067

1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
    /**
     * The search path for namespaces in the currently connected database.
     *
     * The first entry is usually the default namespace in the Schema. All
     * further namespaces contain tables/sequences which can also be addressed
     * with a short, not full-qualified name.
     *
     * For databases that don't support subschema/namespaces this method
     * returns the name of the currently connected database.
     *
     * @return array
     */
1080 1081 1082 1083 1084
    public function getSchemaSearchPaths()
    {
        return array($this->_conn->getDatabase());
    }

1085 1086 1087
    /**
     * Given a table comment this method tries to extract a typehint for Doctrine Type, or returns
     * the type given as default.
1088
     *
Benjamin Morel's avatar
Benjamin Morel committed
1089 1090 1091
     * @param string $comment
     * @param string $currentType
     *
1092 1093 1094 1095
     * @return string
     */
    public function extractDoctrineTypeFromComment($comment, $currentType)
    {
1096
        if (preg_match("(\(DC2Type:([a-zA-Z0-9_]+)\))", $comment, $match)) {
1097 1098
            $currentType = $match[1];
        }
Benjamin Morel's avatar
Benjamin Morel committed
1099

1100 1101 1102
        return $currentType;
    }

Benjamin Morel's avatar
Benjamin Morel committed
1103 1104 1105 1106 1107 1108
    /**
     * @param string $comment
     * @param string $type
     *
     * @return string
     */
1109 1110 1111 1112
    public function removeDoctrineTypeFromComment($comment, $type)
    {
        return str_replace('(DC2Type:'.$type.')', '', $comment);
    }
Benjamin Eberlei's avatar
Benjamin Eberlei committed
1113
}