AbstractSchemaManager.php 26 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 27
use Doctrine\DBAL\Types;
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Platforms\AbstractPlatform;
28

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

50 51 52
    /**
     * Holds instance of the database platform used for this schema manager
     *
53
     * @var \Doctrine\DBAL\Platforms\AbstractPlatform
54 55 56 57 58 59
     */
    protected $_platform;

    /**
     * Constructor. Accepts the Connection instance to manage the schema for
     *
60
     * @param \Doctrine\DBAL\Connection $conn
61
     */
62
    public function __construct(\Doctrine\DBAL\Connection $conn, AbstractPlatform $platform = null)
63
    {
64 65
        $this->_conn     = $conn;
        $this->_platform = $platform ?: $this->_conn->getDatabasePlatform();
66 67
    }

68 69 70
    /**
     * Return associated platform.
     *
71
     * @return \Doctrine\DBAL\Platforms\AbstractPlatform
72 73 74 75 76 77
     */
    public function getDatabasePlatform()
    {
        return $this->_platform;
    }

78
    /**
79
     * Try any method on the schema manager. Normally a method throws an
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
     * 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
104
    /**
105
     * List the available databases for this connection
romanb's avatar
romanb committed
106
     *
107
     * @return array $databases
romanb's avatar
romanb committed
108 109 110
     */
    public function listDatabases()
    {
111
        $sql = $this->_platform->getListDatabasesSQL();
112 113 114 115

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

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

    /**
119
     * List the available sequences for this connection
romanb's avatar
romanb committed
120
     *
121
     * @return Sequence[]
romanb's avatar
romanb committed
122
     */
123
    public function listSequences($database = null)
romanb's avatar
romanb committed
124
    {
125 126 127
        if (is_null($database)) {
            $database = $this->_conn->getDatabase();
        }
128
        $sql = $this->_platform->getListSequencesSQL($database);
129 130 131

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

132
        return $this->filterAssetNames($this->_getPortableSequencesList($sequences));
romanb's avatar
romanb committed
133 134 135
    }

    /**
136
     * List the columns for a given table.
romanb's avatar
romanb committed
137
     *
138 139 140 141 142 143 144
     * 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.
     *
145
     * @param string $table The name of the table.
146
     * @param string $database
147
     * @return Column[]
romanb's avatar
romanb committed
148
     */
149
    public function listTableColumns($table, $database = null)
romanb's avatar
romanb committed
150
    {
151
        if ( ! $database) {
152 153 154 155
            $database = $this->_conn->getDatabase();
        }

        $sql = $this->_platform->getListTableColumnsSQL($table, $database);
156 157 158

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

159
        return $this->_getPortableTableColumnList($table, $database, $tableColumns);
romanb's avatar
romanb committed
160 161 162
    }

    /**
163
     * List the indexes for a given table returning an array of Index instances.
romanb's avatar
romanb committed
164
     *
165 166
     * Keys of the portable indexes list are all lower-cased.
     *
167
     * @param string $table The name of the table
168
     * @return Index[] $tableIndexes
romanb's avatar
romanb committed
169 170 171
     */
    public function listTableIndexes($table)
    {
172
        $sql = $this->_platform->getListTableIndexesSQL($table, $this->_conn->getDatabase());
173 174 175

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

176
        return $this->_getPortableTableIndexesList($tableIndexes, $table);
romanb's avatar
romanb committed
177 178
    }

179 180
    /**
     * Return true if all the given tables exist.
181
     *
182 183 184 185 186 187 188 189 190
     * @param array $tableNames
     * @return bool
     */
    public function tablesExist($tableNames)
    {
        $tableNames = array_map('strtolower', (array)$tableNames);
        return count($tableNames) == count(\array_intersect($tableNames, array_map('strtolower', $this->listTableNames())));
    }

romanb's avatar
romanb committed
191
    /**
192
     * Return a list of all tables in the current database
romanb's avatar
romanb committed
193
     *
194
     * @return array
romanb's avatar
romanb committed
195
     */
196
    public function listTableNames()
romanb's avatar
romanb committed
197
    {
198
        $sql = $this->_platform->getListTablesSQL();
199 200

        $tables = $this->_conn->fetchAll($sql);
201 202 203
        $tableNames = $this->_getPortableTablesList($tables);
        return $this->filterAssetNames($tableNames);
    }
204

205 206 207 208 209 210 211 212 213 214
    /**
     * Filter asset names if they are configured to return only a subset of all
     * the found elements.
     *
     * @param array $assetNames
     * @return array
     */
    protected function filterAssetNames($assetNames)
    {
        $filterExpr = $this->getFilterSchemaAssetsExpression();
215
        if ( ! $filterExpr) {
216 217 218 219 220
            return $assetNames;
        }
        return array_values (
            array_filter($assetNames, function ($assetName) use ($filterExpr) {
                $assetName = ($assetName instanceof AbstractAsset) ? $assetName->getName() : $assetName;
221
                return preg_match($filterExpr, $assetName);
222 223 224 225 226 227 228
            })
        );
    }

    protected function getFilterSchemaAssetsExpression()
    {
        return $this->_conn->getConfiguration()->getFilterSchemaAssetsExpression();
229 230 231 232 233 234 235 236 237 238
    }

    /**
     * List the tables for this connection
     *
     * @return Table[]
     */
    public function listTables()
    {
        $tableNames = $this->listTableNames();
239

240
        $tables = array();
241
        foreach ($tableNames as $tableName) {
242
            $tables[] = $this->listTableDetails($tableName);
243 244 245
        }

        return $tables;
romanb's avatar
romanb committed
246 247
    }

248 249 250 251 252 253 254 255 256 257 258 259 260
    /**
     * @param  string $tableName
     * @return Table
     */
    public function listTableDetails($tableName)
    {
        $columns = $this->listTableColumns($tableName);
        $foreignKeys = array();
        if ($this->_platform->supportsForeignKeyConstraints()) {
            $foreignKeys = $this->listTableForeignKeys($tableName);
        }
        $indexes = $this->listTableIndexes($tableName);

261
        return new Table($tableName, $columns, $indexes, $foreignKeys, false, array());
262 263
    }

romanb's avatar
romanb committed
264
    /**
265
     * List the views this connection has
romanb's avatar
romanb committed
266
     *
267
     * @return View[]
romanb's avatar
romanb committed
268
     */
269
    public function listViews()
romanb's avatar
romanb committed
270
    {
271
        $database = $this->_conn->getDatabase();
272
        $sql = $this->_platform->getListViewsSQL($database);
273 274 275
        $views = $this->_conn->fetchAll($sql);

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

278 279 280 281
    /**
     * List the foreign keys for the given table
     *
     * @param string $table  The name of the table
282
     * @return ForeignKeyConstraint[]
283 284 285 286 287 288
     */
    public function listTableForeignKeys($table, $database = null)
    {
        if (is_null($database)) {
            $database = $this->_conn->getDatabase();
        }
289
        $sql = $this->_platform->getListTableForeignKeysSQL($table, $database);
290 291 292 293 294
        $tableForeignKeys = $this->_conn->fetchAll($sql);

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

295 296
    /* drop*() Methods */

romanb's avatar
romanb committed
297
    /**
298
     * Drops a database.
299
     *
300
     * NOTE: You can not drop the database this SchemaManager is currently connected to.
romanb's avatar
romanb committed
301
     *
302
     * @param string $database The name of the database to drop
romanb's avatar
romanb committed
303
     */
304
    public function dropDatabase($database)
romanb's avatar
romanb committed
305
    {
306
        $this->_execSql($this->_platform->getDropDatabaseSQL($database));
romanb's avatar
romanb committed
307 308 309
    }

    /**
310
     * Drop the given table
romanb's avatar
romanb committed
311
     *
312
     * @param string $table The name of the table to drop
romanb's avatar
romanb committed
313 314 315
     */
    public function dropTable($table)
    {
316
        $this->_execSql($this->_platform->getDropTableSQL($table));
romanb's avatar
romanb committed
317 318 319
    }

    /**
320
     * Drop the index from the given table
romanb's avatar
romanb committed
321
     *
322 323
     * @param Index|string $index  The name of the index
     * @param string|Table $table The name of the table
romanb's avatar
romanb committed
324
     */
325
    public function dropIndex($index, $table)
romanb's avatar
romanb committed
326
    {
327
        if($index instanceof Index) {
328
            $index = $index->getQuotedName($this->_platform);
329 330
        }

331
        $this->_execSql($this->_platform->getDropIndexSQL($index, $table));
romanb's avatar
romanb committed
332 333 334
    }

    /**
335
     * Drop the constraint from the given table
romanb's avatar
romanb committed
336
     *
337
     * @param Constraint $constraint
338
     * @param string $table   The name of the table
romanb's avatar
romanb committed
339
     */
340
    public function dropConstraint(Constraint $constraint, $table)
romanb's avatar
romanb committed
341
    {
342
        $this->_execSql($this->_platform->getDropConstraintSQL($constraint, $table));
romanb's avatar
romanb committed
343 344 345
    }

    /**
romanb's avatar
romanb committed
346
     * Drops a foreign key from a table.
romanb's avatar
romanb committed
347
     *
348 349
     * @param ForeignKeyConstraint|string $table The name of the table with the foreign key.
     * @param Table|string $name  The name of the foreign key.
350
     * @return boolean $result
romanb's avatar
romanb committed
351
     */
352
    public function dropForeignKey($foreignKey, $table)
romanb's avatar
romanb committed
353
    {
354
        $this->_execSql($this->_platform->getDropForeignKeySQL($foreignKey, $table));
romanb's avatar
romanb committed
355 356 357
    }

    /**
romanb's avatar
romanb committed
358
     * Drops a sequence with a given name.
romanb's avatar
romanb committed
359
     *
romanb's avatar
romanb committed
360
     * @param string $name The name of the sequence to drop.
romanb's avatar
romanb committed
361
     */
362
    public function dropSequence($name)
romanb's avatar
romanb committed
363
    {
364
        $this->_execSql($this->_platform->getDropSequenceSQL($name));
romanb's avatar
romanb committed
365 366
    }

367 368 369 370 371 372 373 374
    /**
     * Drop a view
     *
     * @param string $name The name of the view
     * @return boolean $result
     */
    public function dropView($name)
    {
375
        $this->_execSql($this->_platform->getDropViewSQL($name));
376 377 378 379
    }

    /* create*() Methods */

romanb's avatar
romanb committed
380
    /**
romanb's avatar
romanb committed
381
     * Creates a new database.
romanb's avatar
romanb committed
382
     *
romanb's avatar
romanb committed
383
     * @param string $database The name of the database to create.
romanb's avatar
romanb committed
384
     */
romanb's avatar
romanb committed
385
    public function createDatabase($database)
romanb's avatar
romanb committed
386
    {
387
        $this->_execSql($this->_platform->getCreateDatabaseSQL($database));
romanb's avatar
romanb committed
388 389 390
    }

    /**
romanb's avatar
romanb committed
391
     * Create a new table.
romanb's avatar
romanb committed
392
     *
393
     * @param Table $table
394
     * @param int $createFlags
romanb's avatar
romanb committed
395
     */
396
    public function createTable(Table $table)
romanb's avatar
romanb committed
397
    {
398
        $createFlags = AbstractPlatform::CREATE_INDEXES|AbstractPlatform::CREATE_FOREIGNKEYS;
399
        $this->_execSql($this->_platform->getCreateTableSQL($table, $createFlags));
romanb's avatar
romanb committed
400 401 402
    }

    /**
403
     * Create a new sequence
romanb's avatar
romanb committed
404
     *
405
     * @param Sequence $sequence
406
     * @throws \Doctrine\DBAL\ConnectionException     if something fails at database level
romanb's avatar
romanb committed
407
     */
408
    public function createSequence($sequence)
romanb's avatar
romanb committed
409
    {
410
        $this->_execSql($this->_platform->getCreateSequenceSQL($sequence));
romanb's avatar
romanb committed
411 412 413
    }

    /**
414
     * Create a constraint on a table
romanb's avatar
romanb committed
415
     *
416 417 418 419
     * @param Constraint $constraint
     * @param string|Table $table
     */
    public function createConstraint(Constraint $constraint, $table)
romanb's avatar
romanb committed
420
    {
421
        $this->_execSql($this->_platform->getCreateConstraintSQL($constraint, $table));
romanb's avatar
romanb committed
422 423 424
    }

    /**
425
     * Create a new index on a table
romanb's avatar
romanb committed
426
     *
427
     * @param Index     $index
romanb's avatar
romanb committed
428 429
     * @param string    $table         name of the table on which the index is to be created
     */
430
    public function createIndex(Index $index, $table)
romanb's avatar
romanb committed
431
    {
432
        $this->_execSql($this->_platform->getCreateIndexSQL($index, $table));
romanb's avatar
romanb committed
433 434 435
    }

    /**
436
     * Create a new foreign key
romanb's avatar
romanb committed
437
     *
438 439
     * @param ForeignKeyConstraint  $foreignKey    ForeignKey instance
     * @param string|Table          $table         name of the table on which the foreign key is to be created
romanb's avatar
romanb committed
440
     */
441
    public function createForeignKey(ForeignKeyConstraint $foreignKey, $table)
romanb's avatar
romanb committed
442
    {
443
        $this->_execSql($this->_platform->getCreateForeignKeySQL($foreignKey, $table));
romanb's avatar
romanb committed
444 445
    }

446 447 448
    /**
     * Create a new view
     *
449
     * @param View $view
450
     */
451
    public function createView(View $view)
452
    {
453
        $this->_execSql($this->_platform->getCreateViewSQL($view->getQuotedName($this->_platform), $view->getSql()));
454 455
    }

456 457
    /* dropAndCreate*() Methods */

458
    /**
459 460
     * Drop and create a constraint
     *
461 462
     * @param Constraint    $constraint
     * @param string        $table
463 464 465
     * @see dropConstraint()
     * @see createConstraint()
     */
466
    public function dropAndCreateConstraint(Constraint $constraint, $table)
467
    {
468 469
        $this->tryMethod('dropConstraint', $constraint, $table);
        $this->createConstraint($constraint, $table);
470 471 472 473 474
    }

    /**
     * Drop and create a new index on a table
     *
475 476
     * @param string|Table $table         name of the table on which the index is to be created
     * @param Index $index
477
     */
478
    public function dropAndCreateIndex(Index $index, $table)
479
    {
480
        $this->tryMethod('dropIndex', $index->getQuotedName($this->_platform), $table);
481
        $this->createIndex($index, $table);
482 483 484 485 486
    }

    /**
     * Drop and create a new foreign key
     *
487 488
     * @param ForeignKeyConstraint  $foreignKey    associative array that defines properties of the foreign key to be created.
     * @param string|Table          $table         name of the table on which the foreign key is to be created
489
     */
490
    public function dropAndCreateForeignKey(ForeignKeyConstraint $foreignKey, $table)
491
    {
492 493
        $this->tryMethod('dropForeignKey', $foreignKey, $table);
        $this->createForeignKey($foreignKey, $table);
494 495 496 497 498
    }

    /**
     * Drop and create a new sequence
     *
499
     * @param Sequence $sequence
500
     * @throws \Doctrine\DBAL\ConnectionException     if something fails at database level
501
     */
502
    public function dropAndCreateSequence(Sequence $sequence)
503
    {
Benjamin Eberlei's avatar
Benjamin Eberlei committed
504 505
        $this->tryMethod('dropSequence', $sequence->getQuotedName($this->_platform));
        $this->createSequence($sequence);
506 507 508 509 510
    }

    /**
     * Drop and create a new table.
     *
511
     * @param Table $table
512
     */
513
    public function dropAndCreateTable(Table $table)
514
    {
515
        $this->tryMethod('dropTable', $table->getQuotedName($this->_platform));
516
        $this->createTable($table);
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
    }

    /**
     * Drop and creates a new database.
     *
     * @param string $database The name of the database to create.
     */
    public function dropAndCreateDatabase($database)
    {
        $this->tryMethod('dropDatabase', $database);
        $this->createDatabase($database);
    }

    /**
     * Drop and create a new view
532
     *
533
     * @param View $view
534
     */
535
    public function dropAndCreateView(View $view)
536
    {
537
        $this->tryMethod('dropView', $view->getQuotedName($this->_platform));
538
        $this->createView($view);
539 540
    }

541 542
    /* alterTable() Methods */

romanb's avatar
romanb committed
543
    /**
544
     * Alter an existing tables schema
romanb's avatar
romanb committed
545
     *
546 547 548 549
     * @param TableDiff $tableDiff
     */
    public function alterTable(TableDiff $tableDiff)
    {
550
        $queries = $this->_platform->getAlterTableSQL($tableDiff);
551
        if (is_array($queries) && count($queries)) {
552
            foreach ($queries as $ddlQuery) {
553 554
                $this->_execSql($ddlQuery);
            }
555
        }
556 557
    }

558 559 560 561 562 563 564 565
    /**
     * Rename a given table to another name
     *
     * @param string $name     The current name of the table
     * @param string $newName  The new name of the table
     */
    public function renameTable($name, $newName)
    {
566 567 568
        $tableDiff = new TableDiff($name);
        $tableDiff->newName = $newName;
        $this->alterTable($tableDiff);
569 570
    }

571 572 573 574 575
    /**
     * Methods for filtering return values of list*() methods to convert
     * the native DBMS data definition to a portable Doctrine definition
     */

576 577
    protected function _getPortableDatabasesList($databases)
    {
578
        $list = array();
579
        foreach ($databases as $value) {
580 581 582
            if ($value = $this->_getPortableDatabaseDefinition($value)) {
                $list[] = $value;
            }
583
        }
584
        return $list;
585 586
    }

587 588 589 590 591
    protected function _getPortableDatabaseDefinition($database)
    {
        return $database;
    }

592 593
    protected function _getPortableFunctionsList($functions)
    {
594
        $list = array();
595
        foreach ($functions as $value) {
596 597 598
            if ($value = $this->_getPortableFunctionDefinition($value)) {
                $list[] = $value;
            }
599
        }
600
        return $list;
601 602
    }

603 604 605 606 607
    protected function _getPortableFunctionDefinition($function)
    {
        return $function;
    }

608 609
    protected function _getPortableTriggersList($triggers)
    {
610
        $list = array();
611
        foreach ($triggers as $value) {
612 613 614
            if ($value = $this->_getPortableTriggerDefinition($value)) {
                $list[] = $value;
            }
615
        }
616
        return $list;
617 618
    }

619 620 621 622 623
    protected function _getPortableTriggerDefinition($trigger)
    {
        return $trigger;
    }

624 625
    protected function _getPortableSequencesList($sequences)
    {
626
        $list = array();
627
        foreach ($sequences as $value) {
628 629 630
            if ($value = $this->_getPortableSequenceDefinition($value)) {
                $list[] = $value;
            }
631
        }
632
        return $list;
633 634
    }

635 636 637 638
    /**
     * @param array $sequence
     * @return Sequence
     */
639 640
    protected function _getPortableSequenceDefinition($sequence)
    {
641
        throw DBALException::notSupported('Sequences');
642 643
    }

644 645 646 647 648
    /**
     * 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.
     *
649 650 651
     * @param  string $table The name of the table.
     * @param  string $database
     * @param  array  $tableColumns
652 653
     * @return array
     */
654
    protected function _getPortableTableColumnList($table, $database, $tableColumns)
655
    {
656 657
        $eventManager = $this->_platform->getEventManager();

658
        $list = array();
659
        foreach ($tableColumns as $tableColumn) {
660
            $column = null;
661 662 663
            $defaultPrevented = false;

            if (null !== $eventManager && $eventManager->hasListeners(Events::onSchemaColumnDefinition)) {
664
                $eventArgs = new SchemaColumnDefinitionEventArgs($tableColumn, $table, $database, $this->_conn);
665 666 667
                $eventManager->dispatchEvent(Events::onSchemaColumnDefinition, $eventArgs);

                $defaultPrevented = $eventArgs->isDefaultPrevented();
668
                $column = $eventArgs->getColumn();
669 670
            }

671
            if ( ! $defaultPrevented) {
672
                $column = $this->_getPortableTableColumnDefinition($tableColumn);
673 674
            }

675 676 677
            if ($column) {
                $name = strtolower($column->getQuotedName($this->_platform));
                $list[$name] = $column;
678
            }
679
        }
680
        return $list;
681 682
    }

683 684 685 686 687 688 689
    /**
     * Get Table Column Definition
     *
     * @param array $tableColumn
     * @return Column
     */
    abstract protected function _getPortableTableColumnDefinition($tableColumn);
690

691 692 693
    /**
     * Aggregate and group the index results according to the required data result.
     *
694
     * @param  array $tableIndexRows
695 696 697
     * @param  string $tableName
     * @return array
     */
698
    protected function _getPortableTableIndexesList($tableIndexRows, $tableName=null)
699
    {
700
        $result = array();
701
        foreach($tableIndexRows as $tableIndex) {
702 703 704 705
            $indexName = $keyName = $tableIndex['key_name'];
            if($tableIndex['primary']) {
                $keyName = 'primary';
            }
706
            $keyName = strtolower($keyName);
707 708 709 710 711 712 713

            if(!isset($result[$keyName])) {
                $result[$keyName] = array(
                    'name' => $indexName,
                    'columns' => array($tableIndex['column_name']),
                    'unique' => $tableIndex['non_unique'] ? false : true,
                    'primary' => $tableIndex['primary'],
714
                    'flags' => isset($tableIndex['flags']) ? $tableIndex['flags'] : array(),
715 716 717
                );
            } else {
                $result[$keyName]['columns'][] = $tableIndex['column_name'];
718
            }
719
        }
720

721 722
        $eventManager = $this->_platform->getEventManager();

723
        $indexes = array();
724
        foreach($result as $indexKey => $data) {
725 726 727 728 729 730 731 732 733 734 735
            $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();
            }

736
            if ( ! $defaultPrevented) {
737
                $index = new Index($data['name'], $data['columns'], $data['unique'], $data['primary'], $data['flags']);
738 739 740 741 742
            }

            if ($index) {
                $indexes[$indexKey] = $index;
            }
743 744 745
        }

        return $indexes;
746 747
    }

748 749
    protected function _getPortableTablesList($tables)
    {
750
        $list = array();
751
        foreach ($tables as $value) {
752 753 754
            if ($value = $this->_getPortableTableDefinition($value)) {
                $list[] = $value;
            }
755
        }
756
        return $list;
757 758
    }

759 760 761 762 763
    protected function _getPortableTableDefinition($table)
    {
        return $table;
    }

764 765
    protected function _getPortableUsersList($users)
    {
766
        $list = array();
767
        foreach ($users as $value) {
768 769 770
            if ($value = $this->_getPortableUserDefinition($value)) {
                $list[] = $value;
            }
771
        }
772
        return $list;
773 774
    }

775 776 777 778 779
    protected function _getPortableUserDefinition($user)
    {
        return $user;
    }

780 781
    protected function _getPortableViewsList($views)
    {
782
        $list = array();
783
        foreach ($views as $value) {
784
            if ($view = $this->_getPortableViewDefinition($value)) {
785
                $viewName = strtolower($view->getQuotedName($this->_platform));
786
                $list[$viewName] = $view;
787
            }
788
        }
789
        return $list;
790 791
    }

792 793
    protected function _getPortableViewDefinition($view)
    {
794
        return false;
795 796
    }

797 798 799
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
    {
        $list = array();
800
        foreach ($tableForeignKeys as $value) {
801 802 803 804 805 806 807 808 809 810 811
            if ($value = $this->_getPortableTableForeignKeyDefinition($value)) {
                $list[] = $value;
            }
        }
        return $list;
    }

    protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
    {
        return $tableForeignKey;
    }
812

romanb's avatar
romanb committed
813
    protected function _execSql($sql)
814 815
    {
        foreach ((array) $sql as $query) {
816
            $this->_conn->executeUpdate($query);
romanb's avatar
romanb committed
817 818
        }
    }
819 820 821

    /**
     * Create a schema instance for the current database.
822
     *
823 824 825 826 827 828 829 830 831 832
     * @return Schema
     */
    public function createSchema()
    {
        $sequences = array();
        if($this->_platform->supportsSequences()) {
            $sequences = $this->listSequences();
        }
        $tables = $this->listTables();

833
        return new Schema($tables, $sequences, $this->createSchemaConfig());
834 835 836 837 838 839 840 841 842 843 844
    }

    /**
     * Create the configuration for this schema.
     *
     * @return SchemaConfig
     */
    public function createSchemaConfig()
    {
        $schemaConfig = new SchemaConfig();
        $schemaConfig->setMaxIdentifierLength($this->_platform->getMaxIdentifierLength());
845 846 847 848 849

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

851 852
        $params = $this->_conn->getParams();
        if (isset($params['defaultTableOptions'])) {
853
            $schemaConfig->setDefaultTableOptions($params['defaultTableOptions']);
854 855
        }

856
        return $schemaConfig;
857
    }
858

859 860 861 862 863 864 865 866 867 868 869 870
    /**
     * 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
     */
871 872 873 874 875
    public function getSchemaSearchPaths()
    {
        return array($this->_conn->getDatabase());
    }

876 877 878
    /**
     * Given a table comment this method tries to extract a typehint for Doctrine Type, or returns
     * the type given as default.
879
     *
880 881 882 883 884 885
     * @param  string $comment
     * @param  string $currentType
     * @return string
     */
    public function extractDoctrineTypeFromComment($comment, $currentType)
    {
886
        if (preg_match("(\(DC2Type:([a-zA-Z0-9_]+)\))", $comment, $match)) {
887 888 889 890 891 892 893 894 895
            $currentType = $match[1];
        }
        return $currentType;
    }

    public function removeDoctrineTypeFromComment($comment, $type)
    {
        return str_replace('(DC2Type:'.$type.')', '', $comment);
    }
Benjamin Eberlei's avatar
Benjamin Eberlei committed
896
}