NewPrimaryKeyWithNewAutoIncrementColumnTest.php 2.49 KB
Newer Older
1 2
<?php

3
namespace Doctrine\DBAL\Tests\Functional\Platform;
4

5
use Doctrine\DBAL\Platforms\AbstractPlatform;
6
use Doctrine\DBAL\Platforms\MySqlPlatform;
7
use Doctrine\DBAL\Schema\Comparator;
8
use Doctrine\DBAL\Tests\FunctionalTestCase;
9
use function count;
10

11
final class NewPrimaryKeyWithNewAutoIncrementColumnTest extends FunctionalTestCase
12 13 14 15
{
    /**
     * {@inheritDoc}
     */
16
    protected function setUp() : void
17 18 19
    {
        parent::setUp();

20
        if ($this->getPlatform() instanceof MySqlPlatform) {
21 22 23
            return;
        }

24
        self::markTestSkipped('Restricted to MySQL.');
25 26 27 28 29 30 31 32 33 34
    }

    /**
     * Ensures that the primary key is created within the same "alter table" statement that an auto-increment column
     * is added to the table as part of the new primary key.
     *
     * Before the fix for this problem this resulted in a database error: (at least on mysql)
     * SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table definition; there can be only one auto
     * column and it must be defined as a key
     */
35
    public function testAlterPrimaryKeyToAutoIncrementColumn() : void
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
    {
        $schemaManager = $this->connection->getSchemaManager();
        $schema        = $schemaManager->createSchema();

        $table = $schema->createTable('dbal2807');
        $table->addColumn('initial_id', 'integer');
        $table->setPrimaryKey(['initial_id']);

        $schemaManager->dropAndCreateTable($table);

        $newSchema = clone $schema;
        $newTable  = $newSchema->getTable($table->getName());
        $newTable->addColumn('new_id', 'integer', ['autoincrement' => true]);
        $newTable->dropPrimaryKey();
        $newTable->setPrimaryKey(['new_id']);

        $diff = (new Comparator())->compare($schema, $newSchema);

        foreach ($diff->toSql($this->getPlatform()) as $sql) {
            $this->connection->exec($sql);
        }

        $validationSchema = $schemaManager->createSchema();
        $validationTable  = $validationSchema->getTable($table->getName());

61 62 63
        self::assertTrue($validationTable->hasColumn('new_id'));
        self::assertTrue($validationTable->getColumn('new_id')->getAutoincrement());
        self::assertTrue($validationTable->hasPrimaryKey());
64 65
        self::assertEquals(1, count($validationTable->getPrimaryKeyColumns()));
        self::assertArrayHasKey('new_id', $validationTable->getPrimaryKeyColumns());
66 67
    }

68
    private function getPlatform() : AbstractPlatform
69 70 71 72
    {
        return $this->connection->getDatabasePlatform();
    }
}