Skip to content

Commit

Permalink
connection func and example
Browse files Browse the repository at this point in the history
  • Loading branch information
mattkasun committed Dec 22, 2023
1 parent e212212 commit f700b3d
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
6 changes: 6 additions & 0 deletions database.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
var (
ErrNoResults = errors.New("no results found") // ErrNoResults indicates query found no results
ErrInvalidTableName = errors.New("invalid table") // ErrInvalidTableName indicates that specified table does not exist
ErrNoConnection = errors.New("no db connection") //
db *bbolt.DB
)

Expand All @@ -30,6 +31,11 @@ func Close() error {
return db.Close()
}

// Connection returns the connection to the store for more advanced queries by caller
func Connection() *bbolt.DB {
return db
}

func createTables(tables []string) error {
var errs error
for _, table := range tables {
Expand Down
54 changes: 54 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package boltdb_test

import (
"encoding/json"
"fmt"

"github.com/devilcove/boltdb"
"go.etcd.io/bbolt"
)

const UserTable = "users"

type User struct {
UserName string
Password string
IsAdmin bool
}

func ExampleConnection() {
if AdminExists() {
fmt.Println("admin exists")
} else {
fmt.Println("admin does not exist")
}
// Output: admin does not exist
}

func AdminExists() bool {
var user User
var found bool
db := boltdb.Connection()
if db == nil {
return found
}
if err := db.View(func(tx *bbolt.Tx) error {
b := tx.Bucket([]byte(UserTable))
if b == nil {
return boltdb.ErrNoResults
}
_ = b.ForEach(func(k, v []byte) error {
if err := json.Unmarshal(v, &user); err != nil {
return err
}
if user.IsAdmin {
found = true
}
return nil
})
return nil
}); err != nil {
return false
}
return found
}

0 comments on commit f700b3d

Please sign in to comment.