Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Platform-aware schema comparison #4746

Merged
merged 3 commits into from
Aug 26, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions UPGRADE.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ awareness about deprecated code.

# Upgrade to 3.2

## Deprecated schema comparison APIs that don't account for the current database connection and the database platform

1. Instantiation of the `Comparator` class outside the DBAL is deprecated. Use `SchemaManager::createComparator()`
to create the comparator specific to the current database connection and the database platform.
2. The `Schema::getMigrateFromSql()` and `::getMigrateToSql()` methods are deprecated. Compare the schemas using the
connection-aware comparator and produce the SQL by passing the resulting diff to the target platform.

## Deprecated driver-level APIs that don't take the server version into account.

The `ServerInfoAwareConnection` and `VersionAwarePlatformDriver` interfaces are deprecated. In the next major version,
Expand Down
5 changes: 5 additions & 0 deletions phpcs.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,9 @@
<rule ref="Squiz.PHP.LowercasePHPFunctions">
<exclude-pattern>src/Driver/SQLSrv/Statement.php</exclude-pattern>
</rule>

<!-- See https://github.com/squizlabs/PHP_CodeSniffer/issues/3035 -->
<rule ref="Generic.CodeAnalysis.UselessOverridingMethod.Found">
<exclude-pattern>src/Platforms/*/Comparator.php</exclude-pattern>
</rule>
</ruleset>
6 changes: 6 additions & 0 deletions psalm.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,10 @@
<referencedMethod name="Doctrine\DBAL\Schema\ForeignKeyConstraint::getLocalTable"/>
<referencedMethod name="Doctrine\DBAL\Schema\ForeignKeyConstraint::getLocalTableName"/>
<referencedMethod name="Doctrine\DBAL\Schema\ForeignKeyConstraint::setLocalTable"/>
<!--
TODO: remove in 4.0.0
-->
<referencedMethod name="Doctrine\DBAL\Schema\Schema::getMigrateToSql"/>
</errorLevel>
</DeprecatedMethod>
<DeprecatedProperty>
Expand Down Expand Up @@ -331,6 +335,8 @@
<!-- See https://github.com/doctrine/dbal/pull/3562 -->
<file name="src/Schema/AbstractSchemaManager.php"/>
<file name="src/Schema/SqliteSchemaManager.php"/>
<!-- See https://github.com/doctrine/dbal/pull/3498 -->
<file name="tests/Platforms/AbstractMySQLPlatformTestCase.php"/>
</errorLevel>
</TooManyArguments>
<TypeDoesNotContainType>
Expand Down
4 changes: 4 additions & 0 deletions src/Driver/AbstractDB2Driver.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
use Doctrine\DBAL\Platforms\DB2Platform;
use Doctrine\DBAL\Schema\DB2SchemaManager;

use function assert;

/**
* Abstract base implementation of the {@link Driver} interface for IBM DB2 based drivers.
*/
Expand All @@ -28,6 +30,8 @@ public function getDatabasePlatform()
*/
public function getSchemaManager(Connection $conn, AbstractPlatform $platform)
{
assert($platform instanceof DB2Platform);

return new DB2SchemaManager($conn, $platform);
}

Expand Down
3 changes: 3 additions & 0 deletions src/Driver/AbstractMySQLDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Doctrine\DBAL\Schema\MySQLSchemaManager;
use Doctrine\DBAL\VersionAwarePlatformDriver;

use function assert;
use function preg_match;
use function stripos;
use function version_compare;
Expand Down Expand Up @@ -126,6 +127,8 @@ public function getDatabasePlatform()
*/
public function getSchemaManager(Connection $conn, AbstractPlatform $platform)
{
assert($platform instanceof MySQLPlatform);

return new MySQLSchemaManager($conn, $platform);
}

Expand Down
4 changes: 4 additions & 0 deletions src/Driver/AbstractOracleDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
use Doctrine\DBAL\Platforms\OraclePlatform;
use Doctrine\DBAL\Schema\OracleSchemaManager;

use function assert;

/**
* Abstract base implementation of the {@link Driver} interface for Oracle based drivers.
*/
Expand All @@ -29,6 +31,8 @@ public function getDatabasePlatform()
*/
public function getSchemaManager(Connection $conn, AbstractPlatform $platform)
{
assert($platform instanceof OraclePlatform);

return new OracleSchemaManager($conn, $platform);
}

Expand Down
3 changes: 3 additions & 0 deletions src/Driver/AbstractPostgreSQLDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Doctrine\DBAL\Schema\PostgreSQLSchemaManager;
use Doctrine\DBAL\VersionAwarePlatformDriver;

