第四节 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. }

11. // Make sure the transaction rolls back in the event of a panic.
12. defer func() {
13. if t.db != nil {
14. t.rollback()
15. }
16. }()

18. // Mark as a managed tx so that the inner function cannot manually rollback.
19. t.managed = true

21. // If an error is returned from the function then pass it through.
22. err = fn(t)
23. t.managed = false
24. if err != nil {
25. _ = t.Rollback()
26. return err
27. }

29. if err := t.Rollback(); err != nil {
30. return err
31. }

33. return nil
34. }