为什么 PHP8 将包含 DDL 语句的事务改为异常抛出?

发布于 2022-09-12 13:35:45 字数 801 浏览 29 评论 0

在 PHP 8.0 以前的版本,包含 DDL 语句的事务只是会触发隐式提交(应该算是 MySQL 的功能,并不是 PHP 的特性),事务无法回滚,并不会抛异常。而8.0版本 commit 时会直接抛异常 There is no active transaction。 8.0 是基于什么考虑抛这个异常出来呢?似乎在 ChangeLog 也没有提到有这个变更。

测试代码如下

$conn = new PDO("mysql:host=127.0.0.1;dbname=test", 'root', '123456');
 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 $conn->beginTransaction();
 try {
 $sql = "CREATE TABLE IF NOT EXISTS test (`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, `text` varchar(32) NOT NULL DEFAULT '', PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
 $conn->exec($sql);
 
 $sql = "INSERT INTO test values(1,'test1')";
 $conn->exec($sql);
 
 $conn->commit();
 } catch (Exception $e) {
 echo $e->getMessage();
 $conn->rollBack();
 }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月野兔 2022-09-19 13:35:45

我近期也在测试php8,也发现了这个变化。

这是由于这个PDO变更导致的
https://github.com/php/php-sr...

Fix inconsistency in PDO transaction state

This addresses an issue introduced by #4996 and reported in
https://bugs.php.net/bug.php?id=80260.

Now that PDO::inTransaction() reports the real transaction state
of the connection, there may be a mismatch with PDOs internal
transaction state (in_tcx). This is compounded by the fact that
MySQL performs implicit commits for DDL queries.

This patch fixes the issue by making beginTransaction/commit/rollBack
work on the real transaction state provided by the driver as well
(or falling back to in_tcx if the driver does not support it).

This does mean that writing something like

$pdo->beginTransaction();
$pdo->exec('CREATE DATABASE ...');
$pdo->rollBack(); // <- illegal

will now result in an error, because the CREATE DATABASE already
committed the transaction. I believe this behavior is both correct
and desired -- otherwise, there is no indication that the code did
not behave correctly and the rollBack() was effectively ignored.
However, this is also a BC break.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文