Skip to content

Instantly share code, notes, and snippets.

@bittrance
Created November 12, 2021 19:47
Show Gist options
  • Save bittrance/496fa2d5e2aa94932d18d5e0e1406bb3 to your computer and use it in GitHub Desktop.
Save bittrance/496fa2d5e2aa94932d18d5e0e1406bb3 to your computer and use it in GitHub Desktop.
go-memdb test uint64
package main
import (
"fmt"
"math/rand"
"os"
"time"
memdb "github.com/hashicorp/go-memdb"
)
type Item struct {
Id string
IntNum uint64
}
func main() {
rand.Seed(time.Now().UnixNano())
expected, actual := once()
for {
if expected == actual {
fmt.Print(".")
} else {
fmt.Printf("Expected %d results, got %d\n", expected, actual)
os.Exit(1)
}
}
}
func once() (int, int) {
schema := &memdb.DBSchema{
Tables: map[string]*memdb.TableSchema{
"test": {
Name: "test",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.StringFieldIndex{Field: "Id"},
},
"int": {
Name: "int",
Unique: false,
Indexer: &memdb.UintFieldIndex{Field: "IntNum"},
},
},
},
},
}
store, err := memdb.NewMemDB(schema)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
numbers := make([]uint64, 0)
for i := 0; i < 200; i++ {
numbers = append(numbers, rand.Uint64())
}
txn := store.Txn(true)
for _, number := range numbers {
id := fmt.Sprintf("%d", number)
txn.Insert("test", Item{Id: id, IntNum: number})
}
txn.Commit()
threshold := rand.Uint64()
expected := make([]uint64, 0)
for _, number := range numbers {
if number >= threshold {
expected = append(expected, number)
}
}
txn = store.Txn(false)
res, err := txn.LowerBound("test", "int", threshold)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
actual := make([]interface{}, 0)
for v := res.Next(); v != nil; v = res.Next() {
actual = append(actual, v)
}
return len(expected), len(actual)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment