首页 > 解决方案 > Phinx 迁移 sqlite 内存 phpunit

问题描述

使用 sqlite 内存的 Phinx 迁移似乎在 0.9.2 中不起作用,我有一个非常简单的应用程序,只有一个表(产品)。运行迁移后,产品表不存在:

use Symfony\Component\Yaml\Yaml;
use Phinx\Config\Config;
use Phinx\Migration\Manager;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\NullOutput;

$pdo = new PDO('sqlite::memory:', null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);

$settings = Yaml::parseFile('../phinx.yml');
$settings['environments']['testing'] = [
    'adapter'       => 'sqlite',
    'connection'    => $pdo
];
$config = new Config($settings);

$manager = new Manager($config, new StringInput(' '), new NullOutput());
$manager->migrate('testing');
$manager->seed('testing');

$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);

// This line creates an exception of table doesn't exist
$pdo->query("SELECT * FROM product");

最后一行查询产生以下异常的产品表:

PDOException: SQLSTATE[HY000]: 一般错误: 1 no such table: product in /home/vagrant/code/ecommerce/public/index.php on line 43

为了完整起见,这里是与开发 mysql 环境完美配合的产品迁移:

use Phinx\Migration\AbstractMigration;

class Product extends AbstractMigration
{
    public function change()
    {
        $table = $this->table('product');
        $table->addColumn('name', 'string', ['limit' => 100, 'null' => false])
            ->addColumn('price', 'integer')
            ->create();
    }
}

标签: phpmysqlphpunitdatabase-migrationphinx

解决方案


当您从命令行正常使用 phinx 时,Phinx\Config 的属性 configFilePath 被正确设置为 phinx.yml 的完整路径

然而,在phinx文档(http://docs.phinx.org/en/latest/commands.html#using-phinx-with-phpunit)的示例中,用于为phpunit测试创建sqlite内存数据库,它使用php数组,因为必须手动输入 pdo 实例。

因为没有设置 phinx.yml 的路径,Phinx\Config 的 replaceTokens 方法通过调用这个来创建 PHINX_CONFIG_DIR:

$tokens['%%PHINX_CONFIG_DIR%%'] = dirname($this->getConfigFilePath());

Phinx 使用 %%PHINX_CONFIG_DIR%% 来计算其迁移和种子文件夹的位置,当不使用 phinx.yml 时,这不再有效。

解决方案是在手动创建 Config 类时提供路径:

$config = new Config($settings, './');

推荐阅读