You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. package bbolt
  2. import (
  3. "bytes"
  4. "fmt"
  5. "unsafe"
  6. )
  7. const (
  8. // MaxKeySize is the maximum length of a key, in bytes.
  9. MaxKeySize = 32768
  10. // MaxValueSize is the maximum length of a value, in bytes.
  11. MaxValueSize = (1 << 31) - 2
  12. )
  13. const bucketHeaderSize = int(unsafe.Sizeof(bucket{}))
  14. const (
  15. minFillPercent = 0.1
  16. maxFillPercent = 1.0
  17. )
  18. // DefaultFillPercent is the percentage that split pages are filled.
  19. // This value can be changed by setting Bucket.FillPercent.
  20. const DefaultFillPercent = 0.5
  21. // Bucket represents a collection of key/value pairs inside the database.
  22. type Bucket struct {
  23. *bucket
  24. tx *Tx // the associated transaction
  25. buckets map[string]*Bucket // subbucket cache
  26. page *page // inline page reference
  27. rootNode *node // materialized node for the root page.
  28. nodes map[pgid]*node // node cache
  29. // Sets the threshold for filling nodes when they split. By default,
  30. // the bucket will fill to 50% but it can be useful to increase this
  31. // amount if you know that your write workloads are mostly append-only.
  32. //
  33. // This is non-persisted across transactions so it must be set in every Tx.
  34. FillPercent float64
  35. }
  36. // bucket represents the on-file representation of a bucket.
  37. // This is stored as the "value" of a bucket key. If the bucket is small enough,
  38. // then its root page can be stored inline in the "value", after the bucket
  39. // header. In the case of inline buckets, the "root" will be 0.
  40. type bucket struct {
  41. root pgid // page id of the bucket's root-level page
  42. sequence uint64 // monotonically incrementing, used by NextSequence()
  43. }
  44. // newBucket returns a new bucket associated with a transaction.
  45. func newBucket(tx *Tx) Bucket {
  46. var b = Bucket{tx: tx, FillPercent: DefaultFillPercent}
  47. if tx.writable {
  48. b.buckets = make(map[string]*Bucket)
  49. b.nodes = make(map[pgid]*node)
  50. }
  51. return b
  52. }
  53. // Tx returns the tx of the bucket.
  54. func (b *Bucket) Tx() *Tx {
  55. return b.tx
  56. }
  57. // Root returns the root of the bucket.
  58. func (b *Bucket) Root() pgid {
  59. return b.root
  60. }
  61. // Writable returns whether the bucket is writable.
  62. func (b *Bucket) Writable() bool {
  63. return b.tx.writable
  64. }
  65. // Cursor creates a cursor associated with the bucket.
  66. // The cursor is only valid as long as the transaction is open.
  67. // Do not use a cursor after the transaction is closed.
  68. func (b *Bucket) Cursor() *Cursor {
  69. // Update transaction statistics.
  70. b.tx.stats.CursorCount++
  71. // Allocate and return a cursor.
  72. return &Cursor{
  73. bucket: b,
  74. stack: make([]elemRef, 0),
  75. }
  76. }
  77. // Bucket retrieves a nested bucket by name.
  78. // Returns nil if the bucket does not exist.
  79. // The bucket instance is only valid for the lifetime of the transaction.
  80. func (b *Bucket) Bucket(name []byte) *Bucket {
  81. if b.buckets != nil {
  82. if child := b.buckets[string(name)]; child != nil {
  83. return child
  84. }
  85. }
  86. // Move cursor to key.
  87. c := b.Cursor()
  88. k, v, flags := c.seek(name)
  89. // Return nil if the key doesn't exist or it is not a bucket.
  90. if !bytes.Equal(name, k) || (flags&bucketLeafFlag) == 0 {
  91. return nil
  92. }
  93. // Otherwise create a bucket and cache it.
  94. var child = b.openBucket(v)
  95. if b.buckets != nil {
  96. b.buckets[string(name)] = child
  97. }
  98. return child
  99. }
  100. // Helper method that re-interprets a sub-bucket value
  101. // from a parent into a Bucket
  102. func (b *Bucket) openBucket(value []byte) *Bucket {
  103. var child = newBucket(b.tx)
  104. // Unaligned access requires a copy to be made.
  105. const unalignedMask = unsafe.Alignof(struct {
  106. bucket
  107. page
  108. }{}) - 1
  109. unaligned := uintptr(unsafe.Pointer(&value[0]))&unalignedMask != 0
  110. if unaligned {
  111. value = cloneBytes(value)
  112. }
  113. // If this is a writable transaction then we need to copy the bucket entry.
  114. // Read-only transactions can point directly at the mmap entry.
  115. if b.tx.writable && !unaligned {
  116. child.bucket = &bucket{}
  117. *child.bucket = *(*bucket)(unsafe.Pointer(&value[0]))
  118. } else {
  119. child.bucket = (*bucket)(unsafe.Pointer(&value[0]))
  120. }
  121. // Save a reference to the inline page if the bucket is inline.
  122. if child.root == 0 {
  123. child.page = (*page)(unsafe.Pointer(&value[bucketHeaderSize]))
  124. }
  125. return &child
  126. }
  127. // CreateBucket creates a new bucket at the given key and returns the new bucket.
  128. // Returns an error if the key already exists, if the bucket name is blank, or if the bucket name is too long.
  129. // The bucket instance is only valid for the lifetime of the transaction.
  130. func (b *Bucket) CreateBucket(key []byte) (*Bucket, error) {
  131. if b.tx.db == nil {
  132. return nil, ErrTxClosed
  133. } else if !b.tx.writable {
  134. return nil, ErrTxNotWritable
  135. } else if len(key) == 0 {
  136. return nil, ErrBucketNameRequired
  137. }
  138. // Move cursor to correct position.
  139. c := b.Cursor()
  140. k, _, flags := c.seek(key)
  141. // Return an error if there is an existing key.
  142. if bytes.Equal(key, k) {
  143. if (flags & bucketLeafFlag) != 0 {
  144. return nil, ErrBucketExists
  145. }
  146. return nil, ErrIncompatibleValue
  147. }
  148. // Create empty, inline bucket.
  149. var bucket = Bucket{
  150. bucket: &bucket{},
  151. rootNode: &node{isLeaf: true},
  152. FillPercent: DefaultFillPercent,
  153. }
  154. var value = bucket.write()
  155. // Insert into node.
  156. key = cloneBytes(key)
  157. c.node().put(key, key, value, 0, bucketLeafFlag)
  158. // Since subbuckets are not allowed on inline buckets, we need to
  159. // dereference the inline page, if it exists. This will cause the bucket
  160. // to be treated as a regular, non-inline bucket for the rest of the tx.
  161. b.page = nil
  162. return b.Bucket(key), nil
  163. }
  164. // CreateBucketIfNotExists creates a new bucket if it doesn't already exist and returns a reference to it.
  165. // Returns an error if the bucket name is blank, or if the bucket name is too long.
  166. // The bucket instance is only valid for the lifetime of the transaction.
  167. func (b *Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) {
  168. child, err := b.CreateBucket(key)
  169. if err == ErrBucketExists {
  170. return b.Bucket(key), nil
  171. } else if err != nil {
  172. return nil, err
  173. }
  174. return child, nil
  175. }
  176. // DeleteBucket deletes a bucket at the given key.
  177. // Returns an error if the bucket does not exist, or if the key represents a non-bucket value.
  178. func (b *Bucket) DeleteBucket(key []byte) error {
  179. if b.tx.db == nil {
  180. return ErrTxClosed
  181. } else if !b.Writable() {
  182. return ErrTxNotWritable
  183. }
  184. // Move cursor to correct position.
  185. c := b.Cursor()
  186. k, _, flags := c.seek(key)
  187. // Return an error if bucket doesn't exist or is not a bucket.
  188. if !bytes.Equal(key, k) {
  189. return ErrBucketNotFound
  190. } else if (flags & bucketLeafFlag) == 0 {
  191. return ErrIncompatibleValue
  192. }
  193. // Recursively delete all child buckets.
  194. child := b.Bucket(key)
  195. err := child.ForEach(func(k, v []byte) error {
  196. if _, _, childFlags := child.Cursor().seek(k); (childFlags & bucketLeafFlag) != 0 {
  197. if err := child.DeleteBucket(k); err != nil {
  198. return fmt.Errorf("delete bucket: %s", err)
  199. }
  200. }
  201. return nil
  202. })
  203. if err != nil {
  204. return err
  205. }
  206. // Remove cached copy.
  207. delete(b.buckets, string(key))
  208. // Release all bucket pages to freelist.
  209. child.nodes = nil
  210. child.rootNode = nil
  211. child.free()
  212. // Delete the node if we have a matching key.
  213. c.node().del(key)
  214. return nil
  215. }
  216. // Get retrieves the value for a key in the bucket.
  217. // Returns a nil value if the key does not exist or if the key is a nested bucket.
  218. // The returned value is only valid for the life of the transaction.
  219. func (b *Bucket) Get(key []byte) []byte {
  220. k, v, flags := b.Cursor().seek(key)
  221. // Return nil if this is a bucket.
  222. if (flags & bucketLeafFlag) != 0 {
  223. return nil
  224. }
  225. // If our target node isn't the same key as what's passed in then return nil.
  226. if !bytes.Equal(key, k) {
  227. return nil
  228. }
  229. return v
  230. }
  231. // Put sets the value for a key in the bucket.
  232. // If the key exist then its previous value will be overwritten.
  233. // Supplied value must remain valid for the life of the transaction.
  234. // Returns an error if the bucket was created from a read-only transaction, if the key is blank, if the key is too large, or if the value is too large.
  235. func (b *Bucket) Put(key []byte, value []byte) error {
  236. if b.tx.db == nil {
  237. return ErrTxClosed
  238. } else if !b.Writable() {
  239. return ErrTxNotWritable
  240. } else if len(key) == 0 {
  241. return ErrKeyRequired
  242. } else if len(key) > MaxKeySize {
  243. return ErrKeyTooLarge
  244. } else if int64(len(value)) > MaxValueSize {
  245. return ErrValueTooLarge
  246. }
  247. // Move cursor to correct position.
  248. c := b.Cursor()
  249. k, _, flags := c.seek(key)
  250. // Return an error if there is an existing key with a bucket value.
  251. if bytes.Equal(key, k) && (flags&bucketLeafFlag) != 0 {
  252. return ErrIncompatibleValue
  253. }
  254. // Insert into node.
  255. key = cloneBytes(key)
  256. c.node().put(key, key, value, 0, 0)
  257. return nil
  258. }
  259. // Delete removes a key from the bucket.
  260. // If the key does not exist then nothing is done and a nil error is returned.
  261. // Returns an error if the bucket was created from a read-only transaction.
  262. func (b *Bucket) Delete(key []byte) error {
  263. if b.tx.db == nil {
  264. return ErrTxClosed
  265. } else if !b.Writable() {
  266. return ErrTxNotWritable
  267. }
  268. // Move cursor to correct position.
  269. c := b.Cursor()
  270. k, _, flags := c.seek(key)
  271. // Return nil if the key doesn't exist.
  272. if !bytes.Equal(key, k) {
  273. return nil
  274. }
  275. // Return an error if there is already existing bucket value.
  276. if (flags & bucketLeafFlag) != 0 {
  277. return ErrIncompatibleValue
  278. }
  279. // Delete the node if we have a matching key.
  280. c.node().del(key)
  281. return nil
  282. }
  283. // Sequence returns the current integer for the bucket without incrementing it.
  284. func (b *Bucket) Sequence() uint64 { return b.bucket.sequence }
  285. // SetSequence updates the sequence number for the bucket.
  286. func (b *Bucket) SetSequence(v uint64) error {
  287. if b.tx.db == nil {
  288. return ErrTxClosed
  289. } else if !b.Writable() {
  290. return ErrTxNotWritable
  291. }
  292. // Materialize the root node if it hasn't been already so that the
  293. // bucket will be saved during commit.
  294. if b.rootNode == nil {
  295. _ = b.node(b.root, nil)
  296. }
  297. // Increment and return the sequence.
  298. b.bucket.sequence = v
  299. return nil
  300. }
  301. // NextSequence returns an autoincrementing integer for the bucket.
  302. func (b *Bucket) NextSequence() (uint64, error) {
  303. if b.tx.db == nil {
  304. return 0, ErrTxClosed
  305. } else if !b.Writable() {
  306. return 0, ErrTxNotWritable
  307. }
  308. // Materialize the root node if it hasn't been already so that the
  309. // bucket will be saved during commit.
  310. if b.rootNode == nil {
  311. _ = b.node(b.root, nil)
  312. }
  313. // Increment and return the sequence.
  314. b.bucket.sequence++
  315. return b.bucket.sequence, nil
  316. }
  317. // ForEach executes a function for each key/value pair in a bucket.
  318. // If the provided function returns an error then the iteration is stopped and
  319. // the error is returned to the caller. The provided function must not modify
  320. // the bucket; this will result in undefined behavior.
  321. func (b *Bucket) ForEach(fn func(k, v []byte) error) error {
  322. if b.tx.db == nil {
  323. return ErrTxClosed
  324. }
  325. c := b.Cursor()
  326. for k, v := c.First(); k != nil; k, v = c.Next() {
  327. if err := fn(k, v); err != nil {
  328. return err
  329. }
  330. }
  331. return nil
  332. }
  333. // Stat returns stats on a bucket.
  334. func (b *Bucket) Stats() BucketStats {
  335. var s, subStats BucketStats
  336. pageSize := b.tx.db.pageSize
  337. s.BucketN += 1
  338. if b.root == 0 {
  339. s.InlineBucketN += 1
  340. }
  341. b.forEachPage(func(p *page, depth int) {
  342. if (p.flags & leafPageFlag) != 0 {
  343. s.KeyN += int(p.count)
  344. // used totals the used bytes for the page
  345. used := pageHeaderSize
  346. if p.count != 0 {
  347. // If page has any elements, add all element headers.
  348. used += leafPageElementSize * uintptr(p.count-1)
  349. // Add all element key, value sizes.
  350. // The computation takes advantage of the fact that the position
  351. // of the last element's key/value equals to the total of the sizes
  352. // of all previous elements' keys and values.
  353. // It also includes the last element's header.
  354. lastElement := p.leafPageElement(p.count - 1)
  355. used += uintptr(lastElement.pos + lastElement.ksize + lastElement.vsize)
  356. }
  357. if b.root == 0 {
  358. // For inlined bucket just update the inline stats
  359. s.InlineBucketInuse += int(used)
  360. } else {
  361. // For non-inlined bucket update all the leaf stats
  362. s.LeafPageN++
  363. s.LeafInuse += int(used)
  364. s.LeafOverflowN += int(p.overflow)
  365. // Collect stats from sub-buckets.
  366. // Do that by iterating over all element headers
  367. // looking for the ones with the bucketLeafFlag.
  368. for i := uint16(0); i < p.count; i++ {
  369. e := p.leafPageElement(i)
  370. if (e.flags & bucketLeafFlag) != 0 {
  371. // For any bucket element, open the element value
  372. // and recursively call Stats on the contained bucket.
  373. subStats.Add(b.openBucket(e.value()).Stats())
  374. }
  375. }
  376. }
  377. } else if (p.flags & branchPageFlag) != 0 {
  378. s.BranchPageN++
  379. lastElement := p.branchPageElement(p.count - 1)
  380. // used totals the used bytes for the page
  381. // Add header and all element headers.
  382. used := pageHeaderSize + (branchPageElementSize * uintptr(p.count-1))
  383. // Add size of all keys and values.
  384. // Again, use the fact that last element's position equals to
  385. // the total of key, value sizes of all previous elements.
  386. used += uintptr(lastElement.pos + lastElement.ksize)
  387. s.BranchInuse += int(used)
  388. s.BranchOverflowN += int(p.overflow)
  389. }
  390. // Keep track of maximum page depth.
  391. if depth+1 > s.Depth {
  392. s.Depth = (depth + 1)
  393. }
  394. })
  395. // Alloc stats can be computed from page counts and pageSize.
  396. s.BranchAlloc = (s.BranchPageN + s.BranchOverflowN) * pageSize
  397. s.LeafAlloc = (s.LeafPageN + s.LeafOverflowN) * pageSize
  398. // Add the max depth of sub-buckets to get total nested depth.
  399. s.Depth += subStats.Depth
  400. // Add the stats for all sub-buckets
  401. s.Add(subStats)
  402. return s
  403. }
  404. // forEachPage iterates over every page in a bucket, including inline pages.
  405. func (b *Bucket) forEachPage(fn func(*page, int)) {
  406. // If we have an inline page then just use that.
  407. if b.page != nil {
  408. fn(b.page, 0)
  409. return
  410. }
  411. // Otherwise traverse the page hierarchy.
  412. b.tx.forEachPage(b.root, 0, fn)
  413. }
  414. // forEachPageNode iterates over every page (or node) in a bucket.
  415. // This also includes inline pages.
  416. func (b *Bucket) forEachPageNode(fn func(*page, *node, int)) {
  417. // If we have an inline page or root node then just use that.
  418. if b.page != nil {
  419. fn(b.page, nil, 0)
  420. return
  421. }
  422. b._forEachPageNode(b.root, 0, fn)
  423. }
  424. func (b *Bucket) _forEachPageNode(pgid pgid, depth int, fn func(*page, *node, int)) {
  425. var p, n = b.pageNode(pgid)
  426. // Execute function.
  427. fn(p, n, depth)
  428. // Recursively loop over children.
  429. if p != nil {
  430. if (p.flags & branchPageFlag) != 0 {
  431. for i := 0; i < int(p.count); i++ {
  432. elem := p.branchPageElement(uint16(i))
  433. b._forEachPageNode(elem.pgid, depth+1, fn)
  434. }
  435. }
  436. } else {
  437. if !n.isLeaf {
  438. for _, inode := range n.inodes {
  439. b._forEachPageNode(inode.pgid, depth+1, fn)
  440. }
  441. }
  442. }
  443. }
  444. // spill writes all the nodes for this bucket to dirty pages.
  445. func (b *Bucket) spill() error {
  446. // Spill all child buckets first.
  447. for name, child := range b.buckets {
  448. // If the child bucket is small enough and it has no child buckets then
  449. // write it inline into the parent bucket's page. Otherwise spill it
  450. // like a normal bucket and make the parent value a pointer to the page.
  451. var value []byte
  452. if child.inlineable() {
  453. child.free()
  454. value = child.write()
  455. } else {
  456. if err := child.spill(); err != nil {
  457. return err
  458. }
  459. // Update the child bucket header in this bucket.
  460. value = make([]byte, unsafe.Sizeof(bucket{}))
  461. var bucket = (*bucket)(unsafe.Pointer(&value[0]))
  462. *bucket = *child.bucket
  463. }
  464. // Skip writing the bucket if there are no materialized nodes.
  465. if child.rootNode == nil {
  466. continue
  467. }
  468. // Update parent node.
  469. var c = b.Cursor()
  470. k, _, flags := c.seek([]byte(name))
  471. if !bytes.Equal([]byte(name), k) {
  472. panic(fmt.Sprintf("misplaced bucket header: %x -> %x", []byte(name), k))
  473. }
  474. if flags&bucketLeafFlag == 0 {
  475. panic(fmt.Sprintf("unexpected bucket header flag: %x", flags))
  476. }
  477. c.node().put([]byte(name), []byte(name), value, 0, bucketLeafFlag)
  478. }
  479. // Ignore if there's not a materialized root node.
  480. if b.rootNode == nil {
  481. return nil
  482. }
  483. // Spill nodes.
  484. if err := b.rootNode.spill(); err != nil {
  485. return err
  486. }
  487. b.rootNode = b.rootNode.root()
  488. // Update the root node for this bucket.
  489. if b.rootNode.pgid >= b.tx.meta.pgid {
  490. panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", b.rootNode.pgid, b.tx.meta.pgid))
  491. }
  492. b.root = b.rootNode.pgid
  493. return nil
  494. }
  495. // inlineable returns true if a bucket is small enough to be written inline
  496. // and if it contains no subbuckets. Otherwise returns false.
  497. func (b *Bucket) inlineable() bool {
  498. var n = b.rootNode
  499. // Bucket must only contain a single leaf node.
  500. if n == nil || !n.isLeaf {
  501. return false
  502. }
  503. // Bucket is not inlineable if it contains subbuckets or if it goes beyond
  504. // our threshold for inline bucket size.
  505. var size = pageHeaderSize
  506. for _, inode := range n.inodes {
  507. size += leafPageElementSize + uintptr(len(inode.key)) + uintptr(len(inode.value))
  508. if inode.flags&bucketLeafFlag != 0 {
  509. return false
  510. } else if size > b.maxInlineBucketSize() {
  511. return false
  512. }
  513. }
  514. return true
  515. }
  516. // Returns the maximum total size of a bucket to make it a candidate for inlining.
  517. func (b *Bucket) maxInlineBucketSize() uintptr {
  518. return uintptr(b.tx.db.pageSize / 4)
  519. }
  520. // write allocates and writes a bucket to a byte slice.
  521. func (b *Bucket) write() []byte {
  522. // Allocate the appropriate size.
  523. var n = b.rootNode
  524. var value = make([]byte, bucketHeaderSize+n.size())
  525. // Write a bucket header.
  526. var bucket = (*bucket)(unsafe.Pointer(&value[0]))
  527. *bucket = *b.bucket
  528. // Convert byte slice to a fake page and write the root node.
  529. var p = (*page)(unsafe.Pointer(&value[bucketHeaderSize]))
  530. n.write(p)
  531. return value
  532. }
  533. // rebalance attempts to balance all nodes.
  534. func (b *Bucket) rebalance() {
  535. for _, n := range b.nodes {
  536. n.rebalance()
  537. }
  538. for _, child := range b.buckets {
  539. child.rebalance()
  540. }
  541. }
  542. // node creates a node from a page and associates it with a given parent.
  543. func (b *Bucket) node(pgid pgid, parent *node) *node {
  544. _assert(b.nodes != nil, "nodes map expected")
  545. // Retrieve node if it's already been created.
  546. if n := b.nodes[pgid]; n != nil {
  547. return n
  548. }
  549. // Otherwise create a node and cache it.
  550. n := &node{bucket: b, parent: parent}
  551. if parent == nil {
  552. b.rootNode = n
  553. } else {
  554. parent.children = append(parent.children, n)
  555. }
  556. // Use the inline page if this is an inline bucket.
  557. var p = b.page
  558. if p == nil {
  559. p = b.tx.page(pgid)
  560. }
  561. // Read the page into the node and cache it.
  562. n.read(p)
  563. b.nodes[pgid] = n
  564. // Update statistics.
  565. b.tx.stats.NodeCount++
  566. return n
  567. }
  568. // free recursively frees all pages in the bucket.
  569. func (b *Bucket) free() {
  570. if b.root == 0 {
  571. return
  572. }
  573. var tx = b.tx
  574. b.forEachPageNode(func(p *page, n *node, _ int) {
  575. if p != nil {
  576. tx.db.freelist.free(tx.meta.txid, p)
  577. } else {
  578. n.free()
  579. }
  580. })
  581. b.root = 0
  582. }
  583. // dereference removes all references to the old mmap.
  584. func (b *Bucket) dereference() {
  585. if b.rootNode != nil {
  586. b.rootNode.root().dereference()
  587. }
  588. for _, child := range b.buckets {
  589. child.dereference()
  590. }
  591. }
  592. // pageNode returns the in-memory node, if it exists.
  593. // Otherwise returns the underlying page.
  594. func (b *Bucket) pageNode(id pgid) (*page, *node) {
  595. // Inline buckets have a fake page embedded in their value so treat them
  596. // differently. We'll return the rootNode (if available) or the fake page.
  597. if b.root == 0 {
  598. if id != 0 {
  599. panic(fmt.Sprintf("inline bucket non-zero page access(2): %d != 0", id))
  600. }
  601. if b.rootNode != nil {
  602. return nil, b.rootNode
  603. }
  604. return b.page, nil
  605. }
  606. // Check the node cache for non-inline buckets.
  607. if b.nodes != nil {
  608. if n := b.nodes[id]; n != nil {
  609. return nil, n
  610. }
  611. }
  612. // Finally lookup the page from the transaction if no node is materialized.
  613. return b.tx.page(id), nil
  614. }
  615. // BucketStats records statistics about resources used by a bucket.
  616. type BucketStats struct {
  617. // Page count statistics.
  618. BranchPageN int // number of logical branch pages
  619. BranchOverflowN int // number of physical branch overflow pages
  620. LeafPageN int // number of logical leaf pages
  621. LeafOverflowN int // number of physical leaf overflow pages
  622. // Tree statistics.
  623. KeyN int // number of keys/value pairs
  624. Depth int // number of levels in B+tree
  625. // Page size utilization.
  626. BranchAlloc int // bytes allocated for physical branch pages
  627. BranchInuse int // bytes actually used for branch data
  628. LeafAlloc int // bytes allocated for physical leaf pages
  629. LeafInuse int // bytes actually used for leaf data
  630. // Bucket statistics
  631. BucketN int // total number of buckets including the top bucket
  632. InlineBucketN int // total number on inlined buckets
  633. InlineBucketInuse int // bytes used for inlined buckets (also accounted for in LeafInuse)
  634. }
  635. func (s *BucketStats) Add(other BucketStats) {
  636. s.BranchPageN += other.BranchPageN
  637. s.BranchOverflowN += other.BranchOverflowN
  638. s.LeafPageN += other.LeafPageN
  639. s.LeafOverflowN += other.LeafOverflowN
  640. s.KeyN += other.KeyN
  641. if s.Depth < other.Depth {
  642. s.Depth = other.Depth
  643. }
  644. s.BranchAlloc += other.BranchAlloc
  645. s.BranchInuse += other.BranchInuse
  646. s.LeafAlloc += other.LeafAlloc
  647. s.LeafInuse += other.LeafInuse
  648. s.BucketN += other.BucketN
  649. s.InlineBucketN += other.InlineBucketN
  650. s.InlineBucketInuse += other.InlineBucketInuse
  651. }
  652. // cloneBytes returns a copy of a given slice.
  653. func cloneBytes(v []byte) []byte {
  654. var clone = make([]byte, len(v))
  655. copy(clone, v)
  656. return clone
  657. }