douzuizhuo0587 2017-07-01 07:36 采纳率: 0%
浏览 424
已采纳

在事务中途提交工作,然后继续执行的一种简单方法是

Background

I am using the github.com/jmoiron/sqlx golang package with a Postgres database.

I have the following wrapper function to run SQL code in a transaction:

func (s *postgresStore) runInTransaction(ctx context.Context, fn func(*sqlx.Tx) error) error {
    tx, err := s.db.Beginx()
    if err != nil {
        return err
    }
    defer func() {
        if err != nil {
            tx.Rollback()
            return
        }
        err = tx.Commit()
    }()
    err = fn(tx)
    return err
}

Given this, consider the following code:

func (s *store) SampleFunc(ctx context.Context) error {
    err := s.runInTransaction(ctx,func(tx *sqlx.Tx) error {

        // Point A: Do some database work

        if err := tx.Commit(); err != nil {
            return err
        }

        // Point B: Do some more database work, which may return an error
    })
}

Desired behavior

  • If there is an error at Point A, then the transaction should have done zero work
  • If there is an error at Point B, then the transaction should still have completed the work at Point A.

Problem with current code

The code does not work as intended at the moment, because I am committing the transaction twice (once in runInTransaction, once in SampleFunc).

A Possible Solution

Where I commit the transaction, I could instead run something like tx.Exec("SAVEPOINT my_savepoint"), then defer tx.Exec("ROLLBACK TO SAVEPOINT my_savepoint")

After the code at Point B, I could run: tx.Exec("RELEASE SAVEPOINT my_savepoint")

So, if the code at Point B runs without error, I will fail to ROLLBACK to my savepoint.

Problems with Possible Solution

I'm not sure if using savepoints will mess with the database/sql package's behavior. Also, my solution seems a bit messy -- surely there is a cleaner way to do this!

  • 写回答

2条回答 默认 最新

  • duanjiu2701 2017-07-02 06:52
    关注

    I had the problem alike: I had a lots of steps in one transaction. After starting transaction:

    • BEGIN
    • In loop:

      • SAVEPOINT s1
      • Some actions ....
      • If I get an error: ROLLBACK TO SAVEPOINT s1
      • If OK go to next step
    • Finally COMMIT

    This approach gives me ability to perform all steps one-by-one. If some steps got failed I can throw away only them, keeping others. And finally commit all "good" work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。