SchemaManagerFunctionalTestCase.php 57.8 KB
Newer Older
1 2 3 4
<?php

namespace Doctrine\Tests\DBAL\Functional\Schema;

5 6
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Events;
Thomas Müller's avatar
Thomas Müller committed
7
use Doctrine\DBAL\Platforms\OraclePlatform;
8 9
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\ColumnDiff;
jeroendedauw's avatar
jeroendedauw committed
10
use Doctrine\DBAL\Schema\Comparator;
11
use Doctrine\DBAL\Schema\Sequence;
jeroendedauw's avatar
jeroendedauw committed
12
use Doctrine\DBAL\Schema\Table;
13
use Doctrine\DBAL\Schema\TableDiff;
jeroendedauw's avatar
jeroendedauw committed
14
use Doctrine\DBAL\Types\Type;
15

romanb's avatar
romanb committed
16
class SchemaManagerFunctionalTestCase extends \Doctrine\Tests\DbalFunctionalTestCase
17
{
18 19 20 21
    /**
     * @var \Doctrine\DBAL\Schema\AbstractSchemaManager
     */
    protected $_sm;
22

23 24 25
    protected function getPlatformName()
    {
        $class = get_class($this);
26 27 28
        $e = explode('\\', $class);
        $testClass = end($e);
        $dbms = strtolower(str_replace('SchemaManagerTest', null, $testClass));
29
        return $dbms;
30
    }
31 32 33 34

    protected function setUp()
    {
        parent::setUp();
35 36

        $dbms = $this->getPlatformName();
37

38
        if ($this->_conn->getDatabasePlatform()->getName() !== $dbms) {
39
            $this->markTestSkipped(get_class($this) . ' requires the use of ' . $dbms);
40 41 42 43 44
        }

        $this->_sm = $this->_conn->getSchemaManager();
    }

45 46 47 48 49 50 51 52 53 54 55
    /**
     * @group DBAL-1220
     */
    public function testDropsDatabaseWithActiveConnections()
    {
        if (! $this->_sm->getDatabasePlatform()->supportsCreateDropDatabase()) {
            $this->markTestSkipped('Cannot drop Database client side with this Driver.');
        }

        $this->_sm->dropAndCreateDatabase('test_drop_database');

Thomas Müller's avatar
Thomas Müller committed
56 57
        $knownDatabases = $this->_sm->listDatabases();
        if ($this->_conn->getDatabasePlatform() instanceof OraclePlatform) {
58
            self::assertContains('TEST_DROP_DATABASE', $knownDatabases);
Thomas Müller's avatar
Thomas Müller committed
59
        } else {
60
            self::assertContains('test_drop_database', $knownDatabases);
Thomas Müller's avatar
Thomas Müller committed
61
        }
62 63

        $params = $this->_conn->getParams();
Thomas Müller's avatar
Thomas Müller committed
64 65 66 67 68
        if ($this->_conn->getDatabasePlatform() instanceof OraclePlatform) {
            $params['user'] = 'test_drop_database';
        } else {
            $params['dbname'] = 'test_drop_database';
        }
69

70 71
        $user = $params['user'] ?? null;
        $password = $params['password'] ?? null;
72 73 74

        $connection = $this->_conn->getDriver()->connect($params, $user, $password);

75
        self::assertInstanceOf('Doctrine\DBAL\Driver\Connection', $connection);
76 77 78

        $this->_sm->dropDatabase('test_drop_database');

79
        self::assertNotContains('test_drop_database', $this->_sm->listDatabases());
80 81
    }

Benjamin Eberlei's avatar
Benjamin Eberlei committed
82 83 84 85 86
    /**
     * @group DBAL-195
     */
    public function testDropAndCreateSequence()
    {
Luís Cobucci's avatar
Luís Cobucci committed
87
        if ( ! $this->_conn->getDatabasePlatform()->supportsSequences()) {
Benjamin Eberlei's avatar
Benjamin Eberlei committed
88 89 90
            $this->markTestSkipped($this->_conn->getDriver()->getName().' does not support sequences.');
        }

Luís Cobucci's avatar
Luís Cobucci committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
        $name = 'dropcreate_sequences_test_seq';

        $this->_sm->dropAndCreateSequence(new \Doctrine\DBAL\Schema\Sequence($name, 20, 10));

        self::assertTrue($this->hasElementWithName($this->_sm->listSequences(), $name));
    }

    private function hasElementWithName(array $items, string $name) : bool
    {
        $filteredList = array_filter(
            $items,
            function (\Doctrine\DBAL\Schema\AbstractAsset $item) use ($name) : bool {
                return $item->getShortestName($item->getNamespaceName()) === $name;
            }
        );

        return count($filteredList) === 1;
Benjamin Eberlei's avatar
Benjamin Eberlei committed
108 109
    }

110 111 112 113 114 115
    public function testListSequences()
    {
        if(!$this->_conn->getDatabasePlatform()->supportsSequences()) {
            $this->markTestSkipped($this->_conn->getDriver()->getName().' does not support sequences.');
        }

116 117
        $sequence = new \Doctrine\DBAL\Schema\Sequence('list_sequences_test_seq', 20, 10);
        $this->_sm->createSequence($sequence);
118

119
        $sequences = $this->_sm->listSequences();
120

121
        self::assertInternalType('array', $sequences, 'listSequences() should return an array.');
122 123

        $foundSequence = null;
jeroendedauw's avatar
jeroendedauw committed
124
        foreach($sequences as $sequence) {
125
            self::assertInstanceOf('Doctrine\DBAL\Schema\Sequence', $sequence, 'Array elements of listSequences() should be Sequence instances.');
126 127 128 129 130
            if(strtolower($sequence->getName()) == 'list_sequences_test_seq') {
                $foundSequence = $sequence;
            }
        }

131 132 133
        self::assertNotNull($foundSequence, "Sequence with name 'list_sequences_test_seq' was not found.");
        self::assertEquals(20, $foundSequence->getAllocationSize(), "Allocation Size is expected to be 20.");
        self::assertEquals(10, $foundSequence->getInitialValue(), "Initial Value is expected to be 10.");
134 135
    }

136 137
    public function testListDatabases()
    {
138 139 140 141
        if (!$this->_sm->getDatabasePlatform()->supportsCreateDropDatabase()) {
            $this->markTestSkipped('Cannot drop Database client side with this Driver.');
        }

142 143 144
        $this->_sm->dropAndCreateDatabase('test_create_database');
        $databases = $this->_sm->listDatabases();

145
        $databases = array_map('strtolower', $databases);
146

147
        self::assertContains('test_create_database', $databases);
148 149
    }

150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    /**
     * @group DBAL-1058
     */
    public function testListNamespaceNames()
    {
        if (!$this->_sm->getDatabasePlatform()->supportsSchemas()) {
            $this->markTestSkipped('Platform does not support schemas.');
        }

        // Currently dropping schemas is not supported, so we have to workaround here.
        $namespaces = $this->_sm->listNamespaceNames();
        $namespaces = array_map('strtolower', $namespaces);

        if (!in_array('test_create_schema', $namespaces)) {
            $this->_conn->executeUpdate($this->_sm->getDatabasePlatform()->getCreateSchemaSQL('test_create_schema'));

            $namespaces = $this->_sm->listNamespaceNames();
            $namespaces = array_map('strtolower', $namespaces);
        }

170
        self::assertContains('test_create_schema', $namespaces);
171 172
    }

173 174 175 176 177
    public function testListTables()
    {
        $this->createTestTable('list_tables_test');
        $tables = $this->_sm->listTables();

178 179
        self::assertInternalType('array', $tables);
        self::assertTrue(count($tables) > 0, "List Tables has to find at least one table named 'list_tables_test'.");
180 181

        $foundTable = false;
jeroendedauw's avatar
jeroendedauw committed
182
        foreach ($tables as $table) {
183
            self::assertInstanceOf('Doctrine\DBAL\Schema\Table', $table);
184
            if (strtolower($table->getName()) == 'list_tables_test') {
185 186
                $foundTable = true;

187 188 189
                self::assertTrue($table->hasColumn('id'));
                self::assertTrue($table->hasColumn('test'));
                self::assertTrue($table->hasColumn('foreign_key_test'));
190 191
            }
        }
192

193
        self::assertTrue( $foundTable , "The 'list_tables_test' table has to be found.");
194 195
    }

196
    public function createListTableColumns()
197
    {
198
        $table = new Table('list_table_columns');
199
        $table->addColumn('id', 'integer', array('notnull' => true));
200 201
        $table->addColumn('test', 'string', array('length' => 255, 'notnull' => false, 'default' => 'expected default'));
        $table->addColumn('foo', 'text', array('notnull' => true));
202 203 204 205
        $table->addColumn('bar', 'decimal', array('precision' => 10, 'scale' => 4, 'notnull' => false));
        $table->addColumn('baz1', 'datetime');
        $table->addColumn('baz2', 'time');
        $table->addColumn('baz3', 'date');
206
        $table->setPrimaryKey(array('id'));
207

208 209 210 211 212 213 214
        return $table;
    }

    public function testListTableColumns()
    {
        $table = $this->createListTableColumns();

215
        $this->_sm->dropAndCreateTable($table);
216 217

        $columns = $this->_sm->listTableColumns('list_table_columns');
218
        $columnsKeys = array_keys($columns);
219

220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
        self::assertArrayHasKey('id', $columns);
        self::assertEquals(0, array_search('id', $columnsKeys));
        self::assertEquals('id',   strtolower($columns['id']->getname()));
        self::assertInstanceOf('Doctrine\DBAL\Types\IntegerType', $columns['id']->gettype());
        self::assertEquals(false,  $columns['id']->getunsigned());
        self::assertEquals(true,   $columns['id']->getnotnull());
        self::assertEquals(null,   $columns['id']->getdefault());
        self::assertInternalType('array',  $columns['id']->getPlatformOptions());

        self::assertArrayHasKey('test', $columns);
        self::assertEquals(1, array_search('test', $columnsKeys));
        self::assertEquals('test', strtolower($columns['test']->getname()));
        self::assertInstanceOf('Doctrine\DBAL\Types\StringType', $columns['test']->gettype());
        self::assertEquals(255,    $columns['test']->getlength());
        self::assertEquals(false,  $columns['test']->getfixed());
        self::assertEquals(false,  $columns['test']->getnotnull());
        self::assertEquals('expected default',   $columns['test']->getdefault());
        self::assertInternalType('array',  $columns['test']->getPlatformOptions());

        self::assertEquals('foo',  strtolower($columns['foo']->getname()));
        self::assertEquals(2, array_search('foo', $columnsKeys));
        self::assertInstanceOf('Doctrine\DBAL\Types\TextType', $columns['foo']->gettype());
        self::assertEquals(false,  $columns['foo']->getunsigned());
        self::assertEquals(false,  $columns['foo']->getfixed());
        self::assertEquals(true,   $columns['foo']->getnotnull());
        self::assertEquals(null,   $columns['foo']->getdefault());
        self::assertInternalType('array',  $columns['foo']->getPlatformOptions());

        self::assertEquals('bar',  strtolower($columns['bar']->getname()));
        self::assertEquals(3, array_search('bar', $columnsKeys));
        self::assertInstanceOf('Doctrine\DBAL\Types\DecimalType', $columns['bar']->gettype());
        self::assertEquals(null,   $columns['bar']->getlength());
        self::assertEquals(10,     $columns['bar']->getprecision());
        self::assertEquals(4,      $columns['bar']->getscale());
        self::assertEquals(false,  $columns['bar']->getunsigned());
        self::assertEquals(false,  $columns['bar']->getfixed());
        self::assertEquals(false,  $columns['bar']->getnotnull());
        self::assertEquals(null,   $columns['bar']->getdefault());
        self::assertInternalType('array',  $columns['bar']->getPlatformOptions());

        self::assertEquals('baz1', strtolower($columns['baz1']->getname()));
        self::assertEquals(4, array_search('baz1', $columnsKeys));
        self::assertInstanceOf('Doctrine\DBAL\Types\DateTimeType', $columns['baz1']->gettype());
        self::assertEquals(true,   $columns['baz1']->getnotnull());
        self::assertEquals(null,   $columns['baz1']->getdefault());
        self::assertInternalType('array',  $columns['baz1']->getPlatformOptions());

        self::assertEquals('baz2', strtolower($columns['baz2']->getname()));
        self::assertEquals(5, array_search('baz2', $columnsKeys));
        self::assertContains($columns['baz2']->gettype()->getName(), array('time', 'date', 'datetime'));
        self::assertEquals(true,   $columns['baz2']->getnotnull());
        self::assertEquals(null,   $columns['baz2']->getdefault());
        self::assertInternalType('array',  $columns['baz2']->getPlatformOptions());

        self::assertEquals('baz3', strtolower($columns['baz3']->getname()));
        self::assertEquals(6, array_search('baz3', $columnsKeys));
        self::assertContains($columns['baz3']->gettype()->getName(), array('time', 'date', 'datetime'));
        self::assertEquals(true,   $columns['baz3']->getnotnull());
        self::assertEquals(null,   $columns['baz3']->getdefault());
        self::assertInternalType('array',  $columns['baz3']->getPlatformOptions());
280 281
    }

282 283 284 285 286 287 288 289 290 291 292 293 294 295
    /**
     * @group DBAL-1078
     */
    public function testListTableColumnsWithFixedStringColumn()
    {
        $tableName = 'test_list_table_fixed_string';

        $table = new Table($tableName);
        $table->addColumn('column_char', 'string', array('fixed' => true, 'length' => 2));

        $this->_sm->createTable($table);

        $columns = $this->_sm->listTableColumns($tableName);

296 297 298 299
        self::assertArrayHasKey('column_char', $columns);
        self::assertInstanceOf('Doctrine\DBAL\Types\StringType', $columns['column_char']->getType());
        self::assertTrue($columns['column_char']->getFixed());
        self::assertSame(2, $columns['column_char']->getLength());
300 301
    }

302 303 304 305 306 307
    public function testListTableColumnsDispatchEvent()
    {
        $table = $this->createListTableColumns();

        $this->_sm->dropAndCreateTable($table);

308 309 310 311
        $listenerMock = $this
            ->getMockBuilder('ListTableColumnsDispatchEventListener')
            ->setMethods(['onSchemaColumnDefinition'])
            ->getMock();
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
        $listenerMock
            ->expects($this->exactly(7))
            ->method('onSchemaColumnDefinition');

        $oldEventManager = $this->_sm->getDatabasePlatform()->getEventManager();

        $eventManager = new EventManager();
        $eventManager->addEventListener(array(Events::onSchemaColumnDefinition), $listenerMock);

        $this->_sm->getDatabasePlatform()->setEventManager($eventManager);

        $this->_sm->listTableColumns('list_table_columns');

        $this->_sm->getDatabasePlatform()->setEventManager($oldEventManager);
    }

328 329 330 331 332 333 334 335
    public function testListTableIndexesDispatchEvent()
    {
        $table = $this->getTestTable('list_table_indexes_test');
        $table->addUniqueIndex(array('test'), 'test_index_name');
        $table->addIndex(array('id', 'test'), 'test_composite_idx');

        $this->_sm->dropAndCreateTable($table);

336 337 338 339
        $listenerMock = $this
            ->getMockBuilder('ListTableIndexesDispatchEventListener')
            ->setMethods(['onSchemaIndexDefinition'])
            ->getMock();
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
        $listenerMock
            ->expects($this->exactly(3))
            ->method('onSchemaIndexDefinition');

        $oldEventManager = $this->_sm->getDatabasePlatform()->getEventManager();

        $eventManager = new EventManager();
        $eventManager->addEventListener(array(Events::onSchemaIndexDefinition), $listenerMock);

        $this->_sm->getDatabasePlatform()->setEventManager($eventManager);

        $this->_sm->listTableIndexes('list_table_indexes_test');

        $this->_sm->getDatabasePlatform()->setEventManager($oldEventManager);
    }

356 357 358 359 360 361 362
    public function testDiffListTableColumns()
    {
        if ($this->_sm->getDatabasePlatform()->getName() == 'oracle') {
            $this->markTestSkipped('Does not work with Oracle, since it cannot detect DateTime, Date and Time differenecs (at the moment).');
        }

        $offlineTable = $this->createListTableColumns();
363
        $this->_sm->dropAndCreateTable($offlineTable);
364 365 366 367 368
        $onlineTable = $this->_sm->listTableDetails('list_table_columns');

        $comparator = new \Doctrine\DBAL\Schema\Comparator();
        $diff = $comparator->diffTable($offlineTable, $onlineTable);

369
        self::assertFalse($diff, "No differences should be detected with the offline vs online schema.");
370 371
    }

372 373
    public function testListTableIndexes()
    {
374
        $table = $this->getTestCompositeTable('list_table_indexes_test');
375 376
        $table->addUniqueIndex(array('test'), 'test_index_name');
        $table->addIndex(array('id', 'test'), 'test_composite_idx');
377

378
        $this->_sm->dropAndCreateTable($table);
379 380

        $tableIndexes = $this->_sm->listTableIndexes('list_table_indexes_test');
381

382
        self::assertEquals(3, count($tableIndexes));
383

384 385 386 387
        self::assertArrayHasKey('primary', $tableIndexes, 'listTableIndexes() has to return a "primary" array key.');
        self::assertEquals(array('id', 'other_id'), array_map('strtolower', $tableIndexes['primary']->getColumns()));
        self::assertTrue($tableIndexes['primary']->isUnique());
        self::assertTrue($tableIndexes['primary']->isPrimary());
388

389 390 391 392
        self::assertEquals('test_index_name', strtolower($tableIndexes['test_index_name']->getName()));
        self::assertEquals(array('test'), array_map('strtolower', $tableIndexes['test_index_name']->getColumns()));
        self::assertTrue($tableIndexes['test_index_name']->isUnique());
        self::assertFalse($tableIndexes['test_index_name']->isPrimary());
393

394 395 396 397
        self::assertEquals('test_composite_idx', strtolower($tableIndexes['test_composite_idx']->getName()));
        self::assertEquals(array('id', 'test'), array_map('strtolower', $tableIndexes['test_composite_idx']->getColumns()));
        self::assertFalse($tableIndexes['test_composite_idx']->isUnique());
        self::assertFalse($tableIndexes['test_composite_idx']->isPrimary());
398 399 400 401
    }

    public function testDropAndCreateIndex()
    {
402 403 404
        $table = $this->getTestTable('test_create_index');
        $table->addUniqueIndex(array('test'), 'test');
        $this->_sm->dropAndCreateTable($table);
405

406
        $this->_sm->dropAndCreateIndex($table->getIndex('test'), $table);
407
        $tableIndexes = $this->_sm->listTableIndexes('test_create_index');
408
        self::assertInternalType('array', $tableIndexes);
409

410 411 412 413
        self::assertEquals('test',        strtolower($tableIndexes['test']->getName()));
        self::assertEquals(array('test'), array_map('strtolower', $tableIndexes['test']->getColumns()));
        self::assertTrue($tableIndexes['test']->isUnique());
        self::assertFalse($tableIndexes['test']->isPrimary());
414 415
    }

416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
    public function testCreateTableWithForeignKeys()
    {
        if(!$this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) {
            $this->markTestSkipped('Platform does not support foreign keys.');
        }

        $tableB = $this->getTestTable('test_foreign');

        $this->_sm->dropAndCreateTable($tableB);

        $tableA = $this->getTestTable('test_create_fk');
        $tableA->addForeignKeyConstraint('test_foreign', array('foreign_key_test'), array('id'));

        $this->_sm->dropAndCreateTable($tableA);

431 432
        $fkTable = $this->_sm->listTableDetails('test_create_fk');
        $fkConstraints = $fkTable->getForeignKeys();
433
        self::assertEquals(1, count($fkConstraints), "Table 'test_create_fk1' has to have one foreign key.");
434 435

        $fkConstraint = current($fkConstraints);
436 437 438 439
        self::assertInstanceOf('\Doctrine\DBAL\Schema\ForeignKeyConstraint', $fkConstraint);
        self::assertEquals('test_foreign',             strtolower($fkConstraint->getForeignTableName()));
        self::assertEquals(array('foreign_key_test'),  array_map('strtolower', $fkConstraint->getColumns()));
        self::assertEquals(array('id'),                array_map('strtolower', $fkConstraint->getForeignColumns()));
440

441
        self::assertTrue($fkTable->columnsAreIndexed($fkConstraint->getColumns()), "The columns of a foreign key constraint should always be indexed.");
442 443
    }

444 445 446 447 448 449 450 451 452
    public function testListForeignKeys()
    {
        if(!$this->_conn->getDatabasePlatform()->supportsForeignKeyConstraints()) {
            $this->markTestSkipped('Does not support foreign key constraints.');
        }

        $this->createTestTable('test_create_fk1');
        $this->createTestTable('test_create_fk2');

453
        $foreignKey = new \Doctrine\DBAL\Schema\ForeignKeyConstraint(
454
            array('foreign_key_test'), 'test_create_fk2', array('id'), 'foreign_key_test_fk', array('onDelete' => 'CASCADE')
455 456
        );

457
        $this->_sm->createForeignKey($foreignKey, 'test_create_fk1');
458 459 460

        $fkeys = $this->_sm->listTableForeignKeys('test_create_fk1');

461
        self::assertEquals(1, count($fkeys), "Table 'test_create_fk1' has to have one foreign key.");
462

463 464 465 466
        self::assertInstanceOf('Doctrine\DBAL\Schema\ForeignKeyConstraint', $fkeys[0]);
        self::assertEquals(array('foreign_key_test'),  array_map('strtolower', $fkeys[0]->getLocalColumns()));
        self::assertEquals(array('id'),                array_map('strtolower', $fkeys[0]->getForeignColumns()));
        self::assertEquals('test_create_fk2',          strtolower($fkeys[0]->getForeignTableName()));
467

468
        if($fkeys[0]->hasOption('onDelete')) {
469
            self::assertEquals('CASCADE', $fkeys[0]->getOption('onDelete'));
470
        }
471 472
    }

473 474 475 476 477
    protected function getCreateExampleViewSql()
    {
        $this->markTestSkipped('No Create Example View SQL was defined for this SchemaManager');
    }

478 479 480 481 482
    public function testCreateSchema()
    {
        $this->createTestTable('test_table');

        $schema = $this->_sm->createSchema();
483
        self::assertTrue($schema->hasTable('test_table'));
484 485
    }

486 487 488 489 490 491
    public function testAlterTableScenario()
    {
        if(!$this->_sm->getDatabasePlatform()->supportsAlterTable()) {
            $this->markTestSkipped('Alter Table is not supported by this platform.');
        }

492
        $alterTable = $this->createTestTable('alter_table');
493 494 495
        $this->createTestTable('alter_table_foreign');

        $table = $this->_sm->listTableDetails('alter_table');
496 497 498 499 500
        self::assertTrue($table->hasColumn('id'));
        self::assertTrue($table->hasColumn('test'));
        self::assertTrue($table->hasColumn('foreign_key_test'));
        self::assertEquals(0, count($table->getForeignKeys()));
        self::assertEquals(1, count($table->getIndexes()));
501 502

        $tableDiff = new \Doctrine\DBAL\Schema\TableDiff("alter_table");
503
        $tableDiff->fromTable = $alterTable;
504 505 506 507 508 509
        $tableDiff->addedColumns['foo'] = new \Doctrine\DBAL\Schema\Column('foo', Type::getType('integer'));
        $tableDiff->removedColumns['test'] = $table->getColumn('test');

        $this->_sm->alterTable($tableDiff);

        $table = $this->_sm->listTableDetails('alter_table');
510 511
        self::assertFalse($table->hasColumn('test'));
        self::assertTrue($table->hasColumn('foo'));
512 513

        $tableDiff = new \Doctrine\DBAL\Schema\TableDiff("alter_table");
514
        $tableDiff->fromTable = $table;
515 516 517 518 519
        $tableDiff->addedIndexes[] = new \Doctrine\DBAL\Schema\Index('foo_idx', array('foo'));

        $this->_sm->alterTable($tableDiff);

        $table = $this->_sm->listTableDetails('alter_table');
520 521 522 523 524
        self::assertEquals(2, count($table->getIndexes()));
        self::assertTrue($table->hasIndex('foo_idx'));
        self::assertEquals(array('foo'), array_map('strtolower', $table->getIndex('foo_idx')->getColumns()));
        self::assertFalse($table->getIndex('foo_idx')->isPrimary());
        self::assertFalse($table->getIndex('foo_idx')->isUnique());
525 526

        $tableDiff = new \Doctrine\DBAL\Schema\TableDiff("alter_table");
527
        $tableDiff->fromTable = $table;
528 529 530 531 532
        $tableDiff->changedIndexes[] = new \Doctrine\DBAL\Schema\Index('foo_idx', array('foo', 'foreign_key_test'));

        $this->_sm->alterTable($tableDiff);

        $table = $this->_sm->listTableDetails('alter_table');
533 534 535
        self::assertEquals(2, count($table->getIndexes()));
        self::assertTrue($table->hasIndex('foo_idx'));
        self::assertEquals(array('foo', 'foreign_key_test'), array_map('strtolower', $table->getIndex('foo_idx')->getColumns()));
536 537

        $tableDiff = new \Doctrine\DBAL\Schema\TableDiff("alter_table");
538
        $tableDiff->fromTable = $table;
539 540 541 542 543
        $tableDiff->renamedIndexes['foo_idx'] = new \Doctrine\DBAL\Schema\Index('bar_idx', array('foo', 'foreign_key_test'));

        $this->_sm->alterTable($tableDiff);

        $table = $this->_sm->listTableDetails('alter_table');
544 545 546 547 548 549
        self::assertEquals(2, count($table->getIndexes()));
        self::assertTrue($table->hasIndex('bar_idx'));
        self::assertFalse($table->hasIndex('foo_idx'));
        self::assertEquals(array('foo', 'foreign_key_test'), array_map('strtolower', $table->getIndex('bar_idx')->getColumns()));
        self::assertFalse($table->getIndex('bar_idx')->isPrimary());
        self::assertFalse($table->getIndex('bar_idx')->isUnique());
550 551 552 553

        $tableDiff = new \Doctrine\DBAL\Schema\TableDiff("alter_table");
        $tableDiff->fromTable = $table;
        $tableDiff->removedIndexes[] = new \Doctrine\DBAL\Schema\Index('bar_idx', array('foo', 'foreign_key_test'));
554 555 556 557 558 559 560
        $fk = new \Doctrine\DBAL\Schema\ForeignKeyConstraint(array('foreign_key_test'), 'alter_table_foreign', array('id'));
        $tableDiff->addedForeignKeys[] = $fk;

        $this->_sm->alterTable($tableDiff);
        $table = $this->_sm->listTableDetails('alter_table');

        // dont check for index size here, some platforms automatically add indexes for foreign keys.
561
        self::assertFalse($table->hasIndex('bar_idx'));
562

563 564
        if ($this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) {
            $fks = $table->getForeignKeys();
565
            self::assertCount(1, $fks);
566
            $foreignKey = current($fks);
567 568 569
            self::assertEquals('alter_table_foreign', strtolower($foreignKey->getForeignTableName()));
            self::assertEquals(array('foreign_key_test'), array_map('strtolower', $foreignKey->getColumns()));
            self::assertEquals(array('id'), array_map('strtolower', $foreignKey->getForeignColumns()));
570
        }
571 572
    }

573
    public function testCreateAndListViews()
574
    {
575 576 577 578
        if (!$this->_sm->getDatabasePlatform()->supportsViews()) {
            $this->markTestSkipped('Views is not supported by this platform.');
        }

579
        $this->createTestTable('view_test_table');
580

581 582
        $name = "doctrine_test_view";
        $sql = "SELECT * FROM view_test_table";
583

584
        $view = new \Doctrine\DBAL\Schema\View($name, $sql);
585

586 587
        $this->_sm->dropAndCreateView($view);

Luís Cobucci's avatar
Luís Cobucci committed
588
        self::assertTrue($this->hasElementWithName($this->_sm->listViews(), $name));
589 590
    }

591 592 593 594 595 596
    public function testAutoincrementDetection()
    {
        if (!$this->_sm->getDatabasePlatform()->supportsIdentityColumns()) {
            $this->markTestSkipped('This test is only supported on platforms that have autoincrement');
        }

597
        $table = new Table('test_autoincrement');
598 599 600 601 602 603 604
        $table->setSchemaConfig($this->_sm->createSchemaConfig());
        $table->addColumn('id', 'integer', array('autoincrement' => true));
        $table->setPrimaryKey(array('id'));

        $this->_sm->createTable($table);

        $inferredTable = $this->_sm->listTableDetails('test_autoincrement');
605 606
        self::assertTrue($inferredTable->hasColumn('id'));
        self::assertTrue($inferredTable->getColumn('id')->getAutoincrement());
607
    }
608 609 610 611 612 613 614 615 616

    /**
     * @group DBAL-792
     */
    public function testAutoincrementDetectionMulticolumns()
    {
        if (!$this->_sm->getDatabasePlatform()->supportsIdentityColumns()) {
            $this->markTestSkipped('This test is only supported on platforms that have autoincrement');
        }
617

618
        $table = new Table('test_not_autoincrement');
619 620 621 622 623 624 625 626
        $table->setSchemaConfig($this->_sm->createSchemaConfig());
        $table->addColumn('id', 'integer');
        $table->addColumn('other_id', 'integer');
        $table->setPrimaryKey(array('id', 'other_id'));

        $this->_sm->createTable($table);

        $inferredTable = $this->_sm->listTableDetails('test_not_autoincrement');
627 628
        self::assertTrue($inferredTable->hasColumn('id'));
        self::assertFalse($inferredTable->getColumn('id')->getAutoincrement());
629
    }
630

631 632 633 634 635 636 637 638
    /**
     * @group DDC-887
     */
    public function testUpdateSchemaWithForeignKeyRenaming()
    {
        if (!$this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) {
            $this->markTestSkipped('This test is only supported on platforms that have foreign keys.');
        }
639

640
        $table = new Table('test_fk_base');
641 642
        $table->addColumn('id', 'integer');
        $table->setPrimaryKey(array('id'));
643

644
        $tableFK = new Table('test_fk_rename');
645 646 647 648 649 650
        $tableFK->setSchemaConfig($this->_sm->createSchemaConfig());
        $tableFK->addColumn('id', 'integer');
        $tableFK->addColumn('fk_id', 'integer');
        $tableFK->setPrimaryKey(array('id'));
        $tableFK->addIndex(array('fk_id'), 'fk_idx');
        $tableFK->addForeignKeyConstraint('test_fk_base', array('fk_id'), array('id'));
651

652 653
        $this->_sm->createTable($table);
        $this->_sm->createTable($tableFK);
654

655
        $tableFKNew = new Table('test_fk_rename');
656 657 658 659 660 661
        $tableFKNew->setSchemaConfig($this->_sm->createSchemaConfig());
        $tableFKNew->addColumn('id', 'integer');
        $tableFKNew->addColumn('rename_fk_id', 'integer');
        $tableFKNew->setPrimaryKey(array('id'));
        $tableFKNew->addIndex(array('rename_fk_id'), 'fk_idx');
        $tableFKNew->addForeignKeyConstraint('test_fk_base', array('rename_fk_id'), array('id'));
662

663 664
        $c = new \Doctrine\DBAL\Schema\Comparator();
        $tableDiff = $c->diffTable($tableFK, $tableFKNew);
665

666
        $this->_sm->alterTable($tableDiff);
Luís Cobucci's avatar
Luís Cobucci committed
667 668 669 670 671 672 673

        $table       = $this->_sm->listTableDetails('test_fk_rename');
        $foreignKeys = $table->getForeignKeys();

        self::assertTrue($table->hasColumn('rename_fk_id'));
        self::assertCount(1, $foreignKeys);
        self::assertSame(['rename_fk_id'], array_map('strtolower', current($foreignKeys)->getColumns()));
674
    }
675

676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
    /**
     * @group DBAL-1062
     */
    public function testRenameIndexUsedInForeignKeyConstraint()
    {
        if (! $this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) {
            $this->markTestSkipped('This test is only supported on platforms that have foreign keys.');
        }

        $primaryTable = new Table('test_rename_index_primary');
        $primaryTable->addColumn('id', 'integer');
        $primaryTable->setPrimaryKey(array('id'));

        $foreignTable = new Table('test_rename_index_foreign');
        $foreignTable->addColumn('fk', 'integer');
        $foreignTable->addIndex(array('fk'), 'rename_index_fk_idx');
        $foreignTable->addForeignKeyConstraint(
            'test_rename_index_primary',
            array('fk'),
            array('id'),
            array(),
            'fk_constraint'
        );

        $this->_sm->dropAndCreateTable($primaryTable);
        $this->_sm->dropAndCreateTable($foreignTable);

        $foreignTable2 = clone $foreignTable;
        $foreignTable2->renameIndex('rename_index_fk_idx', 'renamed_index_fk_idx');

        $comparator = new Comparator();

        $this->_sm->alterTable($comparator->diffTable($foreignTable, $foreignTable2));

        $foreignTable = $this->_sm->listTableDetails('test_rename_index_foreign');

712 713 714
        self::assertFalse($foreignTable->hasIndex('rename_index_fk_idx'));
        self::assertTrue($foreignTable->hasIndex('renamed_index_fk_idx'));
        self::assertTrue($foreignTable->hasForeignKey('fk_constraint'));
715 716
    }

717 718 719 720 721
    /**
     * @group DBAL-42
     */
    public function testGetColumnComment()
    {
722 723
        if ( ! $this->_conn->getDatabasePlatform()->supportsInlineColumnComments() &&
             ! $this->_conn->getDatabasePlatform()->supportsCommentOnStatement() &&
Steve Müller's avatar
Steve Müller committed
724
            $this->_conn->getDatabasePlatform()->getName() != 'mssql') {
725 726
            $this->markTestSkipped('Database does not support column comments.');
        }
727

728
        $table = new Table('column_comment_test');
729 730 731 732 733
        $table->addColumn('id', 'integer', array('comment' => 'This is a comment'));
        $table->setPrimaryKey(array('id'));

        $this->_sm->createTable($table);

734
        $columns = $this->_sm->listTableColumns("column_comment_test");
735 736
        self::assertEquals(1, count($columns));
        self::assertEquals('This is a comment', $columns['id']->getComment());
737 738

        $tableDiff = new \Doctrine\DBAL\Schema\TableDiff('column_comment_test');
739
        $tableDiff->fromTable = $table;
740 741
        $tableDiff->changedColumns['id'] = new \Doctrine\DBAL\Schema\ColumnDiff(
            'id', new \Doctrine\DBAL\Schema\Column(
742
                'id', \Doctrine\DBAL\Types\Type::getType('integer')
743
            ),
744 745 746 747
            array('comment'),
            new \Doctrine\DBAL\Schema\Column(
                'id', \Doctrine\DBAL\Types\Type::getType('integer'), array('comment' => 'This is a comment')
            )
748 749 750 751 752
        );

        $this->_sm->alterTable($tableDiff);

        $columns = $this->_sm->listTableColumns("column_comment_test");
753 754
        self::assertEquals(1, count($columns));
        self::assertEmpty($columns['id']->getComment());
755 756
    }

757 758 759 760 761
    /**
     * @group DBAL-42
     */
    public function testAutomaticallyAppendCommentOnMarkedColumns()
    {
762 763
        if ( ! $this->_conn->getDatabasePlatform()->supportsInlineColumnComments() &&
             ! $this->_conn->getDatabasePlatform()->supportsCommentOnStatement() &&
Steve Müller's avatar
Steve Müller committed
764
            $this->_conn->getDatabasePlatform()->getName() != 'mssql') {
765 766 767
            $this->markTestSkipped('Database does not support column comments.');
        }

768
        $table = new Table('column_comment_test2');
769 770 771 772 773 774 775 776
        $table->addColumn('id', 'integer', array('comment' => 'This is a comment'));
        $table->addColumn('obj', 'object', array('comment' => 'This is a comment'));
        $table->addColumn('arr', 'array', array('comment' => 'This is a comment'));
        $table->setPrimaryKey(array('id'));

        $this->_sm->createTable($table);

        $columns = $this->_sm->listTableColumns("column_comment_test2");
777 778 779 780 781 782
        self::assertEquals(3, count($columns));
        self::assertEquals('This is a comment', $columns['id']->getComment());
        self::assertEquals('This is a comment', $columns['obj']->getComment(), "The Doctrine2 Typehint should be stripped from comment.");
        self::assertInstanceOf('Doctrine\DBAL\Types\ObjectType', $columns['obj']->getType(), "The Doctrine2 should be detected from comment hint.");
        self::assertEquals('This is a comment', $columns['arr']->getComment(), "The Doctrine2 Typehint should be stripped from comment.");
        self::assertInstanceOf('Doctrine\DBAL\Types\ArrayType', $columns['arr']->getType(), "The Doctrine2 should be detected from comment hint.");
783 784
    }

785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
    /**
     * @group DBAL-1228
     */
    public function testCommentHintOnDateIntervalTypeColumn()
    {
        if ( ! $this->_conn->getDatabasePlatform()->supportsInlineColumnComments() &&
            ! $this->_conn->getDatabasePlatform()->supportsCommentOnStatement() &&
            $this->_conn->getDatabasePlatform()->getName() != 'mssql') {
            $this->markTestSkipped('Database does not support column comments.');
        }

        $table = new Table('column_dateinterval_comment');
        $table->addColumn('id', 'integer', array('comment' => 'This is a comment'));
        $table->addColumn('date_interval', 'dateinterval', array('comment' => 'This is a comment'));
        $table->setPrimaryKey(array('id'));

        $this->_sm->createTable($table);

        $columns = $this->_sm->listTableColumns("column_dateinterval_comment");
804 805 806 807
        self::assertEquals(2, count($columns));
        self::assertEquals('This is a comment', $columns['id']->getComment());
        self::assertEquals('This is a comment', $columns['date_interval']->getComment(), "The Doctrine2 Typehint should be stripped from comment.");
        self::assertInstanceOf('Doctrine\DBAL\Types\DateIntervalType', $columns['date_interval']->getType(), "The Doctrine2 should be detected from comment hint.");
808 809
    }

810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
    /**
     * @group DBAL-825
     */
    public function testChangeColumnsTypeWithDefaultValue()
    {
        $tableName = 'column_def_change_type';
        $table     = new Table($tableName);

        $table->addColumn('col_int', 'smallint', array('default' => 666));
        $table->addColumn('col_string', 'string', array('default' => 'foo'));

        $this->_sm->dropAndCreateTable($table);

        $tableDiff = new TableDiff($tableName);
        $tableDiff->fromTable = $table;
        $tableDiff->changedColumns['col_int'] = new ColumnDiff(
            'col_int',
            new Column('col_int', Type::getType('integer'), array('default' => 666)),
            array('type'),
            new Column('col_int', Type::getType('smallint'), array('default' => 666))
        );

        $tableDiff->changedColumns['col_string'] = new ColumnDiff(
            'col_string',
            new Column('col_string', Type::getType('string'), array('default' => 'foo', 'fixed' => true)),
            array('fixed'),
            new Column('col_string', Type::getType('string'), array('default' => 'foo'))
        );

        $this->_sm->alterTable($tableDiff);

        $columns = $this->_sm->listTableColumns($tableName);

843 844
        self::assertInstanceOf('Doctrine\DBAL\Types\IntegerType', $columns['col_int']->getType());
        self::assertEquals(666, $columns['col_int']->getDefault());
845

846 847
        self::assertInstanceOf('Doctrine\DBAL\Types\StringType', $columns['col_string']->getType());
        self::assertEquals('foo', $columns['col_string']->getDefault());
848 849
    }

850 851 852 853 854
    /**
     * @group DBAL-197
     */
    public function testListTableWithBlob()
    {
855
        $table = new Table('test_blob_table');
Luís Cobucci's avatar
Luís Cobucci committed
856 857 858
        $table->addColumn('id', 'integer', ['comment' => 'This is a comment']);
        $table->addColumn('binarydata', 'blob', []);
        $table->setPrimaryKey(['id']);
859 860

        $this->_sm->createTable($table);
Luís Cobucci's avatar
Luís Cobucci committed
861 862 863 864 865 866

        $created = $this->_sm->listTableDetails('test_blob_table');

        self::assertTrue($created->hasColumn('id'));
        self::assertTrue($created->hasColumn('binarydata'));
        self::assertTrue($created->hasPrimaryKey());
867 868
    }

869 870 871
    /**
     * @param string $name
     * @param array $data
872
     * @return Table
873
     */
romanb's avatar
romanb committed
874
    protected function createTestTable($name = 'test_table', $data = array())
875
    {
876
        $options = $data['options'] ?? [];
877

878 879 880
        $table = $this->getTestTable($name, $options);

        $this->_sm->dropAndCreateTable($table);
881 882

        return $table;
883 884 885 886
    }

    protected function getTestTable($name, $options=array())
    {
887
        $table = new Table($name, array(), array(), array(), false, $options);
888
        $table->setSchemaConfig($this->_sm->createSchemaConfig());
889
        $table->addColumn('id', 'integer', array('notnull' => true));
890 891 892 893 894 895 896 897
        $table->setPrimaryKey(array('id'));
        $table->addColumn('test', 'string', array('length' => 255));
        $table->addColumn('foreign_key_test', 'integer');
        return $table;
    }

    protected function getTestCompositeTable($name)
    {
898
        $table = new Table($name, array(), array(), array(), false, array());
899 900
        $table->setSchemaConfig($this->_sm->createSchemaConfig());
        $table->addColumn('id', 'integer', array('notnull' => true));
901 902
        $table->addColumn('other_id', 'integer', array('notnull' => true));
        $table->setPrimaryKey(array('id', 'other_id'));
903
        $table->addColumn('test', 'string', array('length' => 255));
904
        return $table;
905
    }
906 907 908 909

    protected function assertHasTable($tables, $tableName)
    {
        $foundTable = false;
jeroendedauw's avatar
jeroendedauw committed
910
        foreach ($tables as $table) {
911
            self::assertInstanceOf('Doctrine\DBAL\Schema\Table', $table, 'No Table instance was found in tables array.');
912 913 914 915
            if (strtolower($table->getName()) == 'list_tables_test_new_name') {
                $foundTable = true;
            }
        }
916
        self::assertTrue($foundTable, "Could not find new table");
917
    }
918 919 920 921 922 923 924 925 926 927 928

    public function testListForeignKeysComposite()
    {
        if(!$this->_conn->getDatabasePlatform()->supportsForeignKeyConstraints()) {
            $this->markTestSkipped('Does not support foreign key constraints.');
        }

        $this->_sm->createTable($this->getTestTable('test_create_fk3'));
        $this->_sm->createTable($this->getTestCompositeTable('test_create_fk4'));

        $foreignKey = new \Doctrine\DBAL\Schema\ForeignKeyConstraint(
929
            array('id', 'foreign_key_test'), 'test_create_fk4', array('id', 'other_id'), 'foreign_key_test_fk2'
930 931 932 933 934 935
        );

        $this->_sm->createForeignKey($foreignKey, 'test_create_fk3');

        $fkeys = $this->_sm->listTableForeignKeys('test_create_fk3');

936
        self::assertEquals(1, count($fkeys), "Table 'test_create_fk3' has to have one foreign key.");
937

938 939 940
        self::assertInstanceOf('Doctrine\DBAL\Schema\ForeignKeyConstraint', $fkeys[0]);
        self::assertEquals(array('id', 'foreign_key_test'), array_map('strtolower', $fkeys[0]->getLocalColumns()));
        self::assertEquals(array('id', 'other_id'),         array_map('strtolower', $fkeys[0]->getForeignColumns()));
941
    }
942 943 944 945 946 947 948

    /**
     * @group DBAL-44
     */
    public function testColumnDefaultLifecycle()
    {
        $table = new Table("col_def_lifecycle");
949
        $table->addColumn('id', 'integer', array('autoincrement' => true));
950 951 952 953 954 955
        $table->addColumn('column1', 'string', array('default' => null));
        $table->addColumn('column2', 'string', array('default' => false));
        $table->addColumn('column3', 'string', array('default' => true));
        $table->addColumn('column4', 'string', array('default' => 0));
        $table->addColumn('column5', 'string', array('default' => ''));
        $table->addColumn('column6', 'string', array('default' => 'def'));
956
        $table->addColumn('column7', 'integer', array('default' => 0));
957 958 959 960 961 962
        $table->setPrimaryKey(array('id'));

        $this->_sm->dropAndCreateTable($table);

        $columns = $this->_sm->listTableColumns('col_def_lifecycle');

963 964 965 966 967 968 969 970
        self::assertNull($columns['id']->getDefault());
        self::assertNull($columns['column1']->getDefault());
        self::assertSame('', $columns['column2']->getDefault());
        self::assertSame('1', $columns['column3']->getDefault());
        self::assertSame('0', $columns['column4']->getDefault());
        self::assertSame('', $columns['column5']->getDefault());
        self::assertSame('def', $columns['column6']->getDefault());
        self::assertSame('0', $columns['column7']->getDefault());
971 972 973 974 975 976 977 978 979

        $diffTable = clone $table;

        $diffTable->changeColumn('column1', array('default' => false));
        $diffTable->changeColumn('column2', array('default' => null));
        $diffTable->changeColumn('column3', array('default' => false));
        $diffTable->changeColumn('column4', array('default' => null));
        $diffTable->changeColumn('column5', array('default' => false));
        $diffTable->changeColumn('column6', array('default' => 666));
980
        $diffTable->changeColumn('column7', array('default' => null));
981 982 983 984 985 986 987

        $comparator = new Comparator();

        $this->_sm->alterTable($comparator->diffTable($table, $diffTable));

        $columns = $this->_sm->listTableColumns('col_def_lifecycle');

988 989 990 991 992 993 994
        self::assertSame('', $columns['column1']->getDefault());
        self::assertNull($columns['column2']->getDefault());
        self::assertSame('', $columns['column3']->getDefault());
        self::assertNull($columns['column4']->getDefault());
        self::assertSame('', $columns['column5']->getDefault());
        self::assertSame('666', $columns['column6']->getDefault());
        self::assertNull($columns['column7']->getDefault());
995
    }
Steve Müller's avatar
Steve Müller committed
996 997 998 999 1000

    public function testListTableWithBinary()
    {
        $tableName = 'test_binary_table';

1001
        $table = new Table($tableName);
Steve Müller's avatar
Steve Müller committed
1002 1003 1004 1005 1006 1007 1008 1009 1010
        $table->addColumn('id', 'integer');
        $table->addColumn('column_varbinary', 'binary', array());
        $table->addColumn('column_binary', 'binary', array('fixed' => true));
        $table->setPrimaryKey(array('id'));

        $this->_sm->createTable($table);

        $table = $this->_sm->listTableDetails($tableName);

1011 1012
        self::assertInstanceOf('Doctrine\DBAL\Types\BinaryType', $table->getColumn('column_varbinary')->getType());
        self::assertFalse($table->getColumn('column_varbinary')->getFixed());
Steve Müller's avatar
Steve Müller committed
1013

1014 1015
        self::assertInstanceOf('Doctrine\DBAL\Types\BinaryType', $table->getColumn('column_binary')->getType());
        self::assertTrue($table->getColumn('column_binary')->getFixed());
Steve Müller's avatar
Steve Müller committed
1016
    }
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043

    public function testListTableDetailsWithFullQualifiedTableName()
    {
        if ( ! $this->_sm->getDatabasePlatform()->supportsSchemas()) {
            $this->markTestSkipped('Test only works on platforms that support schemas.');
        }

        $defaultSchemaName = $this->_sm->getDatabasePlatform()->getDefaultSchemaName();
        $primaryTableName  = 'primary_table';
        $foreignTableName  = 'foreign_table';

        $table = new Table($foreignTableName);
        $table->addColumn('id', 'integer', array('autoincrement' => true));
        $table->setPrimaryKey(array('id'));

        $this->_sm->dropAndCreateTable($table);

        $table = new Table($primaryTableName);
        $table->addColumn('id', 'integer', array('autoincrement' => true));
        $table->addColumn('foo', 'integer');
        $table->addColumn('bar', 'string');
        $table->addForeignKeyConstraint($foreignTableName, array('foo'), array('id'));
        $table->addIndex(array('bar'));
        $table->setPrimaryKey(array('id'));

        $this->_sm->dropAndCreateTable($table);

1044
        self::assertEquals(
1045 1046 1047
            $this->_sm->listTableColumns($primaryTableName),
            $this->_sm->listTableColumns($defaultSchemaName . '.' . $primaryTableName)
        );
1048
        self::assertEquals(
1049 1050 1051
            $this->_sm->listTableIndexes($primaryTableName),
            $this->_sm->listTableIndexes($defaultSchemaName . '.' . $primaryTableName)
        );
1052
        self::assertEquals(
1053 1054 1055 1056
            $this->_sm->listTableForeignKeys($primaryTableName),
            $this->_sm->listTableForeignKeys($defaultSchemaName . '.' . $primaryTableName)
        );
    }
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072

    public function testCommentStringsAreQuoted()
    {
        if ( ! $this->_conn->getDatabasePlatform()->supportsInlineColumnComments() &&
            ! $this->_conn->getDatabasePlatform()->supportsCommentOnStatement() &&
            $this->_conn->getDatabasePlatform()->getName() != 'mssql') {
            $this->markTestSkipped('Database does not support column comments.');
        }

        $table = new Table('my_table');
        $table->addColumn('id', 'integer', array('comment' => "It's a comment with a quote"));
        $table->setPrimaryKey(array('id'));

        $this->_sm->createTable($table);

        $columns = $this->_sm->listTableColumns("my_table");
1073
        self::assertEquals("It's a comment with a quote", $columns['id']->getComment());
1074
    }
1075

1076 1077 1078 1079 1080 1081 1082 1083 1084
    public function testCommentNotDuplicated()
    {
        if ( ! $this->_conn->getDatabasePlatform()->supportsInlineColumnComments()) {
            $this->markTestSkipped('Database does not support column comments.');
        }

        $options = array(
            'type' => Type::getType('integer'),
            'default' => 0,
1085
            'notnull' => true,
1086 1087 1088 1089 1090 1091 1092 1093
            'comment' => 'expected+column+comment',
        );
        $columnDefinition = substr($this->_conn->getDatabasePlatform()->getColumnDeclarationSQL('id', $options), strlen('id') + 1);

        $table = new Table('my_table');
        $table->addColumn('id', 'integer', array('columnDefinition' => $columnDefinition, 'comment' => 'unexpected_column_comment'));
        $sql = $this->_conn->getDatabasePlatform()->getCreateTableSQL($table);

1094 1095
        self::assertContains('expected+column+comment', $sql[0]);
        self::assertNotContains('unexpected_column_comment', $sql[0]);
1096 1097
    }

1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
    /**
     * @group DBAL-1009
     *
     * @dataProvider getAlterColumnComment
     */
    public function testAlterColumnComment($comment1, $expectedComment1, $comment2, $expectedComment2)
    {
        if ( ! $this->_conn->getDatabasePlatform()->supportsInlineColumnComments() &&
            ! $this->_conn->getDatabasePlatform()->supportsCommentOnStatement() &&
            $this->_conn->getDatabasePlatform()->getName() != 'mssql') {
            $this->markTestSkipped('Database does not support column comments.');
        }

        $offlineTable = new Table('alter_column_comment_test');
        $offlineTable->addColumn('comment1', 'integer', array('comment' => $comment1));
        $offlineTable->addColumn('comment2', 'integer', array('comment' => $comment2));
        $offlineTable->addColumn('no_comment1', 'integer');
        $offlineTable->addColumn('no_comment2', 'integer');
        $this->_sm->dropAndCreateTable($offlineTable);

        $onlineTable = $this->_sm->listTableDetails("alter_column_comment_test");

1120 1121 1122 1123
        self::assertSame($expectedComment1, $onlineTable->getColumn('comment1')->getComment());
        self::assertSame($expectedComment2, $onlineTable->getColumn('comment2')->getComment());
        self::assertNull($onlineTable->getColumn('no_comment1')->getComment());
        self::assertNull($onlineTable->getColumn('no_comment2')->getComment());
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133

        $onlineTable->changeColumn('comment1', array('comment' => $comment2));
        $onlineTable->changeColumn('comment2', array('comment' => $comment1));
        $onlineTable->changeColumn('no_comment1', array('comment' => $comment1));
        $onlineTable->changeColumn('no_comment2', array('comment' => $comment2));

        $comparator = new Comparator();

        $tableDiff = $comparator->diffTable($offlineTable, $onlineTable);

1134
        self::assertInstanceOf('Doctrine\DBAL\Schema\TableDiff', $tableDiff);
1135 1136 1137 1138 1139

        $this->_sm->alterTable($tableDiff);

        $onlineTable = $this->_sm->listTableDetails("alter_column_comment_test");

1140 1141 1142 1143
        self::assertSame($expectedComment2, $onlineTable->getColumn('comment1')->getComment());
        self::assertSame($expectedComment1, $onlineTable->getColumn('comment2')->getComment());
        self::assertSame($expectedComment1, $onlineTable->getColumn('no_comment1')->getComment());
        self::assertSame($expectedComment2, $onlineTable->getColumn('no_comment2')->getComment());
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
    }

    public function getAlterColumnComment()
    {
        return array(
            array(null, null, ' ', ' '),
            array(null, null, '0', '0'),
            array(null, null, 'foo', 'foo'),

            array('', null, ' ', ' '),
            array('', null, '0', '0'),
            array('', null, 'foo', 'foo'),

            array(' ', ' ', '0', '0'),
            array(' ', ' ', 'foo', 'foo'),

            array('0', '0', 'foo', 'foo'),
        );
    }
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172

    /**
     * @group DBAL-1095
     */
    public function testDoesNotListIndexesImplicitlyCreatedByForeignKeys()
    {
        if (! $this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) {
            $this->markTestSkipped('This test is only supported on platforms that have foreign keys.');
        }

1173
        $primaryTable = new Table('test_list_index_impl_primary');
1174 1175 1176
        $primaryTable->addColumn('id', 'integer');
        $primaryTable->setPrimaryKey(array('id'));

1177
        $foreignTable = new Table('test_list_index_impl_foreign');
1178 1179 1180
        $foreignTable->addColumn('fk1', 'integer');
        $foreignTable->addColumn('fk2', 'integer');
        $foreignTable->addIndex(array('fk1'), 'explicit_fk1_idx');
1181 1182
        $foreignTable->addForeignKeyConstraint('test_list_index_impl_primary', array('fk1'), array('id'));
        $foreignTable->addForeignKeyConstraint('test_list_index_impl_primary', array('fk2'), array('id'));
1183 1184 1185 1186

        $this->_sm->dropAndCreateTable($primaryTable);
        $this->_sm->dropAndCreateTable($foreignTable);

1187
        $indexes = $this->_sm->listTableIndexes('test_list_index_impl_foreign');
1188

1189 1190 1191
        self::assertCount(2, $indexes);
        self::assertArrayHasKey('explicit_fk1_idx', $indexes);
        self::assertArrayHasKey('idx_3d6c147fdc58d6c', $indexes);
1192
    }
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334

    /**
     * @after
     */
    public function removeJsonArrayTable() : void
    {
        if ($this->_sm->tablesExist(['json_array_test'])) {
            $this->_sm->dropTable('json_array_test');
        }
    }

    /**
     * @group 2782
     * @group 6654
     */
    public function testComparatorShouldReturnFalseWhenLegacyJsonArrayColumnHasComment() : void
    {
        $table = new Table('json_array_test');
        $table->addColumn('parameters', 'json_array');

        $this->_sm->createTable($table);

        $comparator = new Comparator();
        $tableDiff  = $comparator->diffTable($this->_sm->listTableDetails('json_array_test'), $table);

        self::assertFalse($tableDiff);
    }

    /**
     * @group 2782
     * @group 6654
     */
    public function testComparatorShouldModifyOnlyTheCommentWhenUpdatingFromJsonArrayTypeOnLegacyPlatforms() : void
    {
        if ($this->_sm->getDatabasePlatform()->hasNativeJsonType()) {
            $this->markTestSkipped('This test is only supported on platforms that do not have native JSON type.');
        }

        $table = new Table('json_array_test');
        $table->addColumn('parameters', 'json_array');

        $this->_sm->createTable($table);

        $table = new Table('json_array_test');
        $table->addColumn('parameters', 'json');

        $comparator = new Comparator();
        $tableDiff  = $comparator->diffTable($this->_sm->listTableDetails('json_array_test'), $table);

        self::assertInstanceOf(TableDiff::class, $tableDiff);

        $changedColumn = $tableDiff->changedColumns['parameters'] ?? $tableDiff->changedColumns['PARAMETERS'];

        self::assertSame(['comment'], $changedColumn->changedProperties);
    }

    /**
     * @group 2782
     * @group 6654
     */
    public function testComparatorShouldAddCommentToLegacyJsonArrayTypeThatDoesNotHaveIt() : void
    {
        if ( ! $this->_sm->getDatabasePlatform()->hasNativeJsonType()) {
            $this->markTestSkipped('This test is only supported on platforms that have native JSON type.');
        }

        $this->_conn->executeQuery('CREATE TABLE json_array_test (parameters JSON NOT NULL)');

        $table = new Table('json_array_test');
        $table->addColumn('parameters', 'json_array');

        $comparator = new Comparator();
        $tableDiff  = $comparator->diffTable($this->_sm->listTableDetails('json_array_test'), $table);

        self::assertInstanceOf(TableDiff::class, $tableDiff);
        self::assertSame(['comment'], $tableDiff->changedColumns['parameters']->changedProperties);
    }

    /**
     * @group 2782
     * @group 6654
     */
    public function testComparatorShouldReturnAllChangesWhenUsingLegacyJsonArrayType() : void
    {
        if ( ! $this->_sm->getDatabasePlatform()->hasNativeJsonType()) {
            $this->markTestSkipped('This test is only supported on platforms that have native JSON type.');
        }

        $this->_conn->executeQuery('CREATE TABLE json_array_test (parameters JSON DEFAULT NULL)');

        $table = new Table('json_array_test');
        $table->addColumn('parameters', 'json_array');

        $comparator = new Comparator();
        $tableDiff  = $comparator->diffTable($this->_sm->listTableDetails('json_array_test'), $table);

        self::assertInstanceOf(TableDiff::class, $tableDiff);
        self::assertSame(['notnull', 'comment'], $tableDiff->changedColumns['parameters']->changedProperties);
    }

    /**
     * @group 2782
     * @group 6654
     */
    public function testComparatorShouldReturnAllChangesWhenUsingLegacyJsonArrayTypeEvenWhenPlatformHasJsonSupport() : void
    {
        if ( ! $this->_sm->getDatabasePlatform()->hasNativeJsonType()) {
            $this->markTestSkipped('This test is only supported on platforms that have native JSON type.');
        }

        $this->_conn->executeQuery('CREATE TABLE json_array_test (parameters JSON DEFAULT NULL)');

        $table = new Table('json_array_test');
        $table->addColumn('parameters', 'json_array');

        $comparator = new Comparator();
        $tableDiff  = $comparator->diffTable($this->_sm->listTableDetails('json_array_test'), $table);

        self::assertInstanceOf(TableDiff::class, $tableDiff);
        self::assertSame(['notnull', 'comment'], $tableDiff->changedColumns['parameters']->changedProperties);
    }

    /**
     * @group 2782
     * @group 6654
     */
    public function testComparatorShouldNotAddCommentToJsonTypeSinceItIsTheDefaultNow() : void
    {
        if ( ! $this->_sm->getDatabasePlatform()->hasNativeJsonType()) {
            $this->markTestSkipped('This test is only supported on platforms that have native JSON type.');
        }

        $this->_conn->executeQuery('CREATE TABLE json_test (parameters JSON NOT NULL)');

        $table = new Table('json_test');
        $table->addColumn('parameters', 'json');

        $comparator = new Comparator();
        $tableDiff  = $comparator->diffTable($this->_sm->listTableDetails('json_test'), $table);

        self::assertFalse($tableDiff);
    }
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360

    /**
     * @dataProvider commentsProvider
     *
     * @group 2596
     */
    public function testExtractDoctrineTypeFromComment(string $comment, string $expected, string $currentType) : void
    {
        $result = $this->_sm->extractDoctrineTypeFromComment($comment, $currentType);

        self::assertSame($expected, $result);
    }

    public function commentsProvider() : array
    {
        $currentType = 'current type';

        return [
            'invalid custom type comments'      => ['should.return.current.type', $currentType, $currentType],
            'valid doctrine type'               => ['(DC2Type:guid)', 'guid', $currentType],
            'valid with dots'                   => ['(DC2Type:type.should.return)', 'type.should.return', $currentType],
            'valid with namespace'              => ['(DC2Type:Namespace\Class)', 'Namespace\Class', $currentType],
            'valid with extra closing bracket'  => ['(DC2Type:should.stop)).before)', 'should.stop', $currentType],
            'valid with extra opening brackets' => ['(DC2Type:should((.stop)).before)', 'should((.stop', $currentType],
        ];
    }
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396

    public function testCreateAndListSequences() : void
    {
        if ( ! $this->_sm->getDatabasePlatform()->supportsSequences()) {
            self::markTestSkipped('This test is only supported on platforms that support sequences.');
        }

        $sequence1Name           = 'sequence_1';
        $sequence1AllocationSize = 1;
        $sequence1InitialValue   = 2;
        $sequence2Name           = 'sequence_2';
        $sequence2AllocationSize = 3;
        $sequence2InitialValue   = 4;
        $sequence1               = new Sequence($sequence1Name, $sequence1AllocationSize, $sequence1InitialValue);
        $sequence2               = new Sequence($sequence2Name, $sequence2AllocationSize, $sequence2InitialValue);

        $this->_sm->createSequence($sequence1);
        $this->_sm->createSequence($sequence2);

        /** @var Sequence[] $actualSequences */
        $actualSequences = [];
        foreach ($this->_sm->listSequences() as $sequence) {
            $actualSequences[$sequence->getName()] = $sequence;
        }

        $actualSequence1 = $actualSequences[$sequence1Name];
        $actualSequence2 = $actualSequences[$sequence2Name];

        self::assertSame($sequence1Name, $actualSequence1->getName());
        self::assertEquals($sequence1AllocationSize, $actualSequence1->getAllocationSize());
        self::assertEquals($sequence1InitialValue, $actualSequence1->getInitialValue());

        self::assertSame($sequence2Name, $actualSequence2->getName());
        self::assertEquals($sequence2AllocationSize, $actualSequence2->getAllocationSize());
        self::assertEquals($sequence2InitialValue, $actualSequence2->getInitialValue());
    }
1397
}