Smartbolt
Smartbold is a minimalistic boltdb wrapper with generics support.
Features
- Generics support
- Simple API
- Queries for fetching data
Getting started
go get github.com/nyan2d/smartbolt
Import Smartbolt
import "github.com/nyan2d/smartbolt"
Usage
Declarate your data models
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
Smartbolt uses json tags for field names declaration
Opening a database
db, err := smartbolt.Open("database.db")
Also you can use the MustOpen function.
Don't forget to close the database after usage.
db := smartbolt.MustOpen("database.db")
defer db.Close()
Using buckets
bucket := smartbolt.OpenBucket[int, User](db, "users")
Warning! If the bucket does not exists, you'll get a panic. So you can initialize the bucket using Init() function.
Writing Key/Values
u := User{
ID: 0,
Name: "Nyan",
Email: "noreply@nyan.com",
}
bucket.Put(u.ID, u)
Bath writing
users := map[int]User{
firstUser.ID: firstUser,
secondUser.ID: secondUser,
}
bucket.PutBulk(users)
Getting an entry
result, err := bucket.Get(key)
Getting all entries
entries, err := bucket.GetAll() // it will return an array with all entries
Deleting an entry
err := bucket.Delete(key)
Autoincrementing ID for the current bucket
id, err := bucket.NextID()
Queries
Make a query
q, err := query.Make[User](db, "users")
Simple syntax
q := query.Make[User](db, "users")
Filter
filtered := q.Filter(func (item User) bool {
return item.Name == "Nyan"
})
Limit
limited := q.Limit(10)
Skip
skipped := q.Skip(10)
Reverse
reversed := q.Reverse()
Sort
sorted := q.Sort(func(a, b User) bool {
return strings.Compare(a.Name, b.Name) > 0
})
Getting results
// Creates an array from a query
q.Collect()
// Returns the number of elements in a query
q.Count()
// Determines whether a query contains any elements
q.Any()
// Returns the first element of a query, or default value if the query contains no elements
q.FirstOrDefault()
// Returns the last element of a query, or default value if the query contains no elements
q.LastOrDefault()
// Returns the last element of a query
q.First()
// Returns the last element of a query
q.Last()
etc
Queries can be chained.
result := query.Make[User](db, "users").
Filter(func(item T) bool{
return strings.HasPrefix("Nyan")
}).
OrderBy(func (a, b User) bool {
return strings.Compare(a.Name, b.Name) > 0
}).
Limit(10).
Collect()