doubu4406 2018-12-04 03:58
浏览 414

当Golang程序在执行数据库事务时终止时,它可以回滚吗?

Assuming a MariaDB compatible database (AWS Aurora RDS) with default settings, which includes autocommit enabled, if a Lambda function was terminated after three seconds doing a transaction that takes more than five seconds, e.g.

  tx, err := h.db.Begin()
  if err != nil {
      log.WithError(err).Error("failed to start transaction")
  }
  res, execErr := tx.Exec(fmt.Sprintf("UPDATE testtable SET val = %d WHERE id = 1; SELECT SLEEP(5.5);", time.Now().Unix()))
  if execErr != nil {
      log.WithError(err).Error("rolling back")
      err = tx.Rollback()
      if err != nil {
          log.WithError(err).Error("failed to roll back")
      }
  }
  if err := tx.Commit(); err != nil {
      log.WithError(err).Error("failed to commit")
  }

What would one assume the result to be? The transaction would have not been committed?

I am using Go MySQL Driver v1.3.0-84-g6be42e0 btw. I also made a video showing my results, but I am wondering if it is right since I don't understand how the driver could have executed rollback.

  • 写回答

2条回答 默认 最新

  • dongzhi4498 2018-12-04 06:21
    关注

    The transaction SQL does not commit. What I believe happens with a <= 5s timeout:

    1. BEGINs transaction
    2. Executes the SQL synchronously
    3. MySQLd detects the client disconnected via a TCP FIN
    4. MySQLd automatically rolls back since it doesn't see the Commit

    A tweet reply from one of the Golang MySQL driver maintainers:

    mysqld receives TCP FIN packet when Go client is terminated.
    Even though Go client exits uncleanly, OS (Linux kernel, etc) sends TCP FIN or TCP RST. So mysqld can know client is gone.— INADA Naoki (@methane) December 4, 2018
    评论

报告相同问题?

悬赏问题

  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题