如何在Symfony 3.4下使用SQLite功能测试启用外键检查

时间:2018-05-28 08:27:10

标签: symfony functional-testing

我已经设置了一对多的关系,并希望在删除父级时删除子级。

我忘记这样做了,当因为孩子存在而拒绝删除父母时,这在MySQL的制作中造成了一个错误。

我想编写一个功能测试,但SQLite默认禁用外键检查。

如何在控制器使用的连接上PRAGMA foreign_keys = ON?我在测试端(灯具)上运行了这个,但这不是相同的连接,因此仍然禁用外键检查,并且删除具有现有子节点的父节点不会失败(它应该)。

1 个答案:

答案 0 :(得分:0)

覆盖捆绑包的boot功能,并在那里执行请求:

public function boot() {
    parent::boot();

    $env = $this->container->getParameter('kernel.environment');
    if ($env !== "test") {
        return;
    }

    /** @var Connection $connection */
    $connection = $this->container->get('doctrine')->getConnection();

    // Get initial state -- should be disabled
    $statement = $connection->prepare("PRAGMA foreign_keys");
    $statement->execute();
    echo __FILE__ . "@" . __LINE__ . "\n";
    print_r($statement->fetchAll());

    // Actually enable the foreign key checks on this connection
    $connection->exec("PRAGMA foreign_keys = ON;");

    // See if it was enabled
    $statement = $connection->prepare("PRAGMA foreign_keys");
    $statement->execute();
    echo __FILE__ . "@" . __LINE__ . "\n";
    print_r($statement->fetchAll());
}

这会产生以下结果:

./src/AppBundle/DependencyInjection/Compiler/DoctrineCompilerPass.php@23
Array
(
    [0] => Array
        (
            [foreign_keys] => 0
        )

)
./src/AppBundle/DependencyInjection/Compiler/DoctrineCompilerPass.php@30
Array
(
    [0] => Array
        (
            [foreign_keys] => 1
        )

)

现在,根据您使用的灯具,您可能需要在擦除数据库架构时禁用外键检查:

public function setUp() {
    $manager = $this->getContainer()
        ->get('doctrine')
        ->getManager();
    if (!isset($metadata)) {
        $metadata = $manager->getMetadataFactory()
            ->getAllMetadata();
    }
    $schemaTool = new SchemaTool($manager);
    // Disable the foreign key checks before the database is wiped
    $manager->getConnection()->exec("PRAGMA foreign_keys = OFF");
    $schemaTool->dropDatabase();
    if (!empty($metadata)) {
        $schemaTool->createSchema($metadata);
    }
    // Re-enable the foreign key checks now that it is created
    $manager->getConnection()->exec("PRAGMA foreign_keys = ON");
    $this->postFixtureSetup();

    $this->referenceRepository = $this->loadFixtures(array(ZZZ::class))->getReferenceRepository();
    $this->loadFixtures(array(ZZZ::class));
    $this->client = $this->makeClient();
}