From a29c375dfe90831de44c1e56a59f837fc6c5a0cd Mon Sep 17 00:00:00 2001 From: ahrtr Date: Mon, 8 Nov 2021 08:54:50 +0800 Subject: [PATCH] enhance check command to detect duplicated keys in each bucket --- tx.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tx.go b/tx.go index 869d41200..c9199501d 100644 --- a/tx.go +++ b/tx.go @@ -1,6 +1,7 @@ package bbolt import ( + "crypto/sha1" "fmt" "io" "os" @@ -483,6 +484,20 @@ func (tx *Tx) checkBucket(b *Bucket, reachable map[pgid]*page, freed map[pgid]bo } }) + // Check all the keys in this bucket, and raise an error if there are duplicated keys. + cachedKeys := map[[sha1.Size]byte][]byte{} + b.ForEach(func(key, _ []byte) error { + sha1Key := sha1.Sum(key) + if val, ok := cachedKeys[sha1Key]; ok { + ch <- fmt.Errorf("duplicated key: %q found", val) + } else { + cachedKeys[sha1Key] = key + } + return nil + }) + // clear the map + cachedKeys = map[[sha1.Size]byte][]byte{} + // Check each bucket within this bucket. _ = b.ForEach(func(k, v []byte) error { if child := b.Bucket(k); child != nil {