Documentation
¶
Index ¶
- Constants
- Variables
- func Batch() func(*Options) error
- func BleveAsyncWrites() func(*Options) error
- func BleveBatchDelay(delay time.Duration) func(*Options) error
- func BleveBatchMaxBytes(max uint64) func(*Options) error
- func BleveBatchMaxDocs(max int) func(*Options) error
- func BleveBatchQueueSize(size int) func(*Options) error
- func BleveSyncWrites() func(*Options) error
- func BoltOptions(mode os.FileMode, options *bolt.Options) func(*Options) error
- func Codec(c codec.MarshalUnmarshaler) func(*Options) error
- func Debug() func(*Options) error
- func Limit(limit int) func(*index.Options)
- func Reverse() func(*index.Options)
- func Root(root ...string) func(*Options) error
- func Skip(offset int) func(*index.Options)
- func UseDB(b *bolt.DB) func(*Options) error
- type BucketScanner
- type ColumnInfo
- type DB
- func (s *DB) Close() error
- func (s *DB) FlushBleve(ctx context.Context) error
- func (s *DB) ListColumns(from, table string) ([]ColumnInfo, error)
- func (s *DB) ListFroms() ([]string, error)
- func (s *DB) ListTables(from string) ([]string, error)
- func (s *DB) SetTableMetadata(from, table string, columns []ColumnInfo) error
- type Finder
- type KeyValueStore
- type Node
- type Options
- type Query
- type SQL
- func (s *SQL) Count(query string, args ...any) (int, error)
- func (s *SQL) Exec(query string, args ...any) (SQLResult, error)
- func (s *SQL) Find(query string, to any, args ...any) error
- func (s *SQL) First(query string, to any, args ...any) error
- func (s *SQL) Project(query string, to any, args ...any) error
- func (s *SQL) Register(models ...any) error
- func (s *SQL) WithAllowFullTableWrite(allow bool) *SQL
- type SQLResult
- type Tx
- type TypeStore
Examples ¶
Constants ¶
const Version = "2.0.0"
Version of Storm
Variables ¶
var ( // ErrNoID is returned when no ID field or id tag is found in the struct. ErrNoID = errors.New("missing struct tag id or ID field") // ErrZeroID is returned when the ID field is a zero value. ErrZeroID = errors.New("id field must not be a zero value") // ErrBadType is returned when a method receives an unexpected value type. ErrBadType = errors.New("provided data must be a struct or a pointer to struct") // ErrAlreadyExists is returned uses when trying to set an existing value on a field that has a unique index. ErrAlreadyExists = errors.New("already exists") // ErrNilParam is returned when the specified param is expected to be not nil. ErrNilParam = errors.New("param must not be nil") // ErrUnknownTag is returned when an unexpected tag is specified. ErrUnknownTag = errors.New("unknown tag") // ErrIdxNotFound is returned when the specified index is not found. ErrIdxNotFound = errors.New("index not found") // ErrSlicePtrNeeded is returned when an unexpected value is given, instead of a pointer to slice. ErrSlicePtrNeeded = errors.New("provided target must be a pointer to slice") // ErrStructPtrNeeded is returned when an unexpected value is given, instead of a pointer to struct. ErrStructPtrNeeded = errors.New("provided target must be a pointer to struct") // ErrPtrNeeded is returned when an unexpected value is given, instead of a pointer. ErrPtrNeeded = errors.New("provided target must be a pointer to a valid variable") // ErrNoName is returned when the specified struct has no name. ErrNoName = errors.New("provided target must have a name") // ErrNotFound is returned when the specified record is not saved in the bucket. ErrNotFound = errors.New("not found") // ErrNotInTransaction is returned when trying to rollback or commit when not in transaction. ErrNotInTransaction = errors.New("not in transaction") // ErrIncompatibleValue is returned when trying to set a value with a different type than the chosen field ErrIncompatibleValue = errors.New("incompatible value") // ErrDifferentCodec is returned when using a codec different than the first codec used with the bucket. ErrDifferentCodec = errors.New("the selected codec is incompatible with this bucket") // ErrUnsupportedSQL is returned when the SQL layer receives syntax it does not execute. ErrUnsupportedSQL = errors.New("unsupported sql statement") // ErrSQLTableNotRegistered is returned when a SQL table has no registered model. ErrSQLTableNotRegistered = errors.New("sql table is not registered") // ErrSQLUnknownField is returned when a SQL column cannot be matched to a model field. ErrSQLUnknownField = errors.New("sql field is not registered") // ErrSQLBadProjectionTarget is returned when Project receives an unsupported destination. ErrSQLBadProjectionTarget = errors.New("sql projection target must be a pointer to slice") // ErrSQLArguments is returned when SQL placeholders do not match supplied args. ErrSQLArguments = errors.New("sql arguments mismatch") // ErrSQLUnsafeWrite is returned when UPDATE or DELETE would affect a whole table by default. ErrSQLUnsafeWrite = errors.New("sql update/delete without where is not allowed") )
Errors
Functions ¶
func BleveAsyncWrites ¶ added in v2.4.0
BleveAsyncWrites explicitly selects the default asynchronous index behavior: mutating APIs return after the Bolt transaction and durable outbox commit.
func BleveBatchDelay ¶ added in v2.4.0
BleveBatchDelay sets the positive group-commit window used to combine index mutations from concurrent writes after their Bolt transactions commit.
func BleveBatchMaxBytes ¶ added in v2.4.0
BleveBatchMaxBytes sets a positive limit for mapped document bytes in one Bleve batch.
func BleveBatchMaxDocs ¶ added in v2.4.0
BleveBatchMaxDocs sets a positive limit for document mutations in one Bleve batch.
func BleveBatchQueueSize ¶ added in v2.4.0
BleveBatchQueueSize sets a positive bound for committed write groups waiting for Bleve. Once full, new indexed writes apply backpressure after releasing Bolt's writer lock.
func BleveSyncWrites ¶ added in v2.4.0
BleveSyncWrites makes mutating APIs wait for their durable outbox entry to be applied to Bleve. It is intended for callers that require synchronous index visibility or immediate Bleve error reporting.
func BoltOptions ¶
BoltOptions used to pass options to BoltDB.
func Codec ¶
func Codec(c codec.MarshalUnmarshaler) func(*Options) error
Codec used to set a custom encoder and decoder. The default is Sonic-backed JSON.
func Limit ¶
Limit sets the maximum number of records to return
Example ¶
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"time"
storm "github.com/clakeboy/storm-rev/v2"
)
func main() {
dir, db := prepareDB()
defer os.RemoveAll(dir)
defer db.Close()
var users []User
err := db.All(&users, storm.Limit(2))
if err != nil {
log.Fatal(err)
}
fmt.Println("Found", len(users))
}
type User struct {
ID int `storm:"id,increment"`
Group string `storm:"index"`
Email string `storm:"unique"`
Name string
Age int `storm:"index"`
CreatedAt time.Time `storm:"index"`
}
type Account struct {
ID int `storm:"id,increment"`
Amount int64
}
func prepareDB() (string, *storm.DB) {
dir, _ := ioutil.TempDir(os.TempDir(), "storm")
db, _ := storm.Open(filepath.Join(dir, "storm.db"))
for i, name := range []string{"John", "Eric", "Dilbert"} {
email := strings.ToLower(name + "@provider.com")
user := User{
Group: "staff",
Email: email,
Name: name,
Age: 21 + i,
CreatedAt: time.Now(),
}
err := db.Save(&user)
if err != nil {
log.Fatal(err)
}
}
for i := int64(0); i < 10; i++ {
account := Account{Amount: 10000}
err := db.Save(&account)
if err != nil {
log.Fatal(err)
}
}
return dir, db
}
Output: Found 2
func Skip ¶
Skip sets the number of records to skip
Example ¶
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"time"
storm "github.com/clakeboy/storm-rev/v2"
)
func main() {
dir, db := prepareDB()
defer os.RemoveAll(dir)
defer db.Close()
var users []User
err := db.All(&users, storm.Skip(1))
if err != nil {
log.Fatal(err)
}
fmt.Println("Found", len(users))
}
type User struct {
ID int `storm:"id,increment"`
Group string `storm:"index"`
Email string `storm:"unique"`
Name string
Age int `storm:"index"`
CreatedAt time.Time `storm:"index"`
}
type Account struct {
ID int `storm:"id,increment"`
Amount int64
}
func prepareDB() (string, *storm.DB) {
dir, _ := ioutil.TempDir(os.TempDir(), "storm")
db, _ := storm.Open(filepath.Join(dir, "storm.db"))
for i, name := range []string{"John", "Eric", "Dilbert"} {
email := strings.ToLower(name + "@provider.com")
user := User{
Group: "staff",
Email: email,
Name: name,
Age: 21 + i,
CreatedAt: time.Now(),
}
err := db.Save(&user)
if err != nil {
log.Fatal(err)
}
}
for i := int64(0); i < 10; i++ {
account := Account{Amount: 10000}
err := db.Save(&account)
if err != nil {
log.Fatal(err)
}
}
return dir, db
}
Output: Found 2
func UseDB ¶
UseDB allows Storm to use an existing open Bolt.DB. Warning: storm.DB.Close() will close the bolt.DB instance.
Example ¶
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"time"
storm "github.com/clakeboy/storm-rev/v2"
bolt "go.etcd.io/bbolt"
)
func main() {
dir, _ := ioutil.TempDir(os.TempDir(), "storm")
defer os.RemoveAll(dir)
bDB, err := bolt.Open(filepath.Join(dir, "bolt.db"), 0600, &bolt.Options{Timeout: 10 * time.Second})
if err != nil {
log.Fatal(err)
}
db, _ := storm.Open("", storm.UseDB(bDB))
defer db.Close()
err = db.Save(&User{ID: 10})
if err != nil {
log.Fatal(err)
}
var user User
err = db.One("ID", 10, &user)
fmt.Println(err)
}
type User struct {
ID int `storm:"id,increment"`
Group string `storm:"index"`
Email string `storm:"unique"`
Name string
Age int `storm:"index"`
CreatedAt time.Time `storm:"index"`
}
Output: <nil>
Types ¶
type BucketScanner ¶
type BucketScanner interface {
// PrefixScan scans the root buckets for keys matching the given prefix.
PrefixScan(prefix string) []Node
// PrefixScan scans the buckets in this node for keys matching the given prefix.
RangeScan(min, max string) []Node
}
A BucketScanner scans a Node for a list of buckets
type ColumnInfo ¶
type ColumnInfo struct {
// Name is the Go struct field name.
Name string `json:"name"`
// JSON is the JSON field name used when the record is encoded.
JSON string `json:"json"`
// Type is the Go type name stored in the table schema.
Type string `json:"type"`
// Index is the Storm index tag value, such as index or unique.
Index string `json:"index,omitempty"`
// ID reports whether this column is the table ID column.
ID bool `json:"id,omitempty"`
// Increment reports whether Storm auto-increments this column.
Increment bool `json:"increment,omitempty"`
// IncrementStart is the configured starting value for an increment column.
IncrementStart int64 `json:"increment_start,omitempty"`
// Integer reports whether the column stores an integer type.
Integer bool `json:"integer,omitempty"`
// Composites records composite-index names and field order.
Composites map[string]int `json:"composites,omitempty"`
}
ColumnInfo describes one persisted column in a Storm table schema.
type DB ¶
type DB struct {
// The root node that points to the root bucket.
Node
// Bolt is still easily accessible
Bolt *bolt.DB
// contains filtered or unexported fields
}
DB is the wrapper around BoltDB. It contains an instance of BoltDB and uses it to perform all the needed operations
func (*DB) ListColumns ¶
func (s *DB) ListColumns(from, table string) ([]ColumnInfo, error)
ListColumns returns persisted column metadata for a table below the given From bucket.
func (*DB) ListTables ¶
ListTables returns direct table bucket names below the given From bucket.
func (*DB) SetTableMetadata ¶
func (s *DB) SetTableMetadata(from, table string, columns []ColumnInfo) error
SetTableMetadata replaces the persisted column metadata for an existing table.
The table bucket must already exist, but it does not need to have __storm_metadata/schema yet. External indexes are not rebuilt here; call ReIndex after changing indexed fields when the new metadata should take effect.
type Finder ¶
type Finder interface {
// One returns one record by the specified index
One(fieldName string, value any, to any) error
// Find returns one or more records by the specified index
Find(fieldName string, value any, to any, options ...func(q *index.Options)) error
// FindByIndex returns records by a named composite index and full equality values.
FindByIndex(indexName string, values []any, to any, options ...func(q *index.Options)) error
// Search returns records by a full-text indexed field.
Search(fieldName string, text string, to any, options ...func(q *index.Options)) error
// AllByIndex gets all the records of a bucket that are indexed in the specified index
AllByIndex(fieldName string, to any, options ...func(*index.Options)) error
// All gets all the records of a bucket.
// If there are no records it returns no error and the 'to' parameter is set to an empty slice.
All(to any, options ...func(*index.Options)) error
// Select a list of records that match a list of matchers. Doesn't use indexes.
Select(matchers ...q.Matcher) Query
// Range returns one or more records by the specified index within the specified range
Range(fieldName string, min, max, to any, options ...func(*index.Options)) error
// Prefix returns one or more records whose given field starts with the specified prefix.
Prefix(fieldName string, prefix string, to any, options ...func(*index.Options)) error
// Count counts all the records of a bucket
Count(data any) (int, error)
}
A Finder can fetch types from BoltDB.
type KeyValueStore ¶
type KeyValueStore interface {
// Get a value from a bucket
Get(bucketName string, key any, to any) error
// Set a key/value pair into a bucket
Set(bucketName string, key any, value any) error
// Delete deletes a key from a bucket
Delete(bucketName string, key any) error
// GetBytes gets a raw value from a bucket.
GetBytes(bucketName string, key any) ([]byte, error)
// SetBytes sets a raw value into a bucket.
SetBytes(bucketName string, key any, value []byte) error
// KeyExists reports the presence of a key in a bucket.
KeyExists(bucketName string, key any) (bool, error)
}
KeyValueStore can store and fetch values by key
type Node ¶
type Node interface {
Tx
TypeStore
KeyValueStore
BucketScanner
// From returns a new Storm node with a new bucket root below the current.
// All DB operations on the new node will be executed relative to this bucket.
From(addend ...string) Node
// Bucket returns the bucket name as a slice from the root.
// In the normal, simple case this will be empty.
Bucket() []string
// GetBucket returns the given bucket below the current node.
GetBucket(tx *bolt.Tx, children ...string) *bolt.Bucket
// CreateBucketIfNotExists creates the bucket below the current node if it doesn't
// already exist.
CreateBucketIfNotExists(tx *bolt.Tx, bucket string) (*bolt.Bucket, error)
// WithTransaction returns a New Storm node that will use the given transaction.
WithTransaction(tx *bolt.Tx) Node
// Begin starts a new transaction.
Begin(writable bool) (Node, error)
// Codec used by this instance of Storm
Codec() codec.MarshalUnmarshaler
// WithCodec returns a New Storm Node that will use the given Codec.
WithCodec(codec codec.MarshalUnmarshaler) Node
// WithBatch returns a new Storm Node with the batch mode enabled.
WithBatch(enabled bool) Node
// SQL returns a SQL interpreter bound to this node and the provided models.
SQL(models ...any) (*SQL, error)
}
A Node in Storm represents the API to a BoltDB bucket.
type Options ¶
type Options struct {
// contains filtered or unexported fields
}
Options are used to customize the way Storm opens a database.
type Query ¶
type Query interface {
// Skip matching records by the given number
Skip(int) Query
// Limit the results by the given number
Limit(int) Query
// Order by the given fields, in descending precedence, left-to-right.
OrderBy(...string) Query
// Reverse the order of the results
Reverse() Query
// Bucket specifies the bucket name
Bucket(string) Query
// Find a list of matching records
Find(any) error
// First gets the first matching record
First(any) error
// Delete all matching records
Delete(any) error
// Count all the matching records
Count(any) (int, error)
// Returns all the records without decoding them
Raw() ([][]byte, error)
// Execute the given function for each raw element
RawEach(func([]byte, []byte) error) error
// Execute the given function for each element
Each(any, func(any) error) error
}
Query is the low level query engine used by Storm. It allows to operate searches through an entire bucket.
type SQL ¶
type SQL struct {
// contains filtered or unexported fields
}
SQL interprets a small single-table SQL subset on top of Storm's typed APIs.
func (*SQL) First ¶
First executes a SELECT * query and decodes the first full model record into to.
func (*SQL) Project ¶
Project executes a SELECT query and fills either []map[string]any or a DTO slice.
func (*SQL) WithAllowFullTableWrite ¶
WithAllowFullTableWrite returns a copy that allows UPDATE/DELETE without WHERE.
type Tx ¶
type Tx interface {
// Commit writes all changes to disk.
Commit() error
// Rollback closes the transaction and ignores all previous updates.
Rollback() error
}
Tx is a transaction.
type TypeStore ¶
type TypeStore interface {
Finder
// Init creates the indexes and buckets for a given structure
Init(data any) error
// ReIndex rebuilds all the indexes of a bucket
ReIndex(data any) error
// Save a structure
Save(data any) error
// SaveAll saves a slice of structures in one write transaction.
SaveAll(data any) error
// Update a structure
Update(data any) error
// UpdateField updates a single field
UpdateField(data any, fieldName string, value any) error
// Drop a bucket
Drop(data any) error
// DeleteStruct deletes a structure from the associated bucket
DeleteStruct(data any) error
}
TypeStore stores user defined types in BoltDB.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package codec contains sub-packages with different codecs that can be used to encode and decode entities in Storm.
|
Package codec contains sub-packages with different codecs that can be used to encode and decode entities in Storm. |
|
gob
Package gob contains a codec to encode and decode entities in Gob format
|
Package gob contains a codec to encode and decode entities in Gob format |
|
json
Package json contains a codec to encode and decode entities in JSON format
|
Package json contains a codec to encode and decode entities in JSON format |
|
msgpack
Package msgpack contains a codec to encode and decode entities in msgpack format
|
Package msgpack contains a codec to encode and decode entities in msgpack format |
|
protobuf
Package protobuf contains a codec to encode and decode entities in Protocol Buffer
|
Package protobuf contains a codec to encode and decode entities in Protocol Buffer |
|
sereal
Package sereal contains a codec to encode and decode entities using Sereal
|
Package sereal contains a codec to encode and decode entities using Sereal |
|
Package index contains Index engines used to store values and their corresponding IDs
|
Package index contains Index engines used to store values and their corresponding IDs |
|
Package q contains a list of Matchers used to compare struct fields with values
|
Package q contains a list of Matchers used to compare struct fields with values |