第二节 boltdb事务Tx定义

1. // txid represents the internal transaction identifier.
2. type txid uint64

4. // Tx represents a read-only or read/write transaction on the database.
5. // Read-only transactions can be used for retrieving values for keys and creating cursors.
6. // Read/write transactions can create and remove buckets and create and remove keys.
7. //
8. // IMPORTANT: You must commit or rollback transactions when you are done with
9. // them. Pages can not be reclaimed by the writer until no more transactions
10. // are using them. A long running read transaction can cause the database to
11. // quickly grow.
12. // Tx 主要封装了读事务和写事务。其中通过writable来区分是读事务还是写事务
13. type Tx struct {
14. writable       bool
15. managed        bool
16. db             *DB
17. meta           *meta
18. root           Bucket
19. pages          map[pgid]*page
20. stats          TxStats
21. // 提交时执行的动作
22. commitHandlers []func()

24. // WriteFlag specifies the flag for write-related methods like WriteTo().
25. // Tx opens the database file with the specified flag to copy the data.
26. //
27. // By default, the flag is unset, which works well for mostly in-memory
28. // workloads. For databases that are much larger than available RAM,
29. // set the flag to syscall.O_DIRECT to avoid trashing the page cache.
30. WriteFlag int
31. }

33. // init initializes the transaction.
34. func (tx *Tx) init(db *DB) {
35. tx.db = db
36. tx.pages = nil

38. // Copy the meta page since it can be changed by the writer.
39. // 拷贝元信息
40. tx.meta = &meta{}
41. db.meta().copy(tx.meta)

43. // Copy over the root bucket.
44. // 拷贝根节点
45. tx.root = newBucket(tx)
46. tx.root.bucket = &bucket{}
47. // meta.root=bucket{root:3}
48. *tx.root.bucket = tx.meta.root

50. // Increment the transaction id and add a page cache for writable transactions.
51. if tx.writable {
52. tx.pages = make(map[pgid]*page)
53. tx.meta.txid += txid(1)
54. }
55. }