Created
July 15, 2020 09:22
-
-
Save nicewook/274ce0568869fa679dcb03d1ba7396c5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/binary" | |
"encoding/json" | |
"fmt" | |
"log" | |
"github.com/timshannon/bolthold" | |
bolt "go.etcd.io/bbolt" | |
) | |
type TestStruct struct { | |
ID uint64 | |
Name string | |
} | |
func itob(v uint64) []byte { | |
b := make([]byte, 8) | |
binary.BigEndian.PutUint64(b, v) | |
// binary.LittleEndian.PutUint64(b, v) | |
// fmt.Printf("%d, %v", b, b) | |
return b | |
} | |
func main() { | |
db, err := bolthold.Open("./mytest.db", 0666, &bolthold.Options{ | |
Encoder: json.Marshal, | |
Decoder: json.Unmarshal, | |
}) | |
if err != nil { | |
log.Printf("fail to open txLog.db: %v", err) | |
return | |
} | |
defer db.Close() | |
// tS := TestStruct{ | |
// 0, | |
// "HaHa" | |
// } | |
repeat := 10 | |
txErr := db.Bolt().Update(func(tx *bolt.Tx) error { | |
b, _ := tx.CreateBucketIfNotExists([]byte("TestStruct")) | |
for i := 0; i < repeat; i++ { | |
// 1. random select one item from uiSlice, upSlice | |
id, _ := b.NextSequence() | |
tempName := fmt.Sprintf("Haha-%d", i) | |
tempTs := TestStruct{ | |
id, | |
tempName, | |
} | |
buf, errJson := json.Marshal(tempTs) | |
fmt.Printf("%s\n", buf) | |
if errJson != nil { | |
fmt.Println("errJson: ", errJson) | |
} | |
// fmt.Printf("buf: %s", buf) | |
if err := b.Put(itob(id), buf); err != nil { | |
log.Printf("fail to add TransactionLog to txlog.db: %v", err) | |
return err | |
} | |
} | |
return nil | |
}) | |
if txErr != nil { | |
log.Println("transaction fails: ", txErr) | |
} | |
// read | |
readTs := []TestStruct{} | |
if err := db.Find(&readTs, bolthold.Where("ID").Le(uint64(100))); err != nil { | |
log.Printf("fail to get All from TransactionLog: %v", err) | |
return | |
} | |
for _, v := range readTs { | |
fmt.Printf("%#v\n", v) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment