Pragmatism in the real world

Registering Doctrine Type Mappings for standalone migrations

Shortly after starting to use Doctrine Migrations as a standalone tool in my project, I came across this error message:

Unknown database type bit requested, Doctrine\DBAL\Platforms\MySqlPlatform may not support it.

This means that I have a column in my database of type bit which is used for booleans in SQL Server, but confuses the MySQL platform as it’s not a default mapping.

To support this, you need to modify the database connection’s Platform object to know about the new mapping. However, with the setup that I’m using, I didn’t have access to the connection object that’s automatically created in the Migrations AbstractCommand object.

After poking around in the code for a bit, I discovered that the solution is to create the connection object myself and then attach it as a new helper to the Console\Application object.

This is how to do to it within the migrations.php file.

Firstly, create the database connection object using the information in migrations-db.php. This code is lifted from AbstractCommand:

if (file_exists('migrations-db.php')) {
    $params = include 'migrations-db.php';
    if (!is_array($params)) {
        throw new \InvalidArgumentException('The connection file has to return an array.');
    }
    $connection = \Doctrine\DBAL\DriverManager::getConnection($params);
} else {
    throw new \InvalidArgumentException('Missing "migrations-db.php" file. Alternatively use --db-configuration.');
}

We can now set up the database type mapping for bit:

$platform = $connection->getDatabasePlatform();
$platform->registerDoctrineTypeMapping('bit', 'boolean');

Now, all we need to do is add the connection to the Console\Application‘s HelperSet so that the AbstractCommand can use it. We are already adding the DialogHelper, so we add a ConnectionHelper

use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper;

$helperSet = new Console\Helper\HelperSet();
$helperSet->set(new Console\Helper\DialogHelper(), 'dialog');
$helperSet->set(new ConnectionHelper($connection), 'connection');
$cli->setHelperSet($helperSet);

That’s it. Our migrations system know nows that a database column of type bit is a boolean on MySQL as well as on SQL Server.