第四节 db.View()实现分析

View()主要用来执行只读事务。事务的开启、提交、回滚都交由tx控制。

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