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

namespace Doctrine\Tests\DBAL\Functional\Schema;

5 6
use Doctrine\DBAL\Schema\Comparator;
use Doctrine\DBAL\Schema\Table;
7 8
use Doctrine\DBAL\Types\Type,
    Doctrine\DBAL\Schema\AbstractSchemaManager;
9
use Doctrine\DBAL\Platforms\AbstractPlatform;
10 11
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Events;
12

romanb's avatar
romanb committed
13 14 15
require_once __DIR__ . '/../../../TestInit.php';

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

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

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

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

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

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

Benjamin Eberlei's avatar
Benjamin Eberlei committed
44 45 46 47 48 49 50 51 52 53 54 55 56
    /**
     * @group DBAL-195
     */
    public function testDropAndCreateSequence()
    {
        if(!$this->_conn->getDatabasePlatform()->supportsSequences()) {
            $this->markTestSkipped($this->_conn->getDriver()->getName().' does not support sequences.');
        }

        $sequence = new \Doctrine\DBAL\Schema\Sequence('dropcreate_sequences_test_seq', 20, 10);
        $this->_sm->dropAndCreateSequence($sequence);
    }

57 58 59 60 61 62
    public function testListSequences()
    {
        if(!$this->_conn->getDatabasePlatform()->supportsSequences()) {
            $this->markTestSkipped($this->_conn->getDriver()->getName().' does not support sequences.');
        }

63 64
        $sequence = new \Doctrine\DBAL\Schema\Sequence('list_sequences_test_seq', 20, 10);
        $this->_sm->createSequence($sequence);
65

66
        $sequences = $this->_sm->listSequences();
67

68
        $this->assertInternalType('array', $sequences, 'listSequences() should return an array.');
69 70 71

        $foundSequence = null;
        foreach($sequences AS $sequence) {
72
            $this->assertInstanceOf('Doctrine\DBAL\Schema\Sequence', $sequence, 'Array elements of listSequences() should be Sequence instances.');
73 74 75 76 77 78 79 80 81 82
            if(strtolower($sequence->getName()) == 'list_sequences_test_seq') {
                $foundSequence = $sequence;
            }
        }

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

83 84
    public function testListDatabases()
    {
85 86 87 88
        if (!$this->_sm->getDatabasePlatform()->supportsCreateDropDatabase()) {
            $this->markTestSkipped('Cannot drop Database client side with this Driver.');
        }

89 90 91
        $this->_sm->dropAndCreateDatabase('test_create_database');
        $databases = $this->_sm->listDatabases();

92
        $databases = array_map('strtolower', $databases);
93

94
        $this->assertContains('test_create_database', $databases);
95 96 97 98 99 100 101
    }

    public function testListTables()
    {
        $this->createTestTable('list_tables_test');
        $tables = $this->_sm->listTables();

102
        $this->assertInternalType('array', $tables);
103
        $this->assertTrue(count($tables) > 0, "List Tables has to find at least one table named 'list_tables_test'.");
104 105 106

        $foundTable = false;
        foreach ($tables AS $table) {
107
            $this->assertInstanceOf('Doctrine\DBAL\Schema\Table', $table);
108
            if (strtolower($table->getName()) == 'list_tables_test') {
109 110 111 112 113 114 115
                $foundTable = true;

                $this->assertTrue($table->hasColumn('id'));
                $this->assertTrue($table->hasColumn('test'));
                $this->assertTrue($table->hasColumn('foreign_key_test'));
            }
        }
116 117

        $this->assertTrue( $foundTable , "The 'list_tables_test' table has to be found.");
118 119
    }

120
    public function createListTableColumns()
121
    {
122
        $table = new \Doctrine\DBAL\Schema\Table('list_table_columns');
123
        $table->addColumn('id', 'integer', array('notnull' => true));
124 125
        $table->addColumn('test', 'string', array('length' => 255, 'notnull' => false, 'default' => 'expected default'));
        $table->addColumn('foo', 'text', array('notnull' => true));
126 127 128 129
        $table->addColumn('bar', 'decimal', array('precision' => 10, 'scale' => 4, 'notnull' => false));
        $table->addColumn('baz1', 'datetime');
        $table->addColumn('baz2', 'time');
        $table->addColumn('baz3', 'date');
130
        $table->setPrimaryKey(array('id'));
131

132 133 134 135 136 137 138
        return $table;
    }

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

139
        $this->_sm->dropAndCreateTable($table);
140 141 142 143

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

        $this->assertArrayHasKey('id', $columns);
144
        $this->assertEquals('id',   strtolower($columns['id']->getname()));
145
        $this->assertInstanceOf('Doctrine\DBAL\Types\IntegerType', $columns['id']->gettype());
146 147 148
        $this->assertEquals(false,  $columns['id']->getunsigned());
        $this->assertEquals(true,   $columns['id']->getnotnull());
        $this->assertEquals(null,   $columns['id']->getdefault());
149
        $this->assertInternalType('array',  $columns['id']->getPlatformOptions());
150 151

        $this->assertArrayHasKey('test', $columns);
152
        $this->assertEquals('test', strtolower($columns['test']->getname()));
153
        $this->assertInstanceOf('Doctrine\DBAL\Types\StringType', $columns['test']->gettype());
154 155 156
        $this->assertEquals(255,    $columns['test']->getlength());
        $this->assertEquals(false,  $columns['test']->getfixed());
        $this->assertEquals(false,  $columns['test']->getnotnull());
157
        $this->assertEquals('expected default',   $columns['test']->getdefault());
158
        $this->assertInternalType('array',  $columns['test']->getPlatformOptions());
159

160
        $this->assertEquals('foo',  strtolower($columns['foo']->getname()));
161
        $this->assertInstanceOf('Doctrine\DBAL\Types\TextType', $columns['foo']->gettype());
162 163 164
        $this->assertEquals(false,  $columns['foo']->getunsigned());
        $this->assertEquals(false,  $columns['foo']->getfixed());
        $this->assertEquals(true,   $columns['foo']->getnotnull());
165
        $this->assertEquals(null,   $columns['foo']->getdefault());
166
        $this->assertInternalType('array',  $columns['foo']->getPlatformOptions());
167

168
        $this->assertEquals('bar',  strtolower($columns['bar']->getname()));
169
        $this->assertInstanceOf('Doctrine\DBAL\Types\DecimalType', $columns['bar']->gettype());
170
        $this->assertEquals(null,   $columns['bar']->getlength());
171 172
        $this->assertEquals(10,     $columns['bar']->getprecision());
        $this->assertEquals(4,      $columns['bar']->getscale());
173 174
        $this->assertEquals(false,  $columns['bar']->getunsigned());
        $this->assertEquals(false,  $columns['bar']->getfixed());
175
        $this->assertEquals(false,  $columns['bar']->getnotnull());
176
        $this->assertEquals(null,   $columns['bar']->getdefault());
177
        $this->assertInternalType('array',  $columns['bar']->getPlatformOptions());
178

179
        $this->assertEquals('baz1', strtolower($columns['baz1']->getname()));
180
        $this->assertInstanceOf('Doctrine\DBAL\Types\DateTimeType', $columns['baz1']->gettype());
181
        $this->assertEquals(true,   $columns['baz1']->getnotnull());
182
        $this->assertEquals(null,   $columns['baz1']->getdefault());
183
        $this->assertInternalType('array',  $columns['baz1']->getPlatformOptions());
184

185
        $this->assertEquals('baz2', strtolower($columns['baz2']->getname()));
186
        $this->assertContains($columns['baz2']->gettype()->getName(), array('time', 'date', 'datetime'));
187
        $this->assertEquals(true,   $columns['baz2']->getnotnull());
188
        $this->assertEquals(null,   $columns['baz2']->getdefault());
189
        $this->assertInternalType('array',  $columns['baz2']->getPlatformOptions());
190

191
        $this->assertEquals('baz3', strtolower($columns['baz3']->getname()));
192
        $this->assertContains($columns['baz2']->gettype()->getName(), array('time', 'date', 'datetime'));
193
        $this->assertEquals(true,   $columns['baz3']->getnotnull());
194
        $this->assertEquals(null,   $columns['baz3']->getdefault());
195
        $this->assertInternalType('array',  $columns['baz3']->getPlatformOptions());
196 197
    }

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
    public function testListTableColumnsDispatchEvent()
    {
        $table = $this->createListTableColumns();

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

        $listenerMock = $this->getMock('ListTableColumnsDispatchEventListener', array('onSchemaColumnDefinition'));
        $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);
    }

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
    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);

        $listenerMock = $this->getMock('ListTableIndexesDispatchEventListener', array('onSchemaIndexDefinition'));
        $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);
    }