use function assert;
use function preg_match;
use function version_compare;

Expand Down Expand Up @@ -57,6 +58,8 @@ public function getDatabasePlatform()
*/
public function getSchemaManager(Connection $conn, AbstractPlatform $platform)
{
assert($platform instanceof PostgreSQL94Platform);

return new PostgreSQLSchemaManager($conn, $platform);
}

Expand Down
4 changes: 4 additions & 0 deletions src/Driver/AbstractSQLServerDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
use Doctrine\DBAL\Platforms\SQLServer2012Platform;
use Doctrine\DBAL\Schema\SQLServerSchemaManager;

use function assert;

/**
* Abstract base implementation of the {@link Driver} interface for Microsoft SQL Server based drivers.
*/
Expand All @@ -28,6 +30,8 @@ public function getDatabasePlatform()
*/
public function getSchemaManager(Connection $conn, AbstractPlatform $platform)
{
assert($platform instanceof SQLServer2012Platform);

return new SQLServerSchemaManager($conn, $platform);
}

Expand Down
4 changes: 4 additions & 0 deletions src/Driver/AbstractSQLiteDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
use Doctrine\DBAL\Platforms\SqlitePlatform;
use Doctrine\DBAL\Schema\SqliteSchemaManager;

use function assert;

/**
* Abstract base implementation of the {@link Doctrine\DBAL\Driver} interface for SQLite based drivers.
*/
Expand All @@ -28,6 +30,8 @@ public function getDatabasePlatform()
*/
public function getSchemaManager(Connection $conn, AbstractPlatform $platform)
{
assert($platform instanceof SqlitePlatform);

return new SqliteSchemaManager($conn, $platform);
}

Expand Down
61 changes: 49 additions & 12 deletions src/Platforms/AbstractPlatform.php
Original file line number Diff line number Diff line change
Expand Up @@ -1795,23 +1795,13 @@ public function getCreateTableSQL(Table $table, $createFlags = self::CREATE_INDE
}
}

$name = $column->getQuotedName($this);

$columnData = array_merge($column->toArray(), [
'name' => $name,
'version' => $column->hasPlatformOption('version') ? $column->getPlatformOption('version') : false,
'comment' => $this->getColumnComment($column),
]);

if ($columnData['type'] instanceof Types\StringType && $columnData['length'] === null) {
$columnData['length'] = 255;
}
$columnData = $this->columnToArray($column);

if (in_array($column->getName(), $options['primary'], true)) {
$columnData['primary'] = true;
}

$columns[$name] = $columnData;
$columns[$columnData['name']] = $columnData;
}

if ($this->_eventManager !== null && $this->_eventManager->hasListeners(Events::onSchemaCreateTable)) {
Expand Down Expand Up @@ -3901,6 +3891,27 @@ final public function escapeStringForLike(string $inputString, string $escapeCha
);
}

/**
* @return array<string,mixed> An associative array with the name of the properties
* of the column being declared as array indexes.
*/
private function columnToArray(Column $column): array
{
$name = $column->getQuotedName($this);

$columnData = array_merge($column->toArray(), [
'name' => $name,
'version' => $column->hasPlatformOption('version') ? $column->getPlatformOption('version') : false,
'comment' => $this->getColumnComment($column),
]);

if ($columnData['type'] instanceof Types\StringType && $columnData['length'] === null) {
$columnData['length'] = 255;
}

return $columnData;
}

/**
* @internal
*/
Expand All @@ -3913,4 +3924,30 @@ protected function getLikeWildcardCharacters(): string
{
return '%_';
}

/**
* Compares the definitions of the given columns in the context of this platform.
*
* @throws Exception
*/
public function columnsEqual(Column $column1, Column $column2): bool
{
if (
$this->getColumnDeclarationSQL('', $this->columnToArray($column1))
!== $this->getColumnDeclarationSQL('', $this->columnToArray($column2))
) {
return false;
}

// If the platform supports inline comments, all comparison is already done above
if ($this->supportsInlineColumnComments()) {
return true;
}

if ($column1->getComment() !== $column2->getComment()) {
return false;
}

return $column1->getType() === $column2->getType();
}
}
66 changes: 66 additions & 0 deletions src/Platforms/MySQL/Comparator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

namespace Doctrine\DBAL\Platforms\MySQL;

use Doctrine\DBAL\Platforms\MySQLPlatform;
use Doctrine\DBAL\Schema\Comparator as BaseComparator;
use Doctrine\DBAL\Schema\Table;

