Skip to content
Open
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
24 changes: 24 additions & 0 deletions docs/en/reference/generating-migrations.rst
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,30 @@ The SQL generated here is the exact same SQL that would be executed if you were
This just allows you to capture that SQL and maybe tweak it or add to it and trigger the deployment later across
multiple database servers.

MySQL ALTER TABLE algorithms
----------------------------

The ``diff`` command leaves algorithm selection to MySQL by default. To add an algorithm to generated MySQL
``ALTER TABLE`` statements, use the ``--mysql-algorithm`` option:

.. code-block:: sh

$ ./vendor/bin/doctrine-migrations diff --mysql-algorithm=INSTANT

The selected algorithm is added to each generated ``ALTER TABLE`` statement in both the ``up()`` and ``down()``
methods. For example:

.. code-block:: php

$this->addSql('ALTER TABLE users ADD COLUMN email VARCHAR(255) DEFAULT NULL, ALGORITHM=INSTANT');

Use ``INSTANT`` for metadata-only changes when the operation supports it. ``INPLACE`` can rebuild a table.
MySQL fails the statement if it cannot use the selected algorithm. Support depends on the MySQL version, operation,
and table definition, so check both generated directions against your supported MySQL versions. See the
`MySQL online DDL operation matrix`_ for operation-specific restrictions.

.. _MySQL online DDL operation matrix: https://dev.mysql.com/doc/refman/8.4/en/innodb-online-ddl-operations.html

Diffing Without the ORM
-----------------------

Expand Down
58 changes: 57 additions & 1 deletion src/Generator/DiffGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Doctrine\DBAL\Configuration as DBALConfiguration;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\MySQLPlatform;
use Doctrine\DBAL\Schema\AbstractAsset;
use Doctrine\DBAL\Schema\AbstractSchemaManager;
use Doctrine\DBAL\Schema\ComparatorConfig;
Expand All @@ -14,10 +15,17 @@
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\Generator\Exception\NoChangesDetected;
use Doctrine\Migrations\Provider\SchemaProvider;
use InvalidArgumentException;

use function array_map;
use function class_exists;
use function in_array;
use function method_exists;
use function preg_match;
use function rtrim;
use function str_ends_with;
use function strtoupper;
use function substr;

