第五节 db.Update()实现分析

Update()主要用来执行读写事务。事务的开始、提交、回滚都交由tx内部控制

  1. // Update executes a function within the context of a read-write managed transaction.
  2. // If no error is returned from the function then the transaction is committed.
  3. // If an error is returned then the entire transaction is rolled back.
  4. // Any error that is returned from the function or returned from the commit is
  5. // returned from the Update() method.
  6. //
  7. // Attempting to manually commit or rollback within the function will cause a panic.
  8. func (db *DB) Update(fn func(*Tx) error) error {
  9. t, err := db.Begin(true)
  10. if err != nil {
  11. return err
  12. }
  13. // Make sure the transaction rolls back in the event of a panic.
  14. defer func() {
  15. if t.db != nil {
  16. t.rollback()
  17. }
  18. }()
  19. // Mark as a managed tx so that the inner function cannot manually commit.
  20. t.managed = true
  21. // If an error is returned from the function then rollback and return error.
  22. err = fn(t)
  23. t.managed = false
  24. if err != nil {
  25. _ = t.Rollback()
  26. return err
  27. }
  28. return t.Commit()
  29. }