第二节 boltdb事务Tx定义

  1. // txid represents the internal transaction identifier.
  2. type txid uint64
  3. // Tx represents a read-only or read/write transaction on the database.
  4. // Read-only transactions can be used for retrieving values for keys and creating cursors.
  5. // Read/write transactions can create and remove buckets and create and remove keys.
  6. //
  7. // IMPORTANT: You must commit or rollback transactions when you are done with
  8. // them. Pages can not be reclaimed by the writer until no more transactions
  9. // are using them. A long running read transaction can cause the database to
  10. // quickly grow.
  11. // Tx 主要封装了读事务和写事务。其中通过writable来区分是读事务还是写事务
  12. type Tx struct {
  13. writable bool
  14. managed bool
  15. db *DB
  16. meta *meta
  17. root Bucket
  18. pages map[pgid]*page
  19. stats TxStats
  20. // 提交时执行的动作
  21. commitHandlers []func()
  22. // WriteFlag specifies the flag for write-related methods like WriteTo().
  23. // Tx opens the database file with the specified flag to copy the data.
  24. //
  25. // By default, the flag is unset, which works well for mostly in-memory
  26. // workloads. For databases that are much larger than available RAM,
  27. // set the flag to syscall.O_DIRECT to avoid trashing the page cache.
  28. WriteFlag int
  29. }
  30. // init initializes the transaction.
  31. func (tx *Tx) init(db *DB) {
  32. tx.db = db
  33. tx.pages = nil
  34. // Copy the meta page since it can be changed by the writer.
  35. // 拷贝元信息
  36. tx.meta = &meta{}
  37. db.meta().copy(tx.meta)
  38. // Copy over the root bucket.
  39. // 拷贝根节点
  40. tx.root = newBucket(tx)
  41. tx.root.bucket = &bucket{}
  42. // meta.root=bucket{root:3}
  43. *tx.root.bucket = tx.meta.root
  44. // Increment the transaction id and add a page cache for writable transactions.
  45. if tx.writable {
  46. tx.pages = make(map[pgid]*page)
  47. tx.meta.txid += txid(1)
  48. }
  49. }