246 247 248 249 250 251 252
    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();
253
        $this->_sm->dropAndCreateTable($offlineTable);
254 255 256 257 258 259 260 261
        $onlineTable = $this->_sm->listTableDetails('list_table_columns');

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

        $this->assertFalse($diff, "No differences should be detected with the offline vs online schema.");
    }

262 263
    public function testListTableIndexes()
    {
264
        $table = $this->getTestCompositeTable('list_table_indexes_test');
265 266
        $table->addUniqueIndex(array('test'), 'test_index_name');
        $table->addIndex(array('id', 'test'), 'test_composite_idx');
267

268
        $this->_sm->dropAndCreateTable($table);
269 270

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

272 273
        $this->assertEquals(3, count($tableIndexes));

274
        $this->assertArrayHasKey('primary', $tableIndexes, 'listTableIndexes() has to return a "primary" array key.');
275
        $this->assertEquals(array('id', 'other_id'), array_map('strtolower', $tableIndexes['primary']->getColumns()));
276 277
        $this->assertTrue($tableIndexes['primary']->isUnique());
        $this->assertTrue($tableIndexes['primary']->isPrimary());
278

279
        $this->assertEquals('test_index_name', strtolower($tableIndexes['test_index_name']->getName()));
280 281 282
        $this->assertEquals(array('test'), array_map('strtolower', $tableIndexes['test_index_name']->getColumns()));
        $this->assertTrue($tableIndexes['test_index_name']->isUnique());
        $this->assertFalse($tableIndexes['test_index_name']->isPrimary());
283

284
        $this->assertEquals('test_composite_idx', strtolower($tableIndexes['test_composite_idx']->getName()));
285 286 287
        $this->assertEquals(array('id', 'test'), array_map('strtolower', $tableIndexes['test_composite_idx']->getColumns()));
        $this->assertFalse($tableIndexes['test_composite_idx']->isUnique());
        $this->assertFalse($tableIndexes['test_composite_idx']->isPrimary());
288 289 290 291
    }

    public function testDropAndCreateIndex()
    {
292 293 294
        $table = $this->getTestTable('test_create_index');
        $table->addUniqueIndex(array('test'), 'test');
        $this->_sm->dropAndCreateTable($table);
295

296
        $this->_sm->dropAndCreateIndex($table->getIndex('test'), $table);
297
        $tableIndexes = $this->_sm->listTableIndexes('test_create_index');
298
        $this->assertInternalType('array', $tableIndexes);
299

300
        $this->assertEquals('test',        strtolower($tableIndexes['test']->getName()));
301 302 303 304 305
        $this->assertEquals(array('test'), array_map('strtolower', $tableIndexes['test']->getColumns()));
        $this->assertTrue($tableIndexes['test']->isUnique());
        $this->assertFalse($tableIndexes['test']->isPrimary());
    }

