1
0
mirror of https://github.com/schollz/cowyo.git synced 2023-08-10 21:13:00 +03:00
cowyo/db.go
Travis Scholl 322446ba18 used flag for command line arguments
Former-commit-id: 2ac565e4d78c22ffafc25532ef0771d4c8fa6da6 [formerly 2b65957a84d49a578c09e005d4100b269b6dc8e5] [formerly 115c739d59b0f5ff34de0f51588e973e94e77689 [formerly f0fbd2c30f]]
Former-commit-id: f28ba24ecfad414f37d054b6099aeb8480776914 [formerly d4e575940c207425c74141f5a78c43f5323d437c]
Former-commit-id: bc1dc9204608c1a4cca74639c46a6edbad8d37c6
2016-02-07 10:15:42 -08:00

102 lines
1.7 KiB
Go

package main
import (
"encoding/json"
"fmt"
"log"
"time"
"github.com/boltdb/bolt"
)
var db *bolt.DB
var open bool
// Open to create the database and open
func Open(filename string) error {
var err error
config := &bolt.Options{Timeout: 30 * time.Second}
db, err = bolt.Open(filename, 0600, config)
if err != nil {
fmt.Println("Opening BoltDB timed out")
log.Fatal(err)
}
open = true
return nil
}
// Close database
func Close() {
open = false
db.Close()
}
// Data for storing in DB
type CowyoData struct {
Title string
Text string
}
func (p *CowyoData) load() error {
if !open {
return fmt.Errorf("db must be opened before saving!")
}
err := db.View(func(tx *bolt.Tx) error {
var err error
b := tx.Bucket([]byte("datas"))
if b == nil {
return nil
}
k := []byte(p.Title)
val := b.Get(k)
if val == nil {
return nil
}
err = p.decode(val)
if err != nil {
return err
}
return nil
})
if err != nil {
fmt.Printf("Could not get CowyoData: %s", err)
return err
}
return nil
}
func (p *CowyoData) save() error {
if !open {
return fmt.Errorf("db must be opened before saving")
}
err := db.Update(func(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists([]byte("datas"))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
enc, err := p.encode()
if err != nil {
return fmt.Errorf("could not encode CowyoData: %s", err)
}
err = bucket.Put([]byte(p.Title), enc)
return err
})
return err
}
func (p *CowyoData) encode() ([]byte, error) {
enc, err := json.Marshal(p)
if err != nil {
return nil, err
}
return enc, nil
}
func (p *CowyoData) decode(data []byte) error {
err := json.Unmarshal(data, &p)
if err != nil {
return err
}
return nil
}