AbstractSchemaManager.php 28.8 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
use function call_user_func_array;
use function count;
use function func_get_args;
Sergei Morozov's avatar
Sergei Morozov committed
21
use function is_callable;
22 23 24
use function preg_match;
use function str_replace;
use function strtolower;
25

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

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

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

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

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

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

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

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

103
        $databases = $this->_conn->fetchAllAssociative($sql);
104 105

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

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

117
        $namespaces = $this->_conn->fetchAllAssociative($sql);
118 119 120 121

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

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

135
        $sql = $this->_platform->getListSequencesSQL($database);
136

137
        $sequences = $this->_conn->fetchAllAssociative($sql);
138

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 === null) {
160 161 162 163
            $database = $this->_conn->getDatabase();
        }

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

165
        $tableColumns = $this->_conn->fetchAllAssociative($sql);
166

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
        $tableIndexes = $this->_conn->fetchAllAssociative($sql);
184

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
     *
191 192
     * The usage of a string $tableNames is deprecated. Pass a one-element array instead.
     *
Sergei Morozov's avatar
Sergei Morozov committed
193
     * @param string|string[] $tableNames
Benjamin Morel's avatar
Benjamin Morel committed
194
     *
195
     * @return bool
196 197 198
     */
    public function tablesExist($tableNames)
    {
199
        $tableNames = array_map('strtolower', (array) $tableNames);
Benjamin Morel's avatar
Benjamin Morel committed
200

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

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

213
        $tables     = $this->_conn->fetchAllAssociative($sql);
214
        $tableNames = $this->_getPortableTablesList($tables);
Benjamin Morel's avatar
Benjamin Morel committed
215

216 217
        return $this->filterAssetNames($tableNames);
    }
218

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

234
        return array_values(array_filter($assetNames, $filter));
235 236
    }

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

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

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

        return $tables;
romanb's avatar
romanb committed
262 263
    }

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

277 278
        $indexes = $this->listTableIndexes($tableName);

Sergei Morozov's avatar
Sergei Morozov committed
279
        return new Table($tableName, $columns, $indexes, $foreignKeys);
280 281
    }

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

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

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

310
        $sql              = $this->_platform->getListTableForeignKeysSQL($table, $database);
311
        $tableForeignKeys = $this->_conn->fetchAllAssociative($sql);
312 313 314 315

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

316 317
    /* drop*() Methods */

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

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

    /**
Benjamin Morel's avatar
Benjamin Morel committed
345
     * Drops the index from the given table.
romanb's avatar
romanb committed
346
     *
347 348
     * @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
349 350
     *
     * @return void
romanb's avatar
romanb committed
351
     */
352
    public function dropIndex($index, $table)
romanb's avatar
romanb committed
353
    {
Steve Müller's avatar
Steve Müller committed
354
        if ($index instanceof Index) {
355
            $index = $index->getQuotedName($this->_platform);
356 357
        }

358
        $this->_execSql($this->_platform->getDropIndexSQL($index, $table));
romanb's avatar
romanb committed
359 360 361
    }

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

    /**
romanb's avatar
romanb committed
374
     * Drops a foreign key from a table.
romanb's avatar
romanb committed
375
     *
376 377
     * @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
378 379
     *
     * @return void
romanb's avatar
romanb committed
380
     */
381
    public function dropForeignKey($foreignKey, $table)
romanb's avatar
romanb committed
382
    {
383
        $this->_execSql($this->_platform->getDropForeignKeySQL($foreignKey, $table));
romanb's avatar
romanb committed
384 385 386
    }

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

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

    /* create*() Methods */

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

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

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

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

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

    /**
Benjamin Morel's avatar
Benjamin Morel committed
474 475
     * Creates a new foreign key.
     *
476 477
     * @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
478
     *
Benjamin Morel's avatar
Benjamin Morel committed
479
     * @return void
romanb's avatar
romanb committed
480
     */
481
    public function createForeignKey(ForeignKeyConstraint $foreignKey, $table)
romanb's avatar
romanb committed
482
    {
483
        $this->_execSql($this->_platform->getCreateForeignKeySQL($foreignKey, $table));
romanb's avatar
romanb committed
484 485
    }

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