306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    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);

321 322
        $fkTable = $this->_sm->listTableDetails('test_create_fk');
        $fkConstraints = $fkTable->getForeignKeys();
323
        $this->assertEquals(1, count($fkConstraints), "Table 'test_create_fk1' has to have one foreign key.");
324 325

        $fkConstraint = current($fkConstraints);
326
        $this->assertInstanceOf('\Doctrine\DBAL\Schema\ForeignKeyConstraint', $fkConstraint);
327 328 329
        $this->assertEquals('test_foreign',             strtolower($fkConstraint->getForeignTableName()));
        $this->assertEquals(array('foreign_key_test'),  array_map('strtolower', $fkConstraint->getColumns()));
        $this->assertEquals(array('id'),                array_map('strtolower', $fkConstraint->getForeignColumns()));
330 331

        $this->assertTrue($fkTable->columnsAreIndexed($fkConstraint->getColumns()), "The columns of a foreign key constraint should always be indexed.");
332 333
    }

334 335 336 337 338 339 340 341 342
    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');

343
        $foreignKey = new \Doctrine\DBAL\Schema\ForeignKeyConstraint(
344
            array('foreign_key_test'), 'test_create_fk2', array('id'), 'foreign_key_test_fk', array('onDelete' => 'CASCADE')
345 346
        );

