AbstractSchemaManager.php 28.9 KB
Newer Older
romanb's avatar
romanb committed
1 2
<?php

3
namespace Doctrine\DBAL\Schema;
romanb's avatar
romanb committed
4

5 6 7
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\ConnectionException;
use Doctrine\DBAL\DBALException;
8
use Doctrine\DBAL\Event\SchemaColumnDefinitionEventArgs;
9
use Doctrine\DBAL\Event\SchemaIndexDefinitionEventArgs;
10
use Doctrine\DBAL\Events;
11
use Doctrine\DBAL\Platforms\AbstractPlatform;
12
use Throwable;
13
use function array_filter;
14
use function array_intersect;
15 16
use function array_map;
use function array_values;
Sergei Morozov's avatar
Sergei Morozov committed
17
use function assert;
18 19 20 21
use function call_user_func_array;
use function count;
use function func_get_args;
use function is_array;
Sergei Morozov's avatar
Sergei Morozov committed
22
use function is_callable;
23 24 25
use function preg_match;
use function str_replace;
use function strtolower;
26

romanb's avatar
romanb committed
27
/**
28
 * Base class for schema managers. Schema managers are used to inspect and/or
29
 * modify the database schema/structure.
romanb's avatar
romanb committed
30
 */
31
abstract class AbstractSchemaManager
romanb's avatar
romanb committed
32
{
33
    /**
Benjamin Morel's avatar
Benjamin Morel committed
34
     * Holds instance of the Doctrine connection for this schema manager.
35
     *
36
     * @var Connection
37
     */
romanb's avatar
romanb committed
38 39
    protected $_conn;

40
    /**
Benjamin Morel's avatar
Benjamin Morel committed
41
     * Holds instance of the database platform used for this schema manager.
42
     *
43
     * @var AbstractPlatform
44 45 46 47
     */
    protected $_platform;

    /**
Benjamin Morel's avatar
Benjamin Morel committed
48
     * Constructor. Accepts the Connection instance to manage the schema for.
49
     */
50
    public function __construct(Connection $conn, ?AbstractPlatform $platform = null)
51
    {
52 53
        $this->_conn     = $conn;
        $this->_platform = $platform ?: $this->_conn->getDatabasePlatform();
54 55
    }

56
    /**
Benjamin Morel's avatar
Benjamin Morel committed
57
     * Returns the associated platform.
58
     *
59
     * @return AbstractPlatform
60 61 62 63 64 65
     */
    public function getDatabasePlatform()
    {
        return $this->_platform;
    }

66
    /**
Benjamin Morel's avatar
Benjamin Morel committed
67
     * Tries any method on the schema manager. Normally a method throws an
68 69 70 71 72 73 74 75 76 77 78 79
     * 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()
    {
80
        $args   = func_get_args();
81 82 83 84
        $method = $args[0];
        unset($args[0]);
        $args = array_values($args);

Sergei Morozov's avatar
Sergei Morozov committed
85 86 87
        $callback = [$this, $method];
        assert(is_callable($callback));

88
        try {
Sergei Morozov's avatar
Sergei Morozov committed
89
            return call_user_func_array($callback, $args);
90
        } catch (Throwable $e) {
91 92 93 94
            return false;
        }
    }

romanb's avatar
romanb committed
95
    /**
Benjamin Morel's avatar
Benjamin Morel committed
96
     * Lists the available databases for this connection.
romanb's avatar
romanb committed
97
     *
98
     * @return string[]
romanb's avatar
romanb committed
99 100 101
     */
    public function listDatabases()
    {
102
        $sql = $this->_platform->getListDatabasesSQL();
103 104 105 106

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

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

109 110 111
    /**
     * Returns a list of all namespaces in the current database.
     *
112
     * @return string[]
113 114 115 116 117 118 119 120 121 122
     */
    public function listNamespaceNames()
    {
        $sql = $this->_platform->getListNamespacesSQL();

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

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

romanb's avatar
romanb committed
123
    /**
Benjamin Morel's avatar
Benjamin Morel committed
124 125 126
     * Lists the available sequences for this connection.
     *
     * @param string|null $database
romanb's avatar
romanb committed
127
     *
128
     * @return Sequence[]
romanb's avatar
romanb committed
129
     */
130
    public function listSequences($database = null)
romanb's avatar
romanb committed
131
    {
132
        if ($database === null) {
133 134
            $database = $this->_conn->getDatabase();
        }
135
        $sql = $this->_platform->getListSequencesSQL($database);
136 137 138

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

139
        return $this->filterAssetNames($this->_getPortableSequencesList($sequences));
romanb's avatar
romanb committed
140 141 142
    }

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

        $sql = $this->_platform->getListTableColumnsSQL($table, $database);
164 165 166

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

167
        return $this->_getPortableTableColumnList($table, $database, $tableColumns);
romanb's avatar
romanb committed
168 169 170
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
171
     * Lists the indexes for a given table returning an array of Index instances.
romanb's avatar
romanb committed
172
     *
173 174
     * Keys of the portable indexes list are all lower-cased.
     *
Benjamin Morel's avatar
Benjamin Morel committed
175 176
     * @param string $table The name of the table.
     *
177
     * @return Index[]
romanb's avatar
romanb committed
178 179 180
     */
    public function listTableIndexes($table)
    {
181
        $sql = $this->_platform->getListTableIndexesSQL($table, $this->_conn->getDatabase());
182 183 184

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

185
        return $this->_getPortableTableIndexesList($tableIndexes, $table);
romanb's avatar
romanb committed
186 187
    }

188
    /**
Benjamin Morel's avatar
Benjamin Morel committed
189
     * Returns true if all the given tables exist.
190
     *
Sergei Morozov's avatar
Sergei Morozov committed
191
     * @param string|string[] $tableNames
Benjamin Morel's avatar
Benjamin Morel committed
192
     *
193
     * @return bool
194 195 196
     */
    public function tablesExist($tableNames)
    {
197
        $tableNames = array_map('strtolower', (array) $tableNames);
Benjamin Morel's avatar
Benjamin Morel committed
198

199
        return count($tableNames) === count(array_intersect($tableNames, array_map('strtolower', $this->listTableNames())));
200 201
    }

romanb's avatar
romanb committed
202
    /**
Benjamin Morel's avatar
Benjamin Morel committed
203
     * Returns a list of all tables in the current database.
romanb's avatar
romanb committed
204
     *
205
     * @return string[]
romanb's avatar
romanb committed
206
     */
207
    public function listTableNames()
romanb's avatar
romanb committed
208
    {
209
        $sql = $this->_platform->getListTablesSQL();
210

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

214 215
        return $this->filterAssetNames($tableNames);
    }
216

217
    /**
Benjamin Morel's avatar
Benjamin Morel committed
218
     * Filters asset names if they are configured to return only a subset of all
219 220
     * the found elements.
     *
221
     * @param mixed[] $assetNames
Benjamin Morel's avatar
Benjamin Morel committed
222
     *
223
     * @return mixed[]
224 225 226
     */
    protected function filterAssetNames($assetNames)
    {
227 228
        $filter = $this->_conn->getConfiguration()->getSchemaAssetsFilter();
        if (! $filter) {
229 230
            return $assetNames;
        }
Benjamin Morel's avatar
Benjamin Morel committed
231

232
        return array_values(array_filter($assetNames, $filter));
233 234
    }

Benjamin Morel's avatar
Benjamin Morel committed
235
    /**
236 237
     * @deprecated Use Configuration::getSchemaAssetsFilter() instead
     *
Benjamin Morel's avatar
Benjamin Morel committed
238 239
     * @return string|null
     */
240 241 242
    protected function getFilterSchemaAssetsExpression()
    {
        return $this->_conn->getConfiguration()->getFilterSchemaAssetsExpression();
243 244 245
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
246
     * Lists the tables for this connection.
247
     *
248
     * @return Table[]
249 250 251 252
     */
    public function listTables()
    {
        $tableNames = $this->listTableNames();
253

254
        $tables = [];
255
        foreach ($tableNames as $tableName) {
256
            $tables[] = $this->listTableDetails($tableName);
257 258 259
        }

        return $tables;
romanb's avatar
romanb committed
260 261
    }

262
    /**
Benjamin Morel's avatar
Benjamin Morel committed
263 264
     * @param string $tableName
     *
265
     * @return Table
266 267 268
     */
    public function listTableDetails($tableName)
    {
269
        $columns     = $this->listTableColumns($tableName);
270
        $foreignKeys = [];
271 272 273 274 275
        if ($this->_platform->supportsForeignKeyConstraints()) {
            $foreignKeys = $this->listTableForeignKeys($tableName);
        }
        $indexes = $this->listTableIndexes($tableName);

Sergei Morozov's avatar
Sergei Morozov committed
276
        return new Table($tableName, $columns, $indexes, $foreignKeys);
277 278
    }

romanb's avatar
romanb committed
279
    /**
Benjamin Morel's avatar
Benjamin Morel committed
280
     * Lists the views this connection has.
romanb's avatar
romanb committed
281
     *
282
     * @return View[]
romanb's avatar
romanb committed
283
     */
284
    public function listViews()
romanb's avatar
romanb committed
285
    {
286
        $database = $this->_conn->getDatabase();
287 288
        $sql      = $this->_platform->getListViewsSQL($database);
        $views    = $this->_conn->fetchAll($sql);
289 290

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

293
    /**
Benjamin Morel's avatar
Benjamin Morel committed
294 295 296 297
     * Lists the foreign keys for the given table.
     *
     * @param string      $table    The name of the table.
     * @param string|null $database
298
     *
299
     * @return ForeignKeyConstraint[]
300 301 302
     */
    public function listTableForeignKeys($table, $database = null)
    {
303
        if ($database === null) {
304 305
            $database = $this->_conn->getDatabase();
        }
306
        $sql              = $this->_platform->getListTableForeignKeysSQL($table, $database);
307 308 309 310 311
        $tableForeignKeys = $this->_conn->fetchAll($sql);

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

312 313
    /* drop*() Methods */

romanb's avatar
romanb committed
314
    /**
315
     * Drops a database.
316
     *
317
     * NOTE: You can not drop the database this SchemaManager is currently connected to.
romanb's avatar
romanb committed
318
     *
Benjamin Morel's avatar
Benjamin Morel committed
319 320 321
     * @param string $database The name of the database to drop.
     *
     * @return void
romanb's avatar
romanb committed
322
     */
323
    public function dropDatabase($database)
romanb's avatar
romanb committed
324
    {
325
        $this->_execSql($this->_platform->getDropDatabaseSQL($database));
romanb's avatar
romanb committed
326 327 328
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
329 330
     * Drops the given table.
     *
jeroendedauw's avatar
jeroendedauw committed
331
     * @param string $tableName The name of the table to drop.
romanb's avatar
romanb committed
332
     *
Benjamin Morel's avatar
Benjamin Morel committed
333
     * @return void
romanb's avatar
romanb committed
334
     */
jeroendedauw's avatar
jeroendedauw committed
335
    public function dropTable($tableName)
romanb's avatar
romanb committed
336
    {
jeroendedauw's avatar
jeroendedauw committed
337
        $this->_execSql($this->_platform->getDropTableSQL($tableName));
romanb's avatar
romanb committed
338 339 340
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
341
     * Drops the index from the given table.
romanb's avatar
romanb committed
342
     *
343 344
     * @param Index|string $index The name of the index.
     * @param Table|string $table The name of the table.
Benjamin Morel's avatar
Benjamin Morel committed
345 346
     *
     * @return void
romanb's avatar
romanb committed
347
     */
348
    public function dropIndex($index, $table)
romanb's avatar
romanb committed
349
    {
Steve Müller's avatar
Steve Müller committed
350
        if ($index instanceof Index) {
351
            $index = $index->getQuotedName($this->_platform);
352 353
        }

354
        $this->_execSql($this->_platform->getDropIndexSQL($index, $table));
romanb's avatar
romanb committed
355 356 357
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
358 359
     * Drops the constraint from the given table.
     *
360
     * @param Table|string $table The name of the table.
romanb's avatar
romanb committed
361
     *
Benjamin Morel's avatar
Benjamin Morel committed
362
     * @return void
romanb's avatar
romanb committed
363
     */
364
    public function dropConstraint(Constraint $constraint, $table)
romanb's avatar
romanb committed
365
    {
366
        $this->_execSql($this->_platform->getDropConstraintSQL($constraint, $table));
romanb's avatar
romanb committed
367 368 369
    }

    /**
romanb's avatar
romanb committed
370
     * Drops a foreign key from a table.
romanb's avatar
romanb committed
371
     *
372 373
     * @param ForeignKeyConstraint|string $foreignKey The name of the foreign key.
     * @param Table|string                $table      The name of the table with the foreign key.
Benjamin Morel's avatar
Benjamin Morel committed
374 375
     *
     * @return void
romanb's avatar
romanb committed
376
     */
377
    public function dropForeignKey($foreignKey, $table)
romanb's avatar
romanb committed
378
    {
379
        $this->_execSql($this->_platform->getDropForeignKeySQL($foreignKey, $table));
romanb's avatar
romanb committed
380 381 382
    }

    /**
romanb's avatar
romanb committed
383
     * Drops a sequence with a given name.
romanb's avatar
romanb committed
384
     *
romanb's avatar
romanb committed
385
     * @param string $name The name of the sequence to drop.
Benjamin Morel's avatar
Benjamin Morel committed
386 387
     *
     * @return void
romanb's avatar
romanb committed
388
     */
389
    public function dropSequence($name)
romanb's avatar
romanb committed
390
    {
391
        $this->_execSql($this->_platform->getDropSequenceSQL($name));
romanb's avatar
romanb committed
392 393
    }

394
    /**
Benjamin Morel's avatar
Benjamin Morel committed
395
     * Drops a view.
396
     *
Benjamin Morel's avatar
Benjamin Morel committed
397 398 399
     * @param string $name The name of the view.
     *
     * @return void
400 401 402
     */
    public function dropView($name)
    {
403
        $this->_execSql($this->_platform->getDropViewSQL($name));
404 405 406 407
    }

    /* create*() Methods */

romanb's avatar
romanb committed
408
    /**
romanb's avatar
romanb committed
409
     * Creates a new database.
romanb's avatar
romanb committed
410
     *
romanb's avatar
romanb committed
411
     * @param string $database The name of the database to create.
Benjamin Morel's avatar
Benjamin Morel committed
412 413
     *
     * @return void
romanb's avatar
romanb committed
414
     */
romanb's avatar
romanb committed
415
    public function createDatabase($database)
romanb's avatar
romanb committed
416
    {
417
        $this->_execSql($this->_platform->getCreateDatabaseSQL($database));
romanb's avatar
romanb committed
418 419 420
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
421
     * Creates a new table.
romanb's avatar
romanb committed
422
     *
Benjamin Morel's avatar
Benjamin Morel committed
423
     * @return void
romanb's avatar
romanb committed
424
     */
425
    public function createTable(Table $table)
romanb's avatar
romanb committed
426
    {
427
        $createFlags = AbstractPlatform::CREATE_INDEXES|AbstractPlatform::CREATE_FOREIGNKEYS;
428
        $this->_execSql($this->_platform->getCreateTableSQL($table, $createFlags));
romanb's avatar
romanb committed
429 430 431
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
432 433
     * Creates a new sequence.
     *
434
     * @param Sequence $sequence
romanb's avatar
romanb committed
435
     *
Benjamin Morel's avatar
Benjamin Morel committed
436 437
     * @return void
     *
438
     * @throws ConnectionException If something fails at database level.
romanb's avatar
romanb committed
439
     */
440
    public function createSequence($sequence)
romanb's avatar
romanb committed
441
    {
442
        $this->_execSql($this->_platform->getCreateSequenceSQL($sequence));
romanb's avatar
romanb committed
443 444 445
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
446 447
     * Creates a constraint on a table.
     *
448
     * @param Table|string $table
romanb's avatar
romanb committed
449
     *
Benjamin Morel's avatar
Benjamin Morel committed
450
     * @return void
451 452
     */
    public function createConstraint(Constraint $constraint, $table)
romanb's avatar
romanb committed
453
    {
454
        $this->_execSql($this->_platform->getCreateConstraintSQL($constraint, $table));
romanb's avatar
romanb committed
455 456 457
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
458
     * Creates a new index on a table.
romanb's avatar
romanb committed
459
     *
460
     * @param Table|string $table The name of the table on which the index is to be created.
Benjamin Morel's avatar
Benjamin Morel committed
461 462
     *
     * @return void
romanb's avatar
romanb committed
463
     */
464
    public function createIndex(Index $index, $table)
romanb's avatar
romanb committed
465
    {
466
        $this->_execSql($this->_platform->getCreateIndexSQL($index, $table));
romanb's avatar
romanb committed
467 468 469
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
470 471
     * Creates a new foreign key.
     *
472 473
     * @param ForeignKeyConstraint $foreignKey The ForeignKey instance.
     * @param Table|string         $table      The name of the table on which the foreign key is to be created.
romanb's avatar
romanb committed
474
     *
Benjamin Morel's avatar
Benjamin Morel committed
475
     * @return void
romanb's avatar
romanb committed
476
     */
477
    public function createForeignKey(ForeignKeyConstraint $foreignKey, $table)
romanb's avatar
romanb committed
478
    {
479
        $this->_execSql($this->_platform->getCreateForeignKeySQL($foreignKey, $table));
romanb's avatar
romanb committed
480 481
    }

482
    /**
Benjamin Morel's avatar
Benjamin Morel committed
483
     * Creates a new view.
484
     *
Benjamin Morel's avatar
Benjamin Morel committed
485
     * @return void
486
     */
487
    public function createView(View $view)
488
    {
489
        $this->_execSql($this->_platform->getCreateViewSQL($view->getQuotedName($this->_platform), $view->getSql()));
490 491
    }

492 493
    /* dropAndCreate*() Methods */

494
    /**
Benjamin Morel's avatar
Benjamin Morel committed
495
     * Drops and creates a constraint.
496 497 498
     *
     * @see dropConstraint()
     * @see createConstraint()
Benjamin Morel's avatar
Benjamin Morel committed
499
     *
500
     * @param Table|string $table
Benjamin Morel's avatar
Benjamin Morel committed
501 502
     *
     * @return void
503
     */
504
    public function dropAndCreateConstraint(Constraint $constraint, $table)
505
    {
506 507
        $this->tryMethod('dropConstraint', $constraint, $table);
        $this->createConstraint($constraint, $table);
508 509 510
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
511 512
     * Drops and creates a new index on a table.
     *
513
     * @param Table|string $table The name of the table on which the index is to be created.
514
     *
Benjamin Morel's avatar
Benjamin Morel committed
515
     * @return void
516
     */
517
    public function dropAndCreateIndex(Index $index, $table)
518
    {
519
        $this->tryMethod('dropIndex', $index->getQuotedName($this->_platform), $table);
520
        $this->createIndex($index, $table);
521 522 523
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
524
     * Drops and creates a new foreign key.
525
     *
526 527
     * @param ForeignKeyConstraint $foreignKey An associative array that defines properties of the foreign key to be created.
     * @param Table|string         $table      The name of the table on which the foreign key is to be created.
Benjamin Morel's avatar
Benjamin Morel committed
528 529
     *
     * @return void
530
     */
531
    public function dropAndCreateForeignKey(ForeignKeyConstraint $foreignKey, $table)
532
    {
533 534
        $this->tryMethod('dropForeignKey', $foreignKey, $table);
        $this->createForeignKey($foreignKey, $table);
535 536 537
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
538 539 540 541
     * Drops and create a new sequence.
     *
     * @return void
     *
542
     * @throws ConnectionException If something fails at database level.
543
     */
544
    public function dropAndCreateSequence(Sequence $sequence)
545
    {
Benjamin Eberlei's avatar
Benjamin Eberlei committed
546 547
        $this->tryMethod('dropSequence', $sequence->getQuotedName($this->_platform));
        $this->createSequence($sequence);
548 549 550
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
551 552 553
     * Drops and creates a new table.
     *
     * @return void
554
     */
555
    public function dropAndCreateTable(Table $table)
556
    {
557
        $this->tryMethod('dropTable', $table->getQuotedName($this->_platform));
558
        $this->createTable($table);
559 560 561
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
562
     * Drops and creates a new database.
563 564
     *
     * @param string $database The name of the database to create.
Benjamin Morel's avatar
Benjamin Morel committed
565 566
     *
     * @return void
567 568 569 570 571 572 573 574
     */
    public function dropAndCreateDatabase($database)
    {
        $this->tryMethod('dropDatabase', $database);
        $this->createDatabase($database);
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
575 576 577
     * Drops and creates a new view.
     *
     * @return void
578
     */
579
    public function dropAndCreateView(View $view)
580
    {
581
        $this->tryMethod('dropView', $view->getQuotedName($this->_platform));
582
        $this->createView($view);
583 584
    }

585 586
    /* alterTable() Methods */

romanb's avatar
romanb committed
587
    /**
Benjamin Morel's avatar
Benjamin Morel committed
588
     * Alters an existing tables schema.
romanb's avatar
romanb committed
589
     *
Benjamin Morel's avatar
Benjamin Morel committed
590
     * @return void
591 592 593
     */
    public function alterTable(TableDiff $tableDiff)
    {
594
        $queries = $this->_platform->getAlterTableSQL($tableDiff);
595 596 597 598 599 600
        if (! is_array($queries) || ! count($queries)) {
            return;
        }

        foreach ($queries as $ddlQuery) {
            $this->_execSql($ddlQuery);
601
        }
602 603
    }

604
    /**
Benjamin Morel's avatar
Benjamin Morel committed
605 606 607 608
     * 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.
609
     *
Benjamin Morel's avatar
Benjamin Morel committed
610
     * @return void
611 612 613
     */
    public function renameTable($name, $newName)
    {
614
        $tableDiff          = new TableDiff($name);
615 616
        $tableDiff->newName = $newName;
        $this->alterTable($tableDiff);
617 618
    }

619 620 621 622 623
    /**
     * 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
624
    /**
625
     * @param mixed[] $databases
Benjamin Morel's avatar
Benjamin Morel committed
626
     *
627
     * @return string[]
Benjamin Morel's avatar
Benjamin Morel committed
628
     */
629 630
    protected function _getPortableDatabasesList($databases)
    {
631
        $list = [];
632
        foreach ($databases as $value) {
633 634 635
            $value = $this->_getPortableDatabaseDefinition($value);

            if (! $value) {
636
                continue;
637
            }
638 639

            $list[] = $value;
640
        }
Benjamin Morel's avatar
Benjamin Morel committed
641

642
        return $list;
643 644
    }

645 646 647
    /**
     * Converts a list of namespace names from the native DBMS data definition to a portable Doctrine definition.
     *
648
     * @param mixed[][] $namespaces The list of namespace names in the native DBMS data definition.
649
     *
650
     * @return string[]
651 652 653
     */
    protected function getPortableNamespacesList(array $namespaces)
    {
654
        $namespacesList = [];
655 656 657 658 659 660 661 662

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

        return $namespacesList;
    }

Benjamin Morel's avatar
Benjamin Morel committed
663
    /**
664
     * @param mixed $database
Benjamin Morel's avatar
Benjamin Morel committed
665 666 667
     *
     * @return mixed
     */
668 669 670 671 672
    protected function _getPortableDatabaseDefinition($database)
    {
        return $database;
    }

673 674 675
    /**
     * Converts a namespace definition from the native DBMS data definition to a portable Doctrine definition.
     *
676
     * @param mixed[] $namespace The native DBMS namespace definition.
677 678 679 680 681 682 683 684
     *
     * @return mixed
     */
    protected function getPortableNamespaceDefinition(array $namespace)
    {
        return $namespace;
    }

Benjamin Morel's avatar
Benjamin Morel committed
685
    /**
686
     * @param mixed[][] $functions
Benjamin Morel's avatar
Benjamin Morel committed
687
     *
688
     * @return mixed[][]
Benjamin Morel's avatar
Benjamin Morel committed
689
     */
690 691
    protected function _getPortableFunctionsList($functions)
    {
692
        $list = [];
693
        foreach ($functions as $value) {
694 695 696
            $value = $this->_getPortableFunctionDefinition($value);

            if (! $value) {
697
                continue;
698
            }
699 700

            $list[] = $value;
701
        }
Benjamin Morel's avatar
Benjamin Morel committed
702

703
        return $list;
704 705
    }

Benjamin Morel's avatar
Benjamin Morel committed
706
    /**
707
     * @param mixed[] $function
Benjamin Morel's avatar
Benjamin Morel committed
708 709 710
     *
     * @return mixed
     */
711 712 713 714 715
    protected function _getPortableFunctionDefinition($function)
    {
        return $function;
    }

Benjamin Morel's avatar
Benjamin Morel committed
716
    /**
717
     * @param mixed[][] $triggers
Benjamin Morel's avatar
Benjamin Morel committed
718
     *
719
     * @return mixed[][]
Benjamin Morel's avatar
Benjamin Morel committed
720
     */
721 722
    protected function _getPortableTriggersList($triggers)
    {
723
        $list = [];
724
        foreach ($triggers as $value) {
725 726 727
            $value = $this->_getPortableTriggerDefinition($value);

            if (! $value) {
728
                continue;
729
            }
730 731

            $list[] = $value;
732
        }
Benjamin Morel's avatar
Benjamin Morel committed
733

734
        return $list;
735 736
    }

Benjamin Morel's avatar
Benjamin Morel committed
737
    /**
738
     * @param mixed[] $trigger
Benjamin Morel's avatar
Benjamin Morel committed
739 740 741
     *
     * @return mixed
     */
742 743 744 745 746
    protected function _getPortableTriggerDefinition($trigger)
    {
        return $trigger;
    }

Benjamin Morel's avatar
Benjamin Morel committed
747
    /**
748
     * @param mixed[][] $sequences
Benjamin Morel's avatar
Benjamin Morel committed
749
     *
750
     * @return Sequence[]
Benjamin Morel's avatar
Benjamin Morel committed
751
     */
752 753
    protected function _getPortableSequencesList($sequences)
    {
754
        $list = [];
755

Sergei Morozov's avatar
Sergei Morozov committed
756 757
        foreach ($sequences as $value) {
            $list[] = $this->_getPortableSequenceDefinition($value);
758
        }
Benjamin Morel's avatar
Benjamin Morel committed
759

760
        return $list;
761 762
    }

763
    /**
764
     * @param mixed[] $sequence
Benjamin Morel's avatar
Benjamin Morel committed
765
     *
766
     * @return Sequence
Benjamin Morel's avatar
Benjamin Morel committed
767
     *
768
     * @throws DBALException
769
     */
770 771
    protected function _getPortableSequenceDefinition($sequence)
    {
772
        throw DBALException::notSupported('Sequences');
773 774
    }

775 776 777 778 779
    /**
     * 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.
     *
780 781 782
     * @param string    $table        The name of the table.
     * @param string    $database
     * @param mixed[][] $tableColumns
Benjamin Morel's avatar
Benjamin Morel committed
783
     *
784
     * @return Column[]
785
     */
786
    protected function _getPortableTableColumnList($table, $database, $tableColumns)
787
    {
788 789
        $eventManager = $this->_platform->getEventManager();

790
        $list = [];
791
        foreach ($tableColumns as $tableColumn) {
792
            $column           = null;
793 794
            $defaultPrevented = false;

795
            if ($eventManager !== null && $eventManager->hasListeners(Events::onSchemaColumnDefinition)) {
796
                $eventArgs = new SchemaColumnDefinitionEventArgs($tableColumn, $table, $database, $this->_conn);
797 798 799
                $eventManager->dispatchEvent(Events::onSchemaColumnDefinition, $eventArgs);

                $defaultPrevented = $eventArgs->isDefaultPrevented();
800
                $column           = $eventArgs->getColumn();
801 802
            }

803
            if (! $defaultPrevented) {
804
                $column = $this->_getPortableTableColumnDefinition($tableColumn);
805 806
            }

807 808
            if (! $column) {
                continue;
809
            }
810 811 812

            $name        = strtolower($column->getQuotedName($this->_platform));
            $list[$name] = $column;
813
        }
Benjamin Morel's avatar
Benjamin Morel committed
814

815
        return $list;
816 817
    }

818
    /**
Benjamin Morel's avatar
Benjamin Morel committed
819
     * Gets Table Column Definition.
820
     *
821
     * @param mixed[] $tableColumn
Benjamin Morel's avatar
Benjamin Morel committed
822
     *
823
     * @return Column
824 825
     */
    abstract protected function _getPortableTableColumnDefinition($tableColumn);
826

827
    /**
Benjamin Morel's avatar
Benjamin Morel committed
828 829
     * Aggregates and groups the index results according to the required data result.
     *
830
     * @param mixed[][]   $tableIndexRows
Benjamin Morel's avatar
Benjamin Morel committed
831
     * @param string|null $tableName
832
     *
833
     * @return Index[]
834
     */
835
    protected function _getPortableTableIndexesList($tableIndexRows, $tableName = null)
836
    {
837
        $result = [];
Steve Müller's avatar
Steve Müller committed
838
        foreach ($tableIndexRows as $tableIndex) {
839
            $indexName = $keyName = $tableIndex['key_name'];
Steve Müller's avatar
Steve Müller committed
840
            if ($tableIndex['primary']) {
841 842
                $keyName = 'primary';
            }
843
            $keyName = strtolower($keyName);
844

845
            if (! isset($result[$keyName])) {
846 847 848 849 850 851 852 853
                $options = [
                    'lengths' => [],
                ];

                if (isset($tableIndex['where'])) {
                    $options['where'] = $tableIndex['where'];
                }

854
                $result[$keyName] = [
855
                    'name' => $indexName,
856
                    'columns' => [],
857
                    'unique' => ! $tableIndex['non_unique'],
858
                    'primary' => $tableIndex['primary'],
859
                    'flags' => $tableIndex['flags'] ?? [],
860
                    'options' => $options,
861
                ];
862
            }
863 864 865

            $result[$keyName]['columns'][]            = $tableIndex['column_name'];
            $result[$keyName]['options']['lengths'][] = $tableIndex['length'] ?? null;
866
        }
867

868 869
        $eventManager = $this->_platform->getEventManager();

870
        $indexes = [];
Steve Müller's avatar
Steve Müller committed
871
        foreach ($result as $indexKey => $data) {
872
            $index            = null;
873 874
            $defaultPrevented = false;

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

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

883
            if (! $defaultPrevented) {
884
                $index = new Index($data['name'], $data['columns'], $data['unique'], $data['primary'], $data['flags'], $data['options']);
885 886
            }

887 888
            if (! $index) {
                continue;
889
            }
890 891

            $indexes[$indexKey] = $index;
892 893 894
        }

        return $indexes;
895 896
    }

Benjamin Morel's avatar
Benjamin Morel committed
897
    /**
898
     * @param mixed[][] $tables
Benjamin Morel's avatar
Benjamin Morel committed
899
     *
900
     * @return string[]
Benjamin Morel's avatar
Benjamin Morel committed
901
     */
902 903
    protected function _getPortableTablesList($tables)
    {
904
        $list = [];
905
        foreach ($tables as $value) {
906 907 908
            $value = $this->_getPortableTableDefinition($value);

            if (! $value) {
909
                continue;
910
            }
911 912

            $list[] = $value;
913
        }
Benjamin Morel's avatar
Benjamin Morel committed
914

915
        return $list;
916 917
    }

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

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

            if (! $value) {
940
                continue;
941
            }
942 943

            $list[] = $value;
944
        }
Benjamin Morel's avatar
Benjamin Morel committed
945

946
        return $list;
947 948
    }

Benjamin Morel's avatar
Benjamin Morel committed
949
    /**
950
     * @param string[] $user
Benjamin Morel's avatar
Benjamin Morel committed
951
     *
952
     * @return string[]
Benjamin Morel's avatar
Benjamin Morel committed
953
     */
954 955 956 957 958
    protected function _getPortableUserDefinition($user)
    {
        return $user;
    }

Benjamin Morel's avatar
Benjamin Morel committed
959
    /**
960
     * @param mixed[][] $views
961
     *
962
     * @return View[]
Benjamin Morel's avatar
Benjamin Morel committed
963
     */
964 965
    protected function _getPortableViewsList($views)
    {
966
        $list = [];
967
        foreach ($views as $value) {
968 969 970
            $view = $this->_getPortableViewDefinition($value);

            if (! $view) {
971
                continue;
972
            }
973 974 975

            $viewName        = strtolower($view->getQuotedName($this->_platform));
            $list[$viewName] = $view;
976
        }
Benjamin Morel's avatar
Benjamin Morel committed
977

978
        return $list;
979 980
    }

Benjamin Morel's avatar
Benjamin Morel committed
981
    /**
982
     * @param mixed[] $view
Benjamin Morel's avatar
Benjamin Morel committed
983
     *
984
     * @return View|false
Benjamin Morel's avatar
Benjamin Morel committed
985
     */
986 987
    protected function _getPortableViewDefinition($view)
    {
988
        return false;
989 990
    }

Benjamin Morel's avatar
Benjamin Morel committed
991
    /**
992
     * @param mixed[][] $tableForeignKeys
Benjamin Morel's avatar
Benjamin Morel committed
993
     *
994
     * @return ForeignKeyConstraint[]
Benjamin Morel's avatar
Benjamin Morel committed
995
     */
996 997
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
    {
998
        $list = [];
999

Sergei Morozov's avatar
Sergei Morozov committed
1000 1001
        foreach ($tableForeignKeys as $value) {
            $list[] = $this->_getPortableTableForeignKeyDefinition($value);
1002
        }
Benjamin Morel's avatar
Benjamin Morel committed
1003

1004 1005 1006
        return $list;
    }

Benjamin Morel's avatar
Benjamin Morel committed
1007
    /**
1008
     * @param mixed $tableForeignKey
Benjamin Morel's avatar
Benjamin Morel committed
1009
     *
1010
     * @return ForeignKeyConstraint
Benjamin Morel's avatar
Benjamin Morel committed
1011
     */
1012 1013 1014 1015
    protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
    {
        return $tableForeignKey;
    }
1016

Benjamin Morel's avatar
Benjamin Morel committed
1017
    /**
1018
     * @param string[]|string $sql
Benjamin Morel's avatar
Benjamin Morel committed
1019 1020 1021
     *
     * @return void
     */
romanb's avatar
romanb committed
1022
    protected function _execSql($sql)
1023 1024
    {
        foreach ((array) $sql as $query) {
1025
            $this->_conn->executeUpdate($query);
romanb's avatar
romanb committed
1026 1027
        }
    }
1028 1029

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1030
     * Creates a schema instance for the current database.
1031
     *
1032
     * @return Schema
1033 1034 1035
     */
    public function createSchema()
    {
1036
        $namespaces = [];
1037 1038 1039 1040 1041

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

1042
        $sequences = [];
1043

Steve Müller's avatar
Steve Müller committed
1044
        if ($this->_platform->supportsSequences()) {
1045 1046
            $sequences = $this->listSequences();
        }
1047

1048 1049
        $tables = $this->listTables();

1050
        return new Schema($tables, $sequences, $this->createSchemaConfig(), $namespaces);
1051 1052 1053
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1054
     * Creates the configuration for this schema.
1055
     *
1056
     * @return SchemaConfig
1057 1058 1059 1060 1061
     */
    public function createSchemaConfig()
    {
        $schemaConfig = new SchemaConfig();
        $schemaConfig->setMaxIdentifierLength($this->_platform->getMaxIdentifierLength());
1062 1063 1064 1065 1066

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

1068
        $params = $this->_conn->getParams();
1069 1070
        if (! isset($params['defaultTableOptions'])) {
            $params['defaultTableOptions'] = [];
1071
        }
1072 1073 1074 1075
        if (! isset($params['defaultTableOptions']['charset']) && isset($params['charset'])) {
            $params['defaultTableOptions']['charset'] = $params['charset'];
        }
        $schemaConfig->setDefaultTableOptions($params['defaultTableOptions']);
1076

1077
        return $schemaConfig;
1078
    }
1079

1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
    /**
     * 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.
     *
1090
     * @return string[]
1091
     */
1092 1093
    public function getSchemaSearchPaths()
    {
1094
        return [$this->_conn->getDatabase()];
1095 1096
    }

1097 1098 1099
    /**
     * Given a table comment this method tries to extract a typehint for Doctrine Type, or returns
     * the type given as default.
1100
     *
Sergei Morozov's avatar
Sergei Morozov committed
1101 1102
     * @param string|null $comment
     * @param string      $currentType
Benjamin Morel's avatar
Benjamin Morel committed
1103
     *
1104 1105 1106 1107
     * @return string
     */
    public function extractDoctrineTypeFromComment($comment, $currentType)
    {
Sergei Morozov's avatar
Sergei Morozov committed
1108 1109
        if ($comment !== null && preg_match('(\(DC2Type:(((?!\)).)+)\))', $comment, $match)) {
            return $match[1];
1110
        }
Benjamin Morel's avatar
Benjamin Morel committed
1111

1112 1113 1114
        return $currentType;
    }

Benjamin Morel's avatar
Benjamin Morel committed
1115
    /**
Sergei Morozov's avatar
Sergei Morozov committed
1116 1117
     * @param string|null $comment
     * @param string|null $type
Benjamin Morel's avatar
Benjamin Morel committed
1118
     *
Sergei Morozov's avatar
Sergei Morozov committed
1119
     * @return string|null
Benjamin Morel's avatar
Benjamin Morel committed
1120
     */
1121 1122
    public function removeDoctrineTypeFromComment($comment, $type)
    {
Sergei Morozov's avatar
Sergei Morozov committed
1123 1124 1125 1126
        if ($comment === null) {
            return null;
        }

1127
        return str_replace('(DC2Type:' . $type . ')', '', $comment);
1128
    }
Benjamin Eberlei's avatar
Benjamin Eberlei committed
1129
}