Max*_*Max 5 php mysql insert doctrine-orm
我正在使用Doctrine它并且它INSERT第一次执行时无法数据persist/flush但是第二次工作,并且第3次失败:
// there is no code executed between any of the attempts
$entity = new My\Entity();
$entity->setTag('A'); // just a random field
$em->persist($entity);
$em->flush();
// INSERT not performed
// if I exit here and check the database, no entry is added
$entity = new My\Entity();
$entity->setTag('B');
$em->persist($entity);
$em->flush();
// INSERT performed
// if I exit here and check the database, 1 entry has been added
// and I can see it's "B"
$entity = new My\Entity();
$entity->setTag('C');
$em->persist($entity);
$em->flush();
// INSERT not performed
// if I exit here and check the database, there is still only 1 entry added
// and I can see it's "B"
Run Code Online (Sandbox Code Playgroud)
以下是我在尝试失败时注意到的事项:
- 没有任何内容PHP logs(error_reporting设置为全部,其他Doctrine和PHP问题,包括警告,确实显示在日志中).
- Doctrine SQLLogger没有显示任何东西(在第二次尝试时它确实显示INSERT).
一些故障排除步骤:
- 我想通过用DQL INSERT查询替换失败的尝试进行进一步的故障排除但是"DQL中不允许INSERT语句" :(
- 在失败的尝试中flush实例化之前做一些额外的$entity帮助 - 我可以插入尽可能多的条目,因为我想手动数据库,它工作,即使是第一次尝试.
- 我有同样的问题2.4.0-DEV.
- 我有同样的问题2.2.2.
我可能会补充说,代码是在PHPunit测试中执行的,而在之前的测试中,我没有遇到问题(即Doctrine INSERT在第一次执行时正确执行persist/flush).
知道问题可能来自哪里?
版本信息:
- PHP 5.4
- Doctrine 2.3.0(pdo_mysql司机)
- MySQL 5.5.24
- Ubuntu 12.04
-PHPUnit 3.7.7
好的,这是答案的一部分.问题似乎是我在我PHPUnit setUp()用来截断每个测试之间的数据库表的例程:
INSERT失败). INSERTs失败的方式似乎是模式随机的,而不是最初的想法,因为我创建了2个测试,每个3个插入(并且只运行那些).当在每个测试之间截断表时,每个测试中的3个插入会发生什么:
-test 1:SUCCESS/SUCCESS/SUCCESS
-test 2:SUCCESS/SUCCESS/FAILURE(我没有像我这样的失败/成功/失败曾经).
这是我用来截断表格的一段代码:
$cmd = $em->getClassMetadata($className);
$connection = $em->getConnection();
$dbPlatform = $connection->getDatabasePlatform();
$connection->beginTransaction();
try {
$connection->query('SET FOREIGN_KEY_CHECKS=0');
$q = $dbPlatform->getTruncateTableSql($cmd->getTableName());
$connection->executeUpdate($q);
$connection->query('SET FOREIGN_KEY_CHECKS=1');
$connection->commit();
}
catch (\Exception $e) {
$connection->rollback();
}
Run Code Online (Sandbox Code Playgroud)
我从这篇SO帖子中得到了代码,据我所知它看起来不错.如果我使用其他代码,我会遇到同样的问题:
$connection = $entityManager->getConnection();
$platform = $connection->getDatabasePlatform();
$connection->executeUpdate($platform->getTruncateTableSQL('my_table', true /* whether to cascade */));
Run Code Online (Sandbox Code Playgroud)
我修改了我的模式以使用和不使用外键进行测试,我在两种情况下都有相同的问题.
最后,问题似乎发生在以下情况:
- 截断函数中每个测试之间的表setUp。
AND
-仅实例化一次 Doctrine 实例setUpBeforeClass(我随后使用 访问self::$em)。
OR如果我在中实例化 Doctrine 实例时不截断每个测试之间的表setUp,则一切正常。
以前很喜欢setUpBeforeClass,现在不喜欢了……