/**
* The DiffGenerator class is responsible for comparing two Doctrine\DBAL\Schema\Schema instances and generating a
Expand All @@ -39,7 +47,7 @@ public function __construct(
) {
}

/** @throws NoChangesDetected */
/** @throws NoChangesDetected|InvalidArgumentException */
public function generate(
string $fqcn,
string|null $filterExpression,
Expand All @@ -48,7 +56,20 @@ public function generate(
int $lineLength = 120,
bool $checkDbPlatform = true,
bool $fromEmptySchema = false,
string|null $mysqlAlgorithm = null,
): string {
if ($mysqlAlgorithm !== null) {
$mysqlAlgorithm = strtoupper($mysqlAlgorithm);

if (! in_array($mysqlAlgorithm, ['INSTANT', 'INPLACE'], true)) {
throw new InvalidArgumentException('The MySQL ALTER TABLE algorithm must be INSTANT or INPLACE.');
}

if (! $this->platform instanceof MySQLPlatform) {
throw new InvalidArgumentException('The MySQL ALTER TABLE algorithm can only be used with MySQL.');
}
}

if ($filterExpression !== null) {
$this->dbalConfiguration->setSchemaAssetsFilter(
static function ($assetName) use ($filterExpression) {
Expand Down Expand Up @@ -95,6 +116,9 @@ static function ($assetName) use ($filterExpression) {
}

$upSql = $this->platform->getAlterSchemaSQL($comparator->compareSchemas($fromSchema, $toSchema));
if ($mysqlAlgorithm !== null) {
$upSql = $this->addMySQLAlgorithm($upSql, $mysqlAlgorithm);
}

$up = $this->migrationSqlGenerator->generate(
$upSql,
Expand All @@ -105,6 +129,9 @@ static function ($assetName) use ($filterExpression) {
);

$downSql = $this->platform->getAlterSchemaSQL($comparator->compareSchemas($toSchema, $fromSchema));
if ($mysqlAlgorithm !== null) {
$downSql = $this->addMySQLAlgorithm($downSql, $mysqlAlgorithm);
}

$down = $this->migrationSqlGenerator->generate(
$downSql,
Expand Down Expand Up @@ -166,4 +193,33 @@ private function createToSchema(): Schema

return $toSchema;
}

/**
* @param string[] $sql
*
* @return string[]
*/
private function addMySQLAlgorithm(array $sql, string $algorithm): array
{
return array_map(static function (string $query) use ($algorithm): string {
if (preg_match('/^\s*ALTER\s+TABLE\b/i', $query) !== 1) {
return $query;
}

if (preg_match('/\bALGORITHM\s*=/i', $query) === 1) {
throw new InvalidArgumentException(
'The generated ALTER TABLE statement already specifies an algorithm.',
);
}

$query = rtrim($query);
$terminator = '';
if (str_ends_with($query, ';')) {
$query = substr($query, 0, -1);
$terminator = ';';
}

return $query . ', ALGORITHM=' . $algorithm . $terminator;
}, $sql);
}
}
51 changes: 42 additions & 9 deletions src/Tools/Console/Command/DiffCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Doctrine\Migrations\Tools\Console\Command;

use Doctrine\DBAL\Platforms\MySQLPlatform;
use Doctrine\Migrations\Generator\Exception\NoChangesDetected;
use Doctrine\Migrations\Metadata\AvailableMigrationsList;
use Doctrine\Migrations\Metadata\ExecutedMigrationsList;
Expand All @@ -18,7 +19,9 @@
use function class_exists;
use function count;
use function filter_var;
use function in_array;
use function sprintf;
use function strtoupper;

use const FILTER_VALIDATE_BOOLEAN;

Expand Down Expand Up @@ -94,6 +97,12 @@ protected function configure(): void
null,
InputOption::VALUE_NONE,
'Generate a full migration as if the current database was empty.',
)
->addOption(
'mysql-algorithm',
null,
InputOption::VALUE_REQUIRED,
'Add INSTANT or INPLACE to generated MySQL ALTER TABLE statements.',
);
}

Expand All @@ -114,6 +123,17 @@ protected function execute(
$allowEmptyDiff = $input->getOption('allow-empty-diff');
$checkDbPlatform = filter_var($input->getOption('check-database-platform'), FILTER_VALIDATE_BOOLEAN);
$fromEmptySchema = $input->getOption('from-empty-schema');
$mysqlAlgorithm = $input->getOption('mysql-algorithm');
if ($mysqlAlgorithm !== null) {
$mysqlAlgorithm = strtoupper((string) $mysqlAlgorithm);
if (! in_array($mysqlAlgorithm, ['INSTANT', 'INPLACE'], true)) {
throw InvalidOptionUsage::new('The "--mysql-algorithm" option must be INSTANT or INPLACE.');
}

if (! $this->getDependencyFactory()->getConnection()->getDatabasePlatform() instanceof MySQLPlatform) {
throw InvalidOptionUsage::new('The "--mysql-algorithm" option can only be used with MySQL.');
}
}

if ($formatted) {
if (! class_exists(SqlFormatter::class)) {
Expand All @@ -139,15 +159,28 @@ protected function execute(
$diffGenerator = $this->getDependencyFactory()->getDiffGenerator();

try {
$path = $diffGenerator->generate(
$fqcn,
$filterExpression,
$formatted,
$nowdocOutput,
$lineLength,
$checkDbPlatform,
$fromEmptySchema,
);
if ($mysqlAlgorithm === null) {
$path = $diffGenerator->generate(
$fqcn,
$filterExpression,
$formatted,
$nowdocOutput,
$lineLength,
$checkDbPlatform,
$fromEmptySchema,
);
} else {
$path = $diffGenerator->generate(
$fqcn,
$filterExpression,
$formatted,
$nowdocOutput,
$lineLength,
$checkDbPlatform,
$fromEmptySchema,
$mysqlAlgorithm,
);
}
} catch (NoChangesDetected $exception) {
if ($allowEmptyDiff) {
$this->io->error($exception->getMessage());
Expand Down
73 changes: 71 additions & 2 deletions tests/Generator/DiffGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

use Doctrine\DBAL\Configuration as DBALConfiguration;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\MySQLPlatform;
use Doctrine\DBAL\Platforms\SQLitePlatform;
use Doctrine\DBAL\Schema\AbstractSchemaManager;
use Doctrine\DBAL\Schema\Comparator;
use Doctrine\DBAL\Schema\NamedObject;
Expand All @@ -16,6 +18,7 @@
use Doctrine\Migrations\Generator\Generator;
use Doctrine\Migrations\Generator\SqlGenerator;
use Doctrine\Migrations\Provider\SchemaProvider;
use InvalidArgumentException;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\MockObject\Stub;
Expand Down Expand Up @@ -125,6 +128,67 @@ public function testGenerate(): void
));
}

public function testGenerateAddsMySQLAlgorithmToAlterStatementsInBothDirections(): void
{
$this->platform = self::createStub(MySQLPlatform::class);
$this->migrationDiffGenerator = $this->createDiffGenerator($this->platform);

$this->schemaManager->method('introspectSchema')->willReturn(new Schema());
$this->schemaProvider->method('createSchema')->willReturn(new Schema());

$schemaDiff = self::createStub(SchemaDiff::class);
$comparator = $this->mockComparator($schemaDiff);
$this->schemaManager->method('createComparator')->willReturn($comparator);

$this->platform->method('getAlterSchemaSQL')->willReturnOnConsecutiveCalls(
['ALTER TABLE users ADD name VARCHAR(255)', 'UPDATE users SET active = 1'],
['ALTER TABLE users DROP name;'],
);

$this->migrationSqlGenerator->expects(self::exactly(2))
->method('generate')
->willReturnCallback(static function (array $sql): string {
static $call = 0;
self::assertSame(
$call++ === 0
? ['ALTER TABLE users ADD name VARCHAR(255), ALGORITHM=INSTANT', 'UPDATE users SET active = 1']
: ['ALTER TABLE users DROP name, ALGORITHM=INSTANT;'],
$sql,
);

return 'generated SQL';
});

$this->migrationGenerator->expects(self::once())
->method('generateMigration')
->with('Version1234', 'generated SQL', 'generated SQL')
->willReturn('path');

self::assertSame(
'path',
$this->migrationDiffGenerator->generate('Version1234', null, mysqlAlgorithm: 'instant'),
);
}

public function testGenerateRejectsUnsupportedMySQLAlgorithm(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('The MySQL ALTER TABLE algorithm must be INSTANT or INPLACE.');

$this->migrationDiffGenerator->generate('Version1234', null, mysqlAlgorithm: 'COPY');
}

public function testGenerateRejectsMySQLAlgorithmOnOtherPlatforms(): void
{
$this->platform = self::createStub(SQLitePlatform::class);
$this->migrationDiffGenerator = $this->createDiffGenerator($this->platform);

$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('The MySQL ALTER TABLE algorithm can only be used with MySQL.');

$this->migrationDiffGenerator->generate('Version1234', null, mysqlAlgorithm: 'INSTANT');
}

public function testGenerateFromEmptySchema(): void
{
$emptySchema = $this->createMock(Schema::class);
Expand Down Expand Up @@ -245,11 +309,16 @@ protected function setUp(): void
$this->migrationGenerator = $this->createMock(Generator::class);
$this->migrationSqlGenerator = $this->createMock(SqlGenerator::class);
$this->emptySchemaProvider = $this->createMock(SchemaProvider::class);
$this->migrationDiffGenerator = new DiffGenerator(
$this->migrationDiffGenerator = $this->createDiffGenerator($this->platform);
}

private function createDiffGenerator(AbstractPlatform $platform): DiffGenerator
{
return new DiffGenerator(
$this->dbalConfiguration,
$this->schemaManager,
$this->schemaProvider,
$this->platform,
$platform,
$this->migrationGenerator,
$this->migrationSqlGenerator,
$this->emptySchemaProvider,
Expand Down
31 changes: 31 additions & 0 deletions tests/Tools/Console/Command/DiffCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

namespace Doctrine\Migrations\Tests\Tools\Console\Command;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Platforms\MySQLPlatform;
use Doctrine\Migrations\AbstractMigration;
use Doctrine\Migrations\Configuration\Configuration;
use Doctrine\Migrations\DependencyFactory;
Expand Down Expand Up @@ -92,6 +94,35 @@ public function testExecute(): void
], array_map(trim(...), explode("\n", trim($output))));
}

public function testExecutePassesMySQLAlgorithmToDiffGenerator(): void
{
$this->migrationStatusCalculator
->method('getNewMigrations')
->willReturn(new AvailableMigrationsList([]));

$this->migrationStatusCalculator
->method('getExecutedUnavailableMigrations')
->willReturn(new ExecutedMigrationsList([]));

$platform = self::createStub(MySQLPlatform::class);

$connection = $this->createMock(Connection::class);
$connection->method('getDatabasePlatform')->willReturn($platform);
$this->dependencyFactory->method('getConnection')->willReturn($connection);

$this->classNameGenerator->expects(self::once())
->method('generateClassName')
->with('FooNs')
->willReturn('FooNs\\Version1234');

$this->migrationDiffGenerator->expects(self::once())
->method('generate')
->with('FooNs\\Version1234', null, false, null, 120, false, false, 'INSTANT')
->willReturn('/path/to/migration.php');

$this->diffCommandTester->execute(['--mysql-algorithm' => 'instant']);
}

public function testAvailableMigrationsCancel(): void
{
$m1 = new AvailableMigration(new Version('A'), self::createStub(AbstractMigration::class));
Expand Down