core/rawdb: add test for table

This commit is contained in:
Gary Rong 2025-06-18 13:36:54 +08:00
parent cabe2dafde
commit 9bc6bf62ce
2 changed files with 36 additions and 0 deletions

View file

@ -17,6 +17,8 @@
package rawdb package rawdb
import ( import (
"bytes"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
) )
@ -132,6 +134,11 @@ func (t *table) Delete(key []byte) error {
// DeleteRange deletes all of the keys (and values) in the range [start,end) // DeleteRange deletes all of the keys (and values) in the range [start,end)
// (inclusive on start, exclusive on end). // (inclusive on start, exclusive on end).
func (t *table) DeleteRange(start, end []byte) error { func (t *table) DeleteRange(start, end []byte) error {
// The nilness will be lost by adding the prefix, explicitly converting it
// to a special flag representing the end of key range.
if end == nil {
end = bytes.Repeat([]byte{0xff}, 32)
}
return t.db.DeleteRange(append([]byte(t.prefix), start...), append([]byte(t.prefix), end...)) return t.db.DeleteRange(append([]byte(t.prefix), start...), append([]byte(t.prefix), end...))
} }
@ -225,6 +232,11 @@ func (b *tableBatch) Delete(key []byte) error {
// DeleteRange removes all keys in the range [start, end) from the batch for later committing. // DeleteRange removes all keys in the range [start, end) from the batch for later committing.
func (b *tableBatch) DeleteRange(start, end []byte) error { func (b *tableBatch) DeleteRange(start, end []byte) error {
// The nilness will be lost by adding the prefix, explicitly converting it
// to a special flag representing the end of key range.
if end == nil {
end = bytes.Repeat([]byte{0xff}, 32)
}
return b.batch.DeleteRange(append([]byte(b.prefix), start...), append([]byte(b.prefix), end...)) return b.batch.DeleteRange(append([]byte(b.prefix), start...), append([]byte(b.prefix), end...))
} }

View file

@ -125,4 +125,28 @@ func testTableDatabase(t *testing.T, prefix string) {
// Test iterators with prefix and start point // Test iterators with prefix and start point
check(db.NewIterator([]byte{0xee}, nil), 0, 0) check(db.NewIterator([]byte{0xee}, nil), 0, 0)
check(db.NewIterator(nil, []byte{0x00}), 6, 0) check(db.NewIterator(nil, []byte{0x00}), 6, 0)
// Test range deletion
db.DeleteRange(nil, nil)
for _, entry := range entries {
_, err := db.Get(entry.key)
if err == nil {
t.Fatal("Unexpected item after deletion")
}
}
// Test range deletion by batch
batch = db.NewBatch()
for _, entry := range entries {
batch.Put(entry.key, entry.value)
}
batch.Write()
batch.Reset()
batch.DeleteRange(nil, nil)
batch.Write()
for _, entry := range entries {
_, err := db.Get(entry.key)
if err == nil {
t.Fatal("Unexpected item after deletion")
}
}
} }