第五节 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. }
14. // Make sure the transaction rolls back in the event of a panic.
15. defer func() {
16. if t.db != nil {
17. t.rollback()
18. }
19. }()
21. // Mark as a managed tx so that the inner function cannot manually commit.
22. t.managed = true
24. // If an error is returned from the function then rollback and return error.
25. err = fn(t)
26. t.managed = false
27. if err != nil {
28. _ = t.Rollback()
29. return err
30. }
32. return t.Commit()
33. }
