我正在尝试将doctrine/migrations集成到TP5框架中以进行单元测试,因此我需要使用doctrine-migrations提供的API而不是CLI来运行迁移。但是,我在使用 SQLite 引擎时遇到了这个错误:元数据存储未初始化,请运行sync-metadata-storage 命令来修复此问题。
这是我的代码
$connectionLoader = new ConfigurationFile('./migrations-db.php');
$configurationLoader = new ConfigurationFileWithFallback('./migrations.php');
$dependencyFactory = DependencyFactory::fromConnection($configurationLoader, $connectionLoader);
$version = $dependencyFactory->getVersionAliasResolver()->resolveVersionAlias('latest');
$planCalculator = $dependencyFactory->getMigrationPlanCalculator();
$plan = $planCalculator->getPlanUntilVersion($version);
$migrator = $dependencyFactory->getMigrator();
$migratorConfigurationFactory = $dependencyFactory->getConsoleInputMigratorConfigurationFactory();
$migratorConfiguration = $migratorConfigurationFactory->getMigratorConfiguration(new ArrayInput([]));
$sql = $migrator->migrate($plan, $migratorConfiguration);
这是我的migrations-db.php
<?php
// return [
// 'driver' => 'pdo_mysql',
// 'host' => '127.0.0.1',
// 'port' => 13306,
// 'password' => 'zhihui',
// 'dbname' => 'migration',
// 'user' => 'root',
// ];
return [
'driver' => 'pdo_sqlite',
'dbname' => ':memory:',
];
如您所见,当驱动程序为“mysql_pdo”时,一切正常。
但是,奇怪的是,无论我选择哪个驱动程序,在 CLI 中运行doctrine-migrations:migrate 都可以正常工作。”
我已经解决了这个问题,并且我找到了一种在 Doctrine\Migrations\Tools\Console\Command\SyncMetadataCommand::execute 方法中调用“sync-metadata-storage”的方法。
所以我只需要添加这一行 $dependencyFactory->getMetadataStorage()->ensureInitialized();