【问题标题】:Phinx migrations sqlite memory phpunitPhinx 迁移 sqlite 内存 phpunit
【发布时间】:2018-11-14 04:01:38
【问题描述】:

使用 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();
    }
}

【问题讨论】:

  • 我对代码进行了挖掘,发现 Config 构造函数有一个 $configFilePath 参数。如果没有传递,则无法正确构建迁移和种子的路径。一旦我输入了一个路径,我就能够以编程方式创建 sqlite 内存数据库。

标签: php mysql phpunit database-migration phinx


【解决方案1】:

当您从命令行正常使用 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, './');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    • 2022-10-25
    • 2014-10-10
    • 2016-09-13
    • 1970-01-01
    相关资源
    最近更新 更多