496 497
    /* dropAndCreate*() Methods */

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

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

    /**
Benjamin Morel's avatar
Benjamin Morel committed
528
     * Drops and creates a new foreign key.
529
     *
530 531
     * @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
532 533
     *
     * @return void
534
     */
535
    public function dropAndCreateForeignKey(ForeignKeyConstraint $foreignKey, $table)
536
    {
537 538
        $this->tryMethod('dropForeignKey', $foreignKey, $table);
        $this->createForeignKey($foreignKey, $table);
539 540 541
    }

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

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

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

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

589 590
    /* alterTable() Methods */

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

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

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

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

637
        return $list;
638 639
    }

640 641 642
    /**
     * Converts a list of namespace names from the native DBMS data definition to a portable Doctrine definition.
     *
643
     * @param array<int, array<string, mixed>> $namespaces The list of namespace names in the native DBMS data definition.
644
     *
645
     * @return string[]
646 647 648
     */
    protected function getPortableNamespacesList(array $namespaces)
    {
649
        $namespacesList = [];
650 651 652 653 654 655 656 657

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

        return $namespacesList;
    }

Benjamin Morel's avatar
Benjamin Morel committed
658
    /**
659
     * @param mixed $database
Benjamin Morel's avatar
Benjamin Morel committed
660 661 662
     *
     * @return mixed
     */
663 664 665 666 667
    protected function _getPortableDatabaseDefinition($database)
    {
        return $database;
    }

668 669 670
    /**
     * Converts a namespace definition from the native DBMS data definition to a portable Doctrine definition.
     *
671
     * @param array<string, mixed> $namespace The native DBMS namespace definition.
672 673 674 675 676 677 678 679
     *
     * @return mixed
     */
    protected function getPortableNamespaceDefinition(array $namespace)
    {
        return $namespace;
    }

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

            if (! $value) {
694
                continue;
695
            }
696 697

            $list[] = $value;
698
        }
Benjamin Morel's avatar
Benjamin Morel committed
699

700
        return $list;
701 702
    }

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

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

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

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

733
        return $list;
734 735
    }

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

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

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

759
        return $list;
760 761
    }

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

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

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

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

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

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

806
            if ($column === null) {
807
                continue;
808
            }
809 810 811

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

814
        return $list;
815 816
    }

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

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

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
            if ($index === null) {
888
                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
            $list[] = $this->_getPortableTableDefinition($value);
907
        }
Benjamin Morel's avatar
Benjamin Morel committed
908

909
        return $list;
910 911
    }

Benjamin Morel's avatar
Benjamin Morel committed
912
    /**
913
     * @param mixed $table
Benjamin Morel's avatar
Benjamin Morel committed
914
     *
915
     * @return string
Benjamin Morel's avatar
Benjamin Morel committed
916
     */
917 918 919 920 921
    protected function _getPortableTableDefinition($table)
    {
        return $table;
    }

Benjamin Morel's avatar
Benjamin Morel committed
922
    /**
923
     * @param mixed[][] $users
Benjamin Morel's avatar
Benjamin Morel committed
924
     *
925
     * @return string[][]
Benjamin Morel's avatar
Benjamin Morel committed
926
     */
927 928
    protected function _getPortableUsersList($users)
    {
929
        $list = [];
930
        foreach ($users as $value) {
931
            $list[] = $this->_getPortableUserDefinition($value);
932
        }
Benjamin Morel's avatar
Benjamin Morel committed
933

934
        return $list;
935 936
    }

Benjamin Morel's avatar
Benjamin Morel committed
937
    /**
938
     * @param string[] $user
Benjamin Morel's avatar
Benjamin Morel committed
939
     *
940
     * @return string[]
Benjamin Morel's avatar
Benjamin Morel committed
941
     */
942 943 944 945 946
    protected function _getPortableUserDefinition($user)
    {
        return $user;
    }

Benjamin Morel's avatar
Benjamin Morel committed
947
    /**
948
     * @param mixed[][] $views
949
     *
950
     * @return View[]
Benjamin Morel's avatar
Benjamin Morel committed
951
     */