use function array_diff_assoc;
use function array_intersect_key;

/**
* Compares schemas in the context of MySQL platform.
*
* In MySQL, unless specified explicitly, the column's character set and collation are inherited from its containing
* table. So during comparison, an omitted value and the value that matches the default value of table in the
* desired schema must be considered equal.
*/
class Comparator extends BaseComparator
{
/**
* @internal The comparator can be only instantiated by a schema manager.
*/
public function __construct(MySQLPlatform $platform)
{
parent::__construct($platform);
}

/**
* {@inheritDoc}
*/
public function diffTable(Table $fromTable, Table $toTable)
{
$defaults = array_intersect_key($fromTable->getOptions(), [
'charset' => null,
'collation' => null,
]);

if ($defaults !== []) {
$fromTable = clone $fromTable;
$toTable = clone $toTable;

$this->normalizeColumns($fromTable, $defaults);
$this->normalizeColumns($toTable, $defaults);
}

return parent::diffTable($fromTable, $toTable);
}

/**
* @param array<string,mixed> $defaults
*/
private function normalizeColumns(Table $table, array $defaults): void
{
foreach ($table->getColumns() as $column) {
$options = $column->getPlatformOptions();
$diff = array_diff_assoc($options, $defaults);

if ($diff === $options) {
continue;
}

$column->setPlatformOptions($diff);
}
}
}
11 changes: 9 additions & 2 deletions src/Platforms/MySQLPlatform.php
Original file line number Diff line number Diff line change
Expand Up @@ -370,8 +370,15 @@ public function getListTableMetadataSQL(string $table, ?string $database = null)
{
return sprintf(
<<<'SQL'
SELECT ENGINE, AUTO_INCREMENT, TABLE_COLLATION, TABLE_COMMENT, CREATE_OPTIONS
FROM information_schema.TABLES
SELECT t.ENGINE,
t.AUTO_INCREMENT,
t.TABLE_COMMENT,
t.CREATE_OPTIONS,
t.TABLE_COLLATION,
ccsa.CHARACTER_SET_NAME
FROM information_schema.TABLES t
INNER JOIN information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` ccsa
ON ccsa.COLLATION_NAME = t.TABLE_COLLATION
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = %s AND TABLE_NAME = %s
SQL
,
Expand Down
56 changes: 56 additions & 0 deletions src/Platforms/SQLServer/Comparator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

namespace Doctrine\DBAL\Platforms\SQLServer;

use Doctrine\DBAL\Platforms\SQLServer2012Platform;
use Doctrine\DBAL\Schema\Comparator as BaseComparator;
use Doctrine\DBAL\Schema\Table;

/**
* Compares schemas in the context of SQL Server platform.
*
* @link https://docs.microsoft.com/en-us/sql/t-sql/statements/collations?view=sql-server-ver15
*/
class Comparator extends BaseComparator
{
/** @var string */
private $databaseCollation;

/**
* @internal The comparator can be only instantiated by a schema manager.
*/
public function __construct(SQLServer2012Platform $platform, string $databaseCollation)
{
parent::__construct($platform);

$this->databaseCollation = $databaseCollation;
}

/**
* {@inheritDoc}
*/
public function diffTable(Table $fromTable, Table $toTable)
{
$fromTable = clone $fromTable;
$toTable = clone $toTable;

$this->normalizeColumns($fromTable);
$this->normalizeColumns($toTable);

return parent::diffTable($fromTable, $toTable);
}

private function normalizeColumns(Table $table): void
{
foreach ($table->getColumns() as $column) {
$options = $column->getPlatformOptions();

if (! isset($options['collation']) || $options['collation'] !== $this->databaseCollation) {
continue;
}

unset($options['collation']);
$column->setPlatformOptions($options);
}
}
}
10 changes: 10 additions & 0 deletions src/Platforms/SQLServer2012Platform.php
Original file line number Diff line number Diff line change
Expand Up @@ -1625,6 +1625,16 @@ public function getColumnDeclarationSQL($name, array $column)
return $name . ' ' . $columnDef;
}

public function columnsEqual(Column $column1, Column $column2): bool
{
if (! parent::columnsEqual($column1, $column2)) {
return false;
}

return $this->getDefaultValueDeclarationSQL($column1->toArray())
=== $this->getDefaultValueDeclarationSQL($column2->toArray());
}

protected function getLikeWildcardCharacters(): string
{
return parent::getLikeWildcardCharacters() . '[]^';
Expand Down
Loading