func main() { ro := &opt.ReadOptions{} wo := &opt.WriteOptions{} opts := &opt.Options{} ldb, err := leveldb.OpenFile("dbfile", opts) if err != nil { fmt.Printf("db open failed %v\n", err) return } batch := new(leveldb.Batch) for _, datum := range dataset { key := fmt.Sprintf("%v", datum.key) batch.Put([]byte(key), []byte(datum.value)) } err = ldb.Write(batch, wo) for _, datum := range dataset { key := fmt.Sprintf("%v", datum.key) data, err := ldb.Get([]byte(key), ro) if err != nil { fmt.Printf("db read failed %v\n", err) } if string(data) != datum.value { fmt.Printf("mismatched data from db key %v val %v db %v", key, datum.value, data) } } fmt.Printf("completed\n") ldb.Close() }
func openDB(dbpath string, create bool) (pbdb btcdb.Db, err error) { var db LevelDb var tlDb *leveldb.DB var dbversion int32 defer func() { if err == nil { db.lDb = tlDb db.txUpdateMap = map[btcwire.ShaHash]*txUpdateObj{} db.txSpentUpdateMap = make(map[btcwire.ShaHash]*spentTxUpdate) pbdb = &db } }() if create == true { err = os.Mkdir(dbpath, 0750) if err != nil { log.Errorf("mkdir failed %v %v", dbpath, err) return } } else { _, err = os.Stat(dbpath) if err != nil { err = btcdb.ErrDbDoesNotExist return } } needVersionFile := false verfile := dbpath + ".ver" fi, ferr := os.Open(verfile) if ferr == nil { defer fi.Close() ferr = binary.Read(fi, binary.LittleEndian, &dbversion) if ferr != nil { dbversion = ^0 } } else { if create == true { needVersionFile = true dbversion = CurrentDBVersion } } myCache := cache.NewEmptyCache() opts := &opt.Options{ BlockCache: myCache, MaxOpenFiles: 256, Compression: opt.NoCompression, } switch dbversion { case 0: opts = &opt.Options{} case 1: // uses defaults from above default: err = fmt.Errorf("unsupported db version %v", dbversion) return } tlDb, err = leveldb.OpenFile(dbpath, opts) if err != nil { return } // If we opened the database successfully on 'create' // update the if needVersionFile { fo, ferr := os.Create(verfile) if ferr != nil { // TODO(design) close and delete database? err = ferr return } defer fo.Close() err = binary.Write(fo, binary.LittleEndian, dbversion) if err != nil { return } } return }