347
        $this->_sm->createForeignKey($foreignKey, 'test_create_fk1');
348 349 350

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

351
        $this->assertEquals(1, count($fkeys), "Table 'test_create_fk1' has to have one foreign key.");
352

353
        $this->assertInstanceOf('Doctrine\DBAL\Schema\ForeignKeyConstraint', $fkeys[0]);
354 355 356
        $this->assertEquals(array('foreign_key_test'),  array_map('strtolower', $fkeys[0]->getLocalColumns()));
        $this->assertEquals(array('id'),                array_map('strtolower', $fkeys[0]->getForeignColumns()));
        $this->assertEquals('test_create_fk2',          strtolower($fkeys[0]->getForeignTableName()));
357

358 359 360
        if($fkeys[0]->hasOption('onDelete')) {
            $this->assertEquals('CASCADE', $fkeys[0]->getOption('onDelete'));
        }
361 362
    }

363 364 365 366 367
    protected function getCreateExampleViewSql()
    {
        $this->markTestSkipped('No Create Example View SQL was defined for this SchemaManager');
    }

368 369 370 371 372 373 374 375
    public function testCreateSchema()
    {
        $this->createTestTable('test_table');

        $schema = $this->_sm->createSchema();
        $this->assertTrue($schema->hasTable('test_table'));
    }

376 377 378 379 380 381
    public function testAlterTableScenario()
    {
        if(!$this->_sm->getDatabasePlatform()->supportsAlterTable()) {
            $this->markTestSkipped('Alter Table is not supported by this platform.');
        }

382
        $alterTable = $this->createTestTable('alter_table');
383 384 385 386 387 388 389 390 391 392
        $this->createTestTable('alter_table_foreign');

        $table = $this->_sm->listTableDetails('alter_table');
        $this->assertTrue($table->hasColumn('id'));
        $this->assertTrue($table->hasColumn('test'));
        $this->assertTrue($table->hasColumn('foreign_key_test'));
        $this->assertEquals(0, count($table->getForeignKeys()));
        $this->assertEquals(1, count($table->getIndexes()));

        $tableDiff = new \Doctrine\DBAL\Schema\TableDiff("alter_table");
393
        $tableDiff->fromTable = $alterTable;
394 395 396 397 398 399 400 401 402 403
        $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');
        $this->assertFalse($table->hasColumn('test'));
        $this->assertTrue($table->hasColumn('foo'));

        $tableDiff = new \Doctrine\DBAL\Schema\TableDiff("alter_table");
404
        $tableDiff->fromTable = $table;
405 406 407 408 409 410 411 412 413 414 415 416
        $tableDiff->addedIndexes[] = new \Doctrine\DBAL\Schema\Index('foo_idx', array('foo'));

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

        $table = $this->_sm->listTableDetails('alter_table');
        $this->assertEquals(2, count($table->getIndexes()));
        $this->assertTrue($table->hasIndex('foo_idx'));
        $this->assertEquals(array('foo'), array_map('strtolower', $table->getIndex('foo_idx')->getColumns()));
        $this->assertFalse($table->getIndex('foo_idx')->isPrimary());
        $this->assertFalse($table->getIndex('foo_idx')->isUnique());

        $tableDiff = new \Doctrine\DBAL\Schema\TableDiff("alter_table");
417
        $tableDiff->fromTable = $table;
418 419 420 421 422 423 424 425 426 427
        $tableDiff->changedIndexes[] = new \Doctrine\DBAL\Schema\Index('foo_idx', array('foo', 'foreign_key_test'));

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

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

        $tableDiff = new \Doctrine\DBAL\Schema\TableDiff("alter_table");
428
        $tableDiff->fromTable = $table;
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
        $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');
        $this->assertEquals(2, count($table->getIndexes()));
        $this->assertTrue($table->hasIndex('bar_idx'));
        $this->assertFalse($table->hasIndex('foo_idx'));
        $this->assertEquals(array('foo', 'foreign_key_test'), array_map('strtolower', $table->getIndex('bar_idx')->getColumns()));
        $this->assertFalse($table->getIndex('bar_idx')->isPrimary());
        $this->assertFalse($table->getIndex('bar_idx')->isUnique());

        $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'));
444 445 446 447 448 449 450
        $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.
451
        $this->assertFalse($table->hasIndex('bar_idx'));
452

453 454 455 456 457 458 459 460
        if ($this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) {
            $fks = $table->getForeignKeys();
            $this->assertCount(1, $fks);
            $foreignKey = current($fks);
            $this->assertEquals('alter_table_foreign', strtolower($foreignKey->getForeignTableName()));
            $this->assertEquals(array('foreign_key_test'), array_map('strtolower', $foreignKey->getColumns()));
            $this->assertEquals(array('id'), array_map('strtolower', $foreignKey->getForeignColumns()));
        }
461 462
    }

463
    public function testCreateAndListViews()
464
    {
465 466 467 468
        if (!$this->_sm->getDatabasePlatform()->supportsViews()) {
            $this->markTestSkipped('Views is not supported by this platform.');
        }

469
        $this->createTestTable('view_test_table');
470

471 472
        $name = "doctrine_test_view";
        $sql = "SELECT * FROM view_test_table";
473

474
        $view = new \Doctrine\DBAL\Schema\View($name, $sql);
475

476 477 478
        $this->_sm->dropAndCreateView($view);

        $views = $this->_sm->listViews();
479 480
    }

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
    public function testAutoincrementDetection()
    {
        if (!$this->_sm->getDatabasePlatform()->supportsIdentityColumns()) {
            $this->markTestSkipped('This test is only supported on platforms that have autoincrement');
        }

        $table = new \Doctrine\DBAL\Schema\Table('test_autoincrement');
        $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');
        $this->assertTrue($inferredTable->hasColumn('id'));
        $this->assertTrue($inferredTable->getColumn('id')->getAutoincrement());
497
    }
498 499 500 501 502 503 504 505 506

    /**
     * @group DBAL-792
     */
    public function testAutoincrementDetectionMulticolumns()
    {
        if (!$this->_sm->getDatabasePlatform()->supportsIdentityColumns()) {
            $this->markTestSkipped('This test is only supported on platforms that have autoincrement');
        }
507 508 509 510 511 512 513 514 515 516 517 518

        $table = new \Doctrine\DBAL\Schema\Table('test_not_autoincrement');
        $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');
        $this->assertTrue($inferredTable->hasColumn('id'));
        $this->assertFalse($inferredTable->getColumn('id')->getAutoincrement());
519
    }
520

521 522 523 524 525 526 527 528
    /**
     * @group DDC-887
     */
    public function testUpdateSchemaWithForeignKeyRenaming()
    {
        if (!$this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) {
            $this->markTestSkipped('This test is only supported on platforms that have foreign keys.');
        }
529

530 531 532
        $table = new \Doctrine\DBAL\Schema\Table('test_fk_base');
        $table->addColumn('id', 'integer');
        $table->setPrimaryKey(array('id'));
533

534 535 536 537 538 539 540
        $tableFK = new \Doctrine\DBAL\Schema\Table('test_fk_rename');
        $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'));
541

542 543
        $this->_sm->createTable($table);
        $this->_sm->createTable($tableFK);
544

545 546 547 548 549 550 551
        $tableFKNew = new \Doctrine\DBAL\Schema\Table('test_fk_rename');
        $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'));
552

553 554
        $c = new \Doctrine\DBAL\Schema\Comparator();
        $tableDiff = $c->diffTable($tableFK, $tableFKNew);
555

556 557
        $this->_sm->alterTable($tableDiff);
    }
558

559 560 561 562 563
    /**
     * @group DBAL-42
     */
    public function testGetColumnComment()
    {
564 565
        if ( ! $this->_conn->getDatabasePlatform()->supportsInlineColumnComments() &&
             ! $this->_conn->getDatabasePlatform()->supportsCommentOnStatement() &&
Steve Müller's avatar
Steve Müller committed
566
            $this->_conn->getDatabasePlatform()->getName() != 'mssql') {
567 568
            $this->markTestSkipped('Database does not support column comments.');
        }
569

570
        $table = new \Doctrine\DBAL\Schema\Table('column_comment_test');
571 572 573 574 575
        $table->addColumn('id', 'integer', array('comment' => 'This is a comment'));
        $table->setPrimaryKey(array('id'));

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

576
        $columns = $this->_sm->listTableColumns("column_comment_test");
577 578
        $this->assertEquals(1, count($columns));
        $this->assertEquals('This is a comment', $columns['id']->getComment());
579 580 581 582 583 584

        $tableDiff = new \Doctrine\DBAL\Schema\TableDiff('column_comment_test');
        $tableDiff->changedColumns['id'] = new \Doctrine\DBAL\Schema\ColumnDiff(
            'id', new \Doctrine\DBAL\Schema\Column(
                'id', \Doctrine\DBAL\Types\Type::getType('integer'), array('primary' => true)
            ),
585 586 587 588
            array('comment'),
            new \Doctrine\DBAL\Schema\Column(
                'id', \Doctrine\DBAL\Types\Type::getType('integer'), array('comment' => 'This is a comment')
            )
589 590 591 592 593 594 595
        );

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

        $columns = $this->_sm->listTableColumns("column_comment_test");
        $this->assertEquals(1, count($columns));
        $this->assertEmpty($columns['id']->getComment());
596 597
    }

598 599 600 601 602
    /**
     * @group DBAL-42
     */
    public function testAutomaticallyAppendCommentOnMarkedColumns()
    {
603 604
        if ( ! $this->_conn->getDatabasePlatform()->supportsInlineColumnComments() &&
             ! $this->_conn->getDatabasePlatform()->supportsCommentOnStatement() &&
Steve Müller's avatar
Steve Müller committed
605
            $this->_conn->getDatabasePlatform()->getName() != 'mssql') {
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
            $this->markTestSkipped('Database does not support column comments.');
        }

        $table = new \Doctrine\DBAL\Schema\Table('column_comment_test2');
        $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");
        $this->assertEquals(3, count($columns));
        $this->assertEquals('This is a comment', $columns['id']->getComment());
        $this->assertEquals('This is a comment', $columns['obj']->getComment(), "The Doctrine2 Typehint should be stripped from comment.");
        $this->assertInstanceOf('Doctrine\DBAL\Types\ObjectType', $columns['obj']->getType(), "The Doctrine2 should be detected from comment hint.");
        $this->assertEquals('This is a comment', $columns['arr']->getComment(), "The Doctrine2 Typehint should be stripped from comment.");
        $this->assertInstanceOf('Doctrine\DBAL\Types\ArrayType', $columns['arr']->getType(), "The Doctrine2 should be detected from comment hint.");
    }

626 627 628 629 630 631 632 633 634 635 636 637 638 639
    /**
     * @group DBAL-197
     */
    public function testListTableWithBlob()
    {
        $table = new \Doctrine\DBAL\Schema\Table('test_blob_table');
        $table->addColumn('id', 'integer', array('comment' => 'This is a comment'));
        $table->addColumn('binarydata', 'blob', array());
        $table->setPrimaryKey(array('id'));

        $this->_sm->createTable($table);
        $blobTable = $this->_sm->listTableDetails('test_blob_table');
    }

640 641 642 643
    /**
     * @param string $name
     * @param array $data
     */
romanb's avatar
romanb committed
644
    protected function createTestTable($name = 'test_table', $data = array())
645 646 647 648 649 650
    {
        $options = array();
        if (isset($data['options'])) {
            $options = $data['options'];
        }

651 652 653
        $table = $this->getTestTable($name, $options);

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

        return $table;
656 657 658 659
    }

    protected function getTestTable($name, $options=array())
    {
660
        $table = new \Doctrine\DBAL\Schema\Table($name, array(), array(), array(), false, $options);
661
        $table->setSchemaConfig($this->_sm->createSchemaConfig());
662
        $table->addColumn('id', 'integer', array('notnull' => true));
663 664 665 666 667 668 669 670 671 672 673
        $table->setPrimaryKey(array('id'));
        $table->addColumn('test', 'string', array('length' => 255));
        $table->addColumn('foreign_key_test', 'integer');
        return $table;
    }

    protected function getTestCompositeTable($name)
    {
        $table = new \Doctrine\DBAL\Schema\Table($name, array(), array(), array(), false, array());
        $table->setSchemaConfig($this->_sm->createSchemaConfig());
        $table->addColumn('id', 'integer', array('notnull' => true));
674 675
        $table->addColumn('other_id', 'integer', array('notnull' => true));
        $table->setPrimaryKey(array('id', 'other_id'));
676
        $table->addColumn('test', 'string', array('length' => 255));
677
        return $table;
678
    }
679 680 681 682 683

    protected function assertHasTable($tables, $tableName)
    {
        $foundTable = false;
        foreach ($tables AS $table) {
684
            $this->assertInstanceOf('Doctrine\DBAL\Schema\Table', $table, 'No Table instance was found in tables array.');
685 686 687 688 689 690
            if (strtolower($table->getName()) == 'list_tables_test_new_name') {
                $foundTable = true;
            }
        }
        $this->assertTrue($foundTable, "Could not find new table");
    }
691 692 693 694 695 696 697 698 699 700 701

    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(
702
            array('id', 'foreign_key_test'), 'test_create_fk4', array('id', 'other_id'), 'foreign_key_test_fk2'
703 704 705 706 707 708 709 710 711 712 713 714
        );

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

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

        $this->assertEquals(1, count($fkeys), "Table 'test_create_fk3' has to have one foreign key.");

        $this->assertInstanceOf('Doctrine\DBAL\Schema\ForeignKeyConstraint', $fkeys[0]);
        $this->assertEquals(array('id', 'foreign_key_test'), array_map('strtolower', $fkeys[0]->getLocalColumns()));
        $this->assertEquals(array('id', 'other_id'),         array_map('strtolower', $fkeys[0]->getForeignColumns()));
    }
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764

    /**
     * @group DBAL-44
     */
    public function testColumnDefaultLifecycle()
    {
        $table = new Table("col_def_lifecycle");
        $table->addColumn('id', 'integer', array('primary' => true, 'autoincrement' => true));
        $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'));
        $table->setPrimaryKey(array('id'));

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

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

        $this->assertNull($columns['id']->getDefault());
        $this->assertNull($columns['column1']->getDefault());
        $this->assertSame('', $columns['column2']->getDefault());
        $this->assertSame('1', $columns['column3']->getDefault());
        $this->assertSame('0', $columns['column4']->getDefault());
        $this->assertSame('', $columns['column5']->getDefault());
        $this->assertSame('def', $columns['column6']->getDefault());

        $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));

        $comparator = new Comparator();

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

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

        $this->assertSame('', $columns['column1']->getDefault());
        $this->assertNull($columns['column2']->getDefault());
        $this->assertSame('', $columns['column3']->getDefault());
        $this->assertNull($columns['column4']->getDefault());
        $this->assertSame('', $columns['column5']->getDefault());
        $this->assertSame('666', $columns['column6']->getDefault());
    }
Steve Müller's avatar
Steve Müller committed
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785

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

        $table = new \Doctrine\DBAL\Schema\Table($tableName);
        $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);

        $this->assertInstanceOf('Doctrine\DBAL\Types\BinaryType', $table->getColumn('column_varbinary')->getType());
        $this->assertFalse($table->getColumn('column_varbinary')->getFixed());

        $this->assertInstanceOf('Doctrine\DBAL\Types\BinaryType', $table->getColumn('column_binary')->getType());
        $this->assertTrue($table->getColumn('column_binary')->getFixed());
    }
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825

    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);

        $this->assertEquals(
            $this->_sm->listTableColumns($primaryTableName),
            $this->_sm->listTableColumns($defaultSchemaName . '.' . $primaryTableName)
        );
        $this->assertEquals(
            $this->_sm->listTableIndexes($primaryTableName),
            $this->_sm->listTableIndexes($defaultSchemaName . '.' . $primaryTableName)
        );
        $this->assertEquals(
            $this->_sm->listTableForeignKeys($primaryTableName),
            $this->_sm->listTableForeignKeys($defaultSchemaName . '.' . $primaryTableName)
        );
    }
826
}