12
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Doctrine で2つのDBのスキーマの差分を出力

Posted at

Doctrine には migrations:diff という XML や YAML で書かれたスキーマ情報と実際のDBのスキーマを比較して migration ファイルを作成する機能があるそうです。

そんなことができるなら、実際のDBを2つ比較してスキーマの差分を出力することも簡単にできるんじゃない?
と思って doctrine/migrations の中を覗いてみたら凄く簡単にできました。


まずは doctrine/dbal を composer でインストールします。

doctrine/migrations が必要なのかと思っていましたが、差分を導出する機能も dbal にありました。

$ composer require "doctrine/dbal:2.*"

次のように php のコードを作成します。接続情報の部分は適当に読み替えてください。

db-diff.php
<?php
require __DIR__ . '/vendor/autoload.php';

use Doctrine\DBAL\DriverManager;

$fromDb = DriverManager::getConnection([
    'driver' => 'pdo_mysql',
    'host' => '127.0.0.1',
    'user' => 'ore',
    'password' => 'pass',
    'dbname' => 'db1',
]);

$toDb = DriverManager::getConnection([
    'driver' => 'pdo_mysql',
    'host' => '127.0.0.1',
    'user' => 'ore',
    'password' => 'pass',
    'dbname' => 'db2',
]);

$fromSchema = $fromDb->getSchemaManager()->createSchema();
$toSchema = $toDb->getSchemaManager()->createSchema();
$sqls = $fromSchema->getMigrateToSql($toSchema, $toDb->getDatabasePlatform());

foreach ($sqls as $sql)
{
    echo "$sql;\n";
}

実行すると2つのDBのスキーマの差分が表示されます。

$ php db-diff.php

これなら Doctrine の XML とか YAML とか無関係なので、Doctrine を採用していないプロジェクトでもマイグレーションを作成するために使えるかもしれません。

12
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?