952 953
    protected function _getPortableViewsList($views)
    {
954
        $list = [];
955
        foreach ($views as $value) {
956 957
            $view = $this->_getPortableViewDefinition($value);

958
            if ($view === false) {
959
                continue;
960
            }
961 962 963

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

966
        return $list;
967 968
    }

Benjamin Morel's avatar
Benjamin Morel committed
969
    /**
970
     * @param mixed[] $view
Benjamin Morel's avatar
Benjamin Morel committed
971
     *
972
     * @return View|false
Benjamin Morel's avatar
Benjamin Morel committed
973
     */
974 975
    protected function _getPortableViewDefinition($view)
    {
976
        return false;
977 978
    }

Benjamin Morel's avatar
Benjamin Morel committed
979
    /**
980
     * @param mixed[][] $tableForeignKeys
Benjamin Morel's avatar
Benjamin Morel committed
981
     *
982
     * @return ForeignKeyConstraint[]
Benjamin Morel's avatar
Benjamin Morel committed
983
     */
984 985
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
    {
986
        $list = [];
987

Sergei Morozov's avatar
Sergei Morozov committed
988 989
        foreach ($tableForeignKeys as $value) {
            $list[] = $this->_getPortableTableForeignKeyDefinition($value);
990
        }
Benjamin Morel's avatar
Benjamin Morel committed
991

992 993 994
        return $list;
    }

Benjamin Morel's avatar
Benjamin Morel committed
995
    /**
996
     * @param mixed $tableForeignKey
Benjamin Morel's avatar
Benjamin Morel committed
997
     *
998
     * @return ForeignKeyConstraint
Benjamin Morel's avatar
Benjamin Morel committed
999
     */
1000 1001 1002 1003
    protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
    {
        return $tableForeignKey;
    }
1004

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

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1018
     * Creates a schema instance for the current database.
1019
     *
1020
     * @return Schema
1021 1022 1023
     */
    public function createSchema()
    {
1024
        $namespaces = [];
1025 1026 1027 1028 1029

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

1030
        $sequences = [];
1031

Steve Müller's avatar
Steve Müller committed
1032
        if ($this->_platform->supportsSequences()) {
1033 1034
            $sequences = $this->listSequences();
        }
1035

1036 1037
        $tables = $this->listTables();

1038
        return new Schema($tables, $sequences, $this->createSchemaConfig(), $namespaces);
1039 1040 1041
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1042
     * Creates the configuration for this schema.
1043
     *
1044
     * @return SchemaConfig
1045 1046 1047 1048 1049
     */
    public function createSchemaConfig()
    {
        $schemaConfig = new SchemaConfig();
        $schemaConfig->setMaxIdentifierLength($this->_platform->getMaxIdentifierLength());
1050 1051 1052 1053 1054

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

1056
        $params = $this->_conn->getParams();
1057 1058
        if (! isset($params['defaultTableOptions'])) {
            $params['defaultTableOptions'] = [];
1059
        }
Grégoire Paris's avatar
Grégoire Paris committed
1060

1061 1062 1063
        if (! isset($params['defaultTableOptions']['charset']) && isset($params['charset'])) {
            $params['defaultTableOptions']['charset'] = $params['charset'];
        }
Grégoire Paris's avatar
Grégoire Paris committed
1064

1065
        $schemaConfig->setDefaultTableOptions($params['defaultTableOptions']);
1066

1067
        return $schemaConfig;
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.
     *
1080
     * @return string[]
1081
     */
1082 1083
    public function getSchemaSearchPaths()
    {
1084
        return [$this->_conn->getDatabase()];
1085 1086
    }

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

1102 1103 1104
        return $currentType;
    }

Benjamin Morel's avatar
Benjamin Morel committed
1105
    /**
Sergei Morozov's avatar
Sergei Morozov committed
1106 1107
     * @param string|null $comment
     * @param string|null $type
Benjamin Morel's avatar
Benjamin Morel committed
1108
     *
Sergei Morozov's avatar
Sergei Morozov committed
1109
     * @return string|null
Benjamin Morel's avatar
Benjamin Morel committed
1110
     */
1111 1112
    public function removeDoctrineTypeFromComment($comment, $type)
    {
Sergei Morozov's avatar
Sergei Morozov committed
1113 1114 1115 1116
        if ($comment === null) {
            return null;
        }

1117
        return str_replace('(DC2Type:' . $type . ')', '', $comment);
1118
    }
Benjamin Eberlei's avatar
Benjamin Eberlei committed
1119
}