Documentation ¶
Overview ¶
Package zoom is a blazing-fast datastore and querying engine for Go built on Redis. It supports models of any arbitrary struct type and provides basic querying functionality. It also supports atomic transactions, lua scripts, and running Redis commands directly if needed.
Version 0.18.0 ¶
For installation instructions, examples, and more information visit https://github.com/albrow/zoom.
Index ¶
- Variables
- func Interfaces(in interface{}) []interface{}
- type Action
- type Collection
- func (c *Collection) Count() (int, error)
- func (c *Collection) Delete(id string) (bool, error)
- func (c *Collection) DeleteAll() (int, error)
- func (c *Collection) Exists(id string) (bool, error)
- func (c *Collection) FieldIndexKey(fieldName string) (string, error)
- func (c *Collection) FieldNames() []string
- func (c *Collection) FieldRedisNames() []string
- func (c *Collection) Find(id string, model Model) error
- func (c *Collection) FindAll(models interface{}) error
- func (c *Collection) FindFields(id string, fieldNames []string, model Model) error
- func (c *Collection) IndexKey() string
- func (c *Collection) ModelKey(id string) string
- func (c *Collection) Name() string
- func (collection *Collection) NewQuery() *Query
- func (c *Collection) Save(model Model) error
- func (c *Collection) SaveFields(fieldNames []string, model Model) error
- type CollectionOptions
- type MarshalerUnmarshaler
- type Model
- type ModelNotFoundError
- type Pool
- type PoolOptions
- func (options PoolOptions) WithAddress(address string) PoolOptions
- func (options PoolOptions) WithDatabase(database int) PoolOptions
- func (options PoolOptions) WithIdleTimeout(timeout time.Duration) PoolOptions
- func (options PoolOptions) WithMaxActive(maxActive int) PoolOptions
- func (options PoolOptions) WithMaxIdle(maxIdle int) PoolOptions
- func (options PoolOptions) WithNetwork(network string) PoolOptions
- func (options PoolOptions) WithPassword(password string) PoolOptions
- func (options PoolOptions) WithWait(wait bool) PoolOptions
- type Query
- func (q *Query) Count() (int, error)
- func (q *Query) Exclude(fields ...string) *Query
- func (q *Query) Filter(filterString string, value interface{}) *Query
- func (q *Query) IDs() ([]string, error)
- func (q *Query) Include(fields ...string) *Query
- func (q *Query) Limit(amount uint) *Query
- func (q *Query) Offset(amount uint) *Query
- func (q *Query) Order(fieldName string) *Query
- func (q *Query) Run(models interface{}) error
- func (q *Query) RunOne(model Model) error
- func (q *Query) StoreIDs(destKey string) error
- func (q Query) String() string
- type RandomID
- type ReplyHandler
- func NewScanBoolHandler(b *bool) ReplyHandler
- func NewScanFloat64Handler(f *float64) ReplyHandler
- func NewScanIntHandler(i *int) ReplyHandler
- func NewScanModelHandler(fieldNames []string, model Model) ReplyHandler
- func NewScanModelsHandler(collection *Collection, fieldNames []string, models interface{}) ReplyHandler
- func NewScanStringHandler(s *string) ReplyHandler
- func NewScanStringsHandler(strings *[]string) ReplyHandler
- type Transaction
- func (t *Transaction) Command(name string, args redis.Args, handler ReplyHandler)
- func (t *Transaction) Count(c *Collection, count *int)
- func (t *Transaction) Delete(c *Collection, id string, deleted *bool)
- func (t *Transaction) DeleteAll(c *Collection, count *int)
- func (t *Transaction) DeleteModelsBySetIDs(setKey string, collectionName string, handler ReplyHandler)
- func (t *Transaction) Exec() error
- func (t *Transaction) Exists(c *Collection, id string, exists *bool)
- func (t *Transaction) ExtractIDsFromFieldIndex(setKey string, destKey string, min interface{}, max interface{})
- func (t *Transaction) ExtractIDsFromStringIndex(setKey, destKey, min, max string)
- func (t *Transaction) Find(c *Collection, id string, model Model)
- func (t *Transaction) FindAll(c *Collection, models interface{})
- func (t *Transaction) FindFields(c *Collection, id string, fieldNames []string, model Model)
- func (tx *Transaction) Query(collection *Collection) *TransactionQuery
- func (t *Transaction) Save(c *Collection, model Model)
- func (t *Transaction) SaveFields(c *Collection, fieldNames []string, model Model)
- func (t *Transaction) Script(script *redis.Script, args redis.Args, handler ReplyHandler)
- func (t *Transaction) Watch(model Model) error
- func (t *Transaction) WatchKey(key string) error
- type TransactionQuery
- func (q *TransactionQuery) Count(count *int)
- func (q *TransactionQuery) Exclude(fields ...string) *TransactionQuery
- func (q *TransactionQuery) Filter(filterString string, value interface{}) *TransactionQuery
- func (q *TransactionQuery) IDs(ids *[]string)
- func (q *TransactionQuery) Include(fields ...string) *TransactionQuery
- func (q *TransactionQuery) Limit(amount uint) *TransactionQuery
- func (q *TransactionQuery) Offset(amount uint) *TransactionQuery
- func (q *TransactionQuery) Order(fieldName string) *TransactionQuery
- func (q *TransactionQuery) Run(models interface{})
- func (q *TransactionQuery) RunOne(model Model)
- func (q *TransactionQuery) StoreIDs(destKey string)
- func (q TransactionQuery) String() string
- type WatchError
Constants ¶
This section is empty.
Variables ¶
var DefaultCollectionOptions = CollectionOptions{ FallbackMarshalerUnmarshaler: GobMarshalerUnmarshaler, Index: false, Name: "", }
DefaultCollectionOptions is the default set of options for a collection.
var DefaultPoolOptions = PoolOptions{ Address: "localhost:6379", Database: 0, IdleTimeout: 240 * time.Second, MaxActive: 1000, MaxIdle: 1000, Network: "tcp", Password: "", Wait: true, }
DefaultPoolOptions is the default set of options for a Pool.
Functions ¶
func Interfaces ¶ added in v0.4.0
func Interfaces(in interface{}) []interface{}
Interfaces converts in to []interface{}. It will panic if the underlying type of in is not a slice.
Types ¶
type Action ¶ added in v0.9.0
type Action struct {
// contains filtered or unexported fields
}
Action is a single step in a transaction and must be either a command or a script with optional arguments and a reply handler.
type Collection ¶ added in v0.11.0
type Collection struct {
// contains filtered or unexported fields
}
Collection represents a specific registered type of model. It has methods for saving, finding, and deleting models of a specific type. Use the NewCollection method to create a new collection.
func (*Collection) Count ¶ added in v0.11.0
func (c *Collection) Count() (int, error)
Count returns the number of models of the given type that exist in the database. It returns an error if there was a problem connecting to the database.
func (*Collection) Delete ¶ added in v0.11.0
func (c *Collection) Delete(id string) (bool, error)
Delete removes the model with the given type and id from the database. It will not return an error if the model corresponding to the given id was not found in the database. Instead, it will return a boolean representing whether or not the model was found and deleted, and will only return an error if there was a problem connecting to the database.
func (*Collection) DeleteAll ¶ added in v0.11.0
func (c *Collection) DeleteAll() (int, error)
DeleteAll deletes all the models of the given type in a single transaction. See http://redis.io/topics/transactions. It returns the number of models deleted and an error if there was a problem connecting to the database.
func (*Collection) Exists ¶ added in v0.18.0
func (c *Collection) Exists(id string) (bool, error)
Exists returns true if the collection has a model with the given id. It returns an error if there was a problem connecting to the database.
func (*Collection) FieldIndexKey ¶ added in v0.11.0
func (c *Collection) FieldIndexKey(fieldName string) (string, error)
FieldIndexKey returns the key for the sorted set used to index the field identified by fieldName. It returns an error if fieldName does not identify a field in the spec or if the field it identifies is not an indexed field.
func (*Collection) FieldNames ¶ added in v0.16.0
func (c *Collection) FieldNames() []string
FieldNames returns all the field names for the Collection. The order is always the same and is used internally by Zoom to determine the order of fields in Redis commands such as HMGET.
func (*Collection) FieldRedisNames ¶ added in v0.16.0
func (c *Collection) FieldRedisNames() []string
FieldRedisNames returns all the Redis names for the fields of the Collection. For example, if a Collection was created with a model type that includes custom field names via the `redis` struct tag, those names will be returned. The order is always the same and is used internally by Zoom to determine the order of fields in Redis commands such as HMGET.
func (*Collection) Find ¶ added in v0.11.0
func (c *Collection) Find(id string, model Model) error
Find retrieves a model with the given id from redis and scans its values into model. model should be a pointer to a struct of a registered type corresponding to the Collection. Find will mutate the struct, filling in its fields and overwriting any previous values. It returns an error if a model with the given id does not exist, if the given model was the wrong type, or if there was a problem connecting to the database.
func (*Collection) FindAll ¶ added in v0.11.0
func (c *Collection) FindAll(models interface{}) error
FindAll finds all the models of the given type. It executes the commands needed to retrieve the models in a single transaction. See http://redis.io/topics/transactions. models must be a pointer to a slice of models with a type corresponding to the Collection. FindAll will grow or shrink the models slice as needed and if any of the models in the models slice are nil, FindAll will use reflection to allocate memory for them. FindAll returns an error if models is the wrong type or if there was a problem connecting to the database.
func (*Collection) FindFields ¶ added in v0.13.0
func (c *Collection) FindFields(id string, fieldNames []string, model Model) error
FindFields is like Find but finds and sets only the specified fields. Any fields of the model which are not in the given fieldNames are not mutated. FindFields will return an error if any of the given fieldNames are not found in the model type.
func (*Collection) IndexKey ¶ added in v0.11.0
func (c *Collection) IndexKey() string
IndexKey returns the key that identifies a set in the database that stores all the ids for models in the given collection.
func (*Collection) ModelKey ¶ added in v0.11.0
func (c *Collection) ModelKey(id string) string
ModelKey returns the key that identifies a hash in the database which contains all the fields of the model corresponding to the given id. If id is an empty string, it will return an empty string.
func (*Collection) Name ¶ added in v0.11.0
func (c *Collection) Name() string
Name returns the name for the given collection. The name is a unique string identifier to use for the collection in redis. All models in this collection that are saved in the database will use the collection name as a prefix.
func (*Collection) NewQuery ¶ added in v0.11.0
func (collection *Collection) NewQuery() *Query
NewQuery is used to construct a query. The query returned can be chained together with one or more query modifiers (e.g. Filter or Order), and then executed using the Run, RunOne, Count, or IDs methods. If no query modifiers are used, running the query will return all models of the given type in unspecified order. Queries use delayed execution, so nothing touches the database until you execute them.
func (*Collection) Save ¶ added in v0.11.0
func (c *Collection) Save(model Model) error
Save writes a model (a struct which satisfies the Model interface) to the redis database. Save returns an error if the type of model does not match the registered Collection. To make a struct satisfy the Model interface, you can embed zoom.RandomID, which will generate pseudo-random ids for each model.
func (*Collection) SaveFields ¶ added in v0.17.0
func (c *Collection) SaveFields(fieldNames []string, model Model) error
SaveFields saves only the given fields of the model. SaveFields uses "last write wins" semantics. If another caller updates the the same fields concurrently, your updates may be overwritten. It will return an error if the type of model does not match the registered Collection, or if any of the given fieldNames are not found in the registered Collection. If SaveFields is called on a model that has not yet been saved, it will not return an error. Instead, only the given fields will be saved in the database.
type CollectionOptions ¶ added in v0.11.0
type CollectionOptions struct { // FallbackMarshalerUnmarshaler is used to marshal/unmarshal any type into a // slice of bytes which is suitable for storing in the database. If Zoom does // not know how to directly encode a certain type into bytes, it will use the // FallbackMarshalerUnmarshaler. Zoom provides GobMarshalerUnmarshaler and // JSONMarshalerUnmarshaler out of the box. You are also free to write your // own implementation. FallbackMarshalerUnmarshaler MarshalerUnmarshaler // If Index is true, any model in the collection that is saved will be added // to a set in Redis which acts as an index on all models in the collection. // The key for the set is exposed via the IndexKey method. Queries and the // FindAll, Count, and DeleteAll methods will not work for unindexed // collections. This may change in future versions. Index bool // Name is a unique string identifier to use for the collection in Redis. All // models in this collection that are saved in the database will use the // collection name as a prefix. If Name is an empty string, Zoom will use the // name of the concrete model type, excluding package prefix and pointer // declarations, as the name for the collection. So for example, the default // name corresponding to *models.User would be "User". If a custom name is // provided, it cannot contain a colon. Name string }
CollectionOptions contains various options for a pool.
func (CollectionOptions) WithFallbackMarshalerUnmarshaler ¶ added in v0.17.0
func (options CollectionOptions) WithFallbackMarshalerUnmarshaler(fallback MarshalerUnmarshaler) CollectionOptions
WithFallbackMarshalerUnmarshaler returns a new copy of the options with the FallbackMarshalerUnmarshaler property set to the given value. It does not mutate the original options.
func (CollectionOptions) WithIndex ¶ added in v0.17.0
func (options CollectionOptions) WithIndex(index bool) CollectionOptions
WithIndex returns a new copy of the options with the Index property set to the given value. It does not mutate the original options.
func (CollectionOptions) WithName ¶ added in v0.17.0
func (options CollectionOptions) WithName(name string) CollectionOptions
WithName returns a new copy of the options with the Name property set to the given value. It does not mutate the original options.
type MarshalerUnmarshaler ¶ added in v0.4.0
type MarshalerUnmarshaler interface { // Marshal returns a byte-encoded representation of v Marshal(v interface{}) ([]byte, error) // Unmarshal parses byte-encoded data and store the result in the value // pointed to by v. Unmarshal(data []byte, v interface{}) error }
MarshalerUnmarshaler defines a handler for marshaling arbitrary data structures into a byte format and unmarshaling bytes into arbitrary data structures. Any struct which correctly implements the interface should have the property that what you put in using Marshal is identical to what you get out using Unmarshal.
var ( // GobMarshalerUnmarshaler is an object that implements MarshalerUnmarshaler // and uses uses the builtin gob package. Note that not all types are // supported by the gob package. See https://golang.org/pkg/encoding/gob/ GobMarshalerUnmarshaler MarshalerUnmarshaler = gobMarshalerUnmarshaler{} // JSONMarshalerUnmarshaler is an object that implements MarshalerUnmarshaler // and uses the builtin json package. Note that not all types are supported // by the json package. See https://golang.org/pkg/encoding/json/#Marshal JSONMarshalerUnmarshaler MarshalerUnmarshaler = jsonMarshalerUnmarshaler{} )
type Model ¶
Model is an interface encapsulating anything that can be saved and retrieved by Zoom. The only requirement is that a Model must have a getter and a setter for a unique id property.
type ModelNotFoundError ¶ added in v0.6.0
type ModelNotFoundError struct { Collection *Collection Msg string }
ModelNotFoundError is returned from Find and Query methods if a model that fits the given criteria is not found.
func (ModelNotFoundError) Error ¶ added in v0.6.0
func (e ModelNotFoundError) Error() string
type Pool ¶ added in v0.10.0
type Pool struct {
// contains filtered or unexported fields
}
Pool represents a pool of connections. Each pool connects to one database and manages its own set of registered models.
func NewPool ¶ added in v0.10.0
NewPool creates and returns a new pool using the given address to connect to Redis. All the other options will be set to their default values, which can be found in DefaultPoolOptions.
func NewPoolWithOptions ¶ added in v0.17.0
func NewPoolWithOptions(options PoolOptions) *Pool
NewPoolWithOptions initializes and returns a pool with the given options. You can pass in DefaultOptions to use all the default options. Or cal the WithX methods of DefaultOptions to change the options you want to change.
func (*Pool) Close ¶ added in v0.10.0
Close closes the pool. It should be run whenever the pool is no longer needed. It is often used in conjunction with defer.
func (*Pool) NewCollection ¶ added in v0.11.0
func (p *Pool) NewCollection(model Model) (*Collection, error)
NewCollection registers and returns a new collection of the given model type. You must create a collection for each model type you want to save. The type of model must be unique, i.e., not already registered, and must be a pointer to a struct. NewCollection will use all the default options for the collection, which are specified in DefaultCollectionOptions. If you want to specify different options, use the NewCollectionWithOptions method.
func (*Pool) NewCollectionWithOptions ¶ added in v0.17.0
func (p *Pool) NewCollectionWithOptions(model Model, options CollectionOptions) (*Collection, error)
NewCollectionWithOptions registers and returns a new collection of the given model type and with the provided options.
func (*Pool) NewConn ¶ added in v0.10.0
NewConn gets a connection from the pool and returns it. It can be used for directly interacting with the database. See http://godoc.org/github.com/garyburd/redigo/redis for full documentation on the redis.Conn type. You must call Close on any connections after you are done using them. Failure to call Close can cause a resource leak.
func (*Pool) NewTransaction ¶ added in v0.10.0
func (p *Pool) NewTransaction() *Transaction
NewTransaction instantiates and returns a new transaction.
type PoolOptions ¶ added in v0.11.0
type PoolOptions struct { // Address to use when connecting to Redis. Address string // Database id to use (using SELECT). Database int // IdleTimeout is the amount of time to wait before timing out (closing) idle // connections. IdleTimeout time.Duration // MaxActive is the maximum number of active connections the pool will keep. // A value of 0 means unlimited. MaxActive int // MaxIdle is the maximum number of idle connections the pool will keep. A // value of 0 means unlimited. MaxIdle int // Network to use. Network string // Password for a password-protected redis database. If not empty, // every connection will use the AUTH command during initialization // to authenticate with the database. Password string // Wait indicates whether or not the pool should wait for a free connection // if the MaxActive limit has been reached. If Wait is false and the // MaxActive limit is reached, Zoom will return an error indicating that the // pool is exhausted. Wait bool }
PoolOptions contains various options for a pool.
func (PoolOptions) WithAddress ¶ added in v0.17.0
func (options PoolOptions) WithAddress(address string) PoolOptions
WithAddress returns a new copy of the options with the Address property set to the given value. It does not mutate the original options.
func (PoolOptions) WithDatabase ¶ added in v0.17.0
func (options PoolOptions) WithDatabase(database int) PoolOptions
WithDatabase returns a new copy of the options with the Database property set to the given value. It does not mutate the original options.
func (PoolOptions) WithIdleTimeout ¶ added in v0.17.0
func (options PoolOptions) WithIdleTimeout(timeout time.Duration) PoolOptions
WithIdleTimeout returns a new copy of the options with the IdleTimeout property set to the given value. It does not mutate the original options.
func (PoolOptions) WithMaxActive ¶ added in v0.17.0
func (options PoolOptions) WithMaxActive(maxActive int) PoolOptions
WithMaxActive returns a new copy of the options with the MaxActive property set to the given value. It does not mutate the original options.
func (PoolOptions) WithMaxIdle ¶ added in v0.17.0
func (options PoolOptions) WithMaxIdle(maxIdle int) PoolOptions
WithMaxIdle returns a new copy of the options with the MaxIdle property set to the given value. It does not mutate the original options.
func (PoolOptions) WithNetwork ¶ added in v0.17.0
func (options PoolOptions) WithNetwork(network string) PoolOptions
WithNetwork returns a new copy of the options with the Network property set to the given value. It does not mutate the original options.
func (PoolOptions) WithPassword ¶ added in v0.17.0
func (options PoolOptions) WithPassword(password string) PoolOptions
WithPassword returns a new copy of the options with the Password property set to the given value. It does not mutate the original options.
func (PoolOptions) WithWait ¶ added in v0.17.0
func (options PoolOptions) WithWait(wait bool) PoolOptions
WithWait returns a new copy of the options with the Wait property set to the given value. It does not mutate the original options.
type Query ¶ added in v0.3.0
type Query struct {
// contains filtered or unexported fields
}
Query represents a query which will retrieve some models from the database. A Query may consist of one or more query modifiers (e.g. Filter or Order) and may be executed with a query finisher (e.g. Run or IDs).
func (*Query) Count ¶ added in v0.4.0
Count counts the number of models that would be returned by the query without actually retrieving the models themselves. Count will also return the first error that occurred during the lifetime of the query (if any).
func (*Query) Exclude ¶ added in v0.4.0
Exclude specifies one or more field names which will *not* be read from the database and scanned. Any other fields *will* be read and scanned into the resulting models when the query is run. You can only use one of Include or Exclude, not both on the same query. Exclude will set an error if you try to use it with Include on the same query. The error, same as any other error that occurs during the lifetime of the query, is not returned until the query is executed.
func (*Query) Filter ¶ added in v0.4.0
Filter applies a filter to the query, which will cause the query to only return models with field values matching the expression. filterString should be an expression which includes a fieldName, a space, and an operator in that order. For example: Filter("Age >=", 30) would only return models which have an Age value greater than or equal to 30. Operators must be one of "=", "!=", ">", "<", ">=", or "<=". You can only use Filter on fields which are indexed, i.e. those which have the `zoom:"index"` struct tag. If multiple filters are applied to the same query, the query will only return models which have matches for *all* of the filters. Filter will set an error on the query if the arguments are improperly formated, if the field you are attempting to filter is not indexed, or if the type of value does not match the type of the field. The error, same as any other error that occurs during the lifetime of the query, is not returned until the query is executed.
func (*Query) IDs ¶ added in v0.19.0
IDs returns only the ids of the models without actually retrieving the models themselves. IDs will return the first error that occurred during the lifetime of the query (if any).
func (*Query) Include ¶ added in v0.4.0
Include specifies one or more field names which will be read from the database and scanned into the resulting models when the query is run. Field names which are not specified in Include will not be read or scanned. You can only use one of Include or Exclude, not both on the same query. Include will set an error if you try to use it with Exclude on the same query. The error, same as any other error that occurs during the lifetime of the query, is not returned until the query is executed.
func (*Query) Limit ¶ added in v0.4.0
Limit specifies an upper limit on the number of models to return. If amount is 0, no limit will be applied and any number of models may be returned. The default value is 0.
func (*Query) Offset ¶ added in v0.4.0
Offset specifies a starting index (inclusive) from which to start counting models that will be returned. For example, if offset is 10, the first 10 models that the query would otherwise return will be skipped. The default value is 0.
func (*Query) Order ¶ added in v0.4.0
Order specifies a field by which to sort the models. fieldName should be a field in the struct type corresponding to the Collection used in the query constructor. By default, the records are sorted by ascending order by the given field. To sort by descending order, put a negative sign before the field name. Zoom can only sort by fields which have been indexed, i.e. those which have the `zoom:"index"` struct tag. Only one order may be specified per Order will set an error on the query if the fieldName is invalid, if another order has already been applied to the query, or if the fieldName specified does not correspond to an indexed field. The error, same as any other error that occurs during the lifetime of the query, is not returned until the query is executed.
func (*Query) Run ¶ added in v0.3.0
Run executes the query and scans the results into models. The type of models should be a pointer to a slice of Models. If no models fit the criteria, Run will set the length of models to 0 but will *not* return an error. Run will return the first error that occurred during the lifetime of the query (if any), or if models is the wrong type.
func (*Query) RunOne ¶ added in v0.6.0
RunOne is exactly like Run but finds only the first model that fits the query criteria and scans the values into model. If no model fits the criteria, RunOne *will* return a ModelNotFoundError.
func (*Query) StoreIDs ¶ added in v0.19.0
StoreIDs executes the query and stores the model ids matching the query criteria in a list identified by destKey. The list will be completely overwritten, and the model ids stored there will be in the correct order if the query includes an Order modifier. StoreIDs will return the first error that occurred during the lifetime of the query (if any).
type RandomID ¶ added in v0.19.0
type RandomID struct {
ID string
}
RandomID can be embedded in any model struct in order to satisfy the Model interface. The first time the ModelID method is called on an embedded RandomID, it will generate a pseudo-random id which is highly likely to be unique.
func (*RandomID) ModelID ¶ added in v0.19.0
ModelID returns the id of the model, satisfying the Model interface. If r.ID is an empty string, it will generate a pseudo-random id which is highly likely to be unique.
func (*RandomID) SetModelID ¶ added in v0.19.0
SetModelID sets the id of the model, satisfying the Model interface.
type ReplyHandler ¶ added in v0.9.0
type ReplyHandler func(reply interface{}) error
ReplyHandler is a function which does something with the reply from a Redis command or script. See https://godoc.org/github.com/garyburd/redigo/redis for a description of the concrete types for reply.
func NewScanBoolHandler ¶ added in v0.16.0
func NewScanBoolHandler(b *bool) ReplyHandler
NewScanBoolHandler returns a ReplyHandler which will convert the reply to a bool and set the value of i to the converted bool. The ReplyHandler will return an error if there was a problem converting the reply.
func NewScanFloat64Handler ¶ added in v0.16.0
func NewScanFloat64Handler(f *float64) ReplyHandler
NewScanFloat64Handler returns a ReplyHandler which will convert the reply to a float64 and set the value of f to the converted value. The ReplyHandler will return an error if there was a problem converting the reply.
func NewScanIntHandler ¶ added in v0.16.0
func NewScanIntHandler(i *int) ReplyHandler
NewScanIntHandler returns a ReplyHandler which will convert the reply to an integer and set the value of i to the converted integer. The ReplyHandler will return an error if there was a problem converting the reply.
func NewScanModelHandler ¶ added in v0.16.0
func NewScanModelHandler(fieldNames []string, model Model) ReplyHandler
NewScanModelHandler returns a ReplyHandler which will scan all the values in the reply into the fields of model. It expects a reply that looks like the output of an HMGET command, without the field names included. The order of fieldNames must correspond to the order of the values in the reply.
fieldNames should be the actual field names as they appear in the struct definition, not the Redis names which may be custom. The special field name "-" is used to represent the id for the model and will be set by the ReplyHandler using the SetModelID method.
For example, if fieldNames is ["Age", "Name", "-"] and the reply from Redis looks like this:
- "25"
- "Bob"
- "b1C7B0yETtXFYuKinndqoa"
The ReplyHandler will set the Age and the Name of the model to 25 and "Bob", respectively, using reflection. Then it will set the id of the model to "b1C7B0yETtXFYuKinndqoa" using the model's SetModelID method.
func NewScanModelsHandler ¶ added in v0.16.0
func NewScanModelsHandler(collection *Collection, fieldNames []string, models interface{}) ReplyHandler
NewScanModelsHandler returns a ReplyHandler which will scan the values of the reply into each corresponding Model in models. models should be a pointer to a slice of some concrete Model type. The type of the Models in models should match the type of the given Collection.
fieldNames should be the actual field names as they appear in the struct definition, not the Redis names which may be custom. The special value of "-" in fieldNames represents the id of the model and will be set via the SetModelID method. The ReplyHandler will use the length of fieldNames to determine which fields belong to which models.
The returned ReplyHandler will grow or shrink models as needed. It expects a reply which is a flat array of field values, with no separation between the fields for each model. The order of the values in the reply must correspond to the order of fieldNames.
For example, if fieldNames is ["Age", "Name", "-"] and the reply from Redis looks like this:
- "25"
- "Bob"
- "b1C7B0yETtXFYuKinndqoa"
- "27"
- "Alice"
- "NmjzzzDyNJpsCpPKnndqoa"
NewScanModelsHandler will use the first value in the reply to set the Age field of the first Model to 25 using reflection. It will use the second value of the reply to set Name value of the first Model to "Bob" using reflection. And finally, it will use the third value in reply to set the id of the first Model by calling its SetModelID method. Because the length of fieldNames is 3 in this case, the ReplyHandler will assign the first three to the first model, the next three to the second model, etc.
func NewScanStringHandler ¶ added in v0.16.0
func NewScanStringHandler(s *string) ReplyHandler
NewScanStringHandler returns a ReplyHandler which will convert the reply to a string and set the value of i to the converted string. The ReplyHandler will return an error if there was a problem converting the reply.
func NewScanStringsHandler ¶ added in v0.16.0
func NewScanStringsHandler(strings *[]string) ReplyHandler
NewScanStringsHandler returns a ReplyHandler which will convert the reply to a slice of strings and set the value of strings to the converted value. The returned ReplyHandler will grow or shrink strings as needed. The ReplyHandler will return an error if there was a problem converting the reply.
type Transaction ¶ added in v0.9.0
type Transaction struct {
// contains filtered or unexported fields
}
Transaction is an abstraction layer around a Redis transaction. Transactions consist of a set of actions which are either Redis commands or lua scripts. Transactions feature delayed execution, so nothing touches the database until you call Exec.
func (*Transaction) Command ¶ added in v0.9.0
func (t *Transaction) Command(name string, args redis.Args, handler ReplyHandler)
Command adds a command action to the transaction with the given args. handler will be called with the reply from this specific command when the transaction is executed.
func (*Transaction) Count ¶ added in v0.9.0
func (t *Transaction) Count(c *Collection, count *int)
Count counts the number of models of the given type in the database in an existing transaction. It sets the value of count to the number of models. Any errors encountered will be added to the transaction and returned as an error when the transaction is executed.
func (*Transaction) Delete ¶ added in v0.9.0
func (t *Transaction) Delete(c *Collection, id string, deleted *bool)
Delete removes a model with the given type and id in an existing transaction. deleted will be set to true iff the model was successfully deleted when the transaction is executed. If the no model with the given type and id existed, the value of deleted will be set to false. Any errors encountered will be added to the transaction and returned as an error when the transaction is executed. You may pass in nil for deleted if you do not care whether or not the model was deleted.
func (*Transaction) DeleteAll ¶ added in v0.9.0
func (t *Transaction) DeleteAll(c *Collection, count *int)
DeleteAll delets all models for the given model type in an existing transaction. The value of count will be set to the number of models that were successfully deleted when the transaction is executed. Any errors encountered will be added to the transaction and returned as an error when the transaction is executed. You may pass in nil for count if you do not care about the number of models that were deleted.
func (*Transaction) DeleteModelsBySetIDs ¶ added in v0.19.0
func (t *Transaction) DeleteModelsBySetIDs(setKey string, collectionName string, handler ReplyHandler)
DeleteModelsBySetIDs is a small function wrapper around a Lua script. The script will atomically delete the models corresponding to the ids in set (not sorted set) identified by setKey and return the number of models that were deleted. You can pass in a handler (e.g. NewScanIntHandler) to capture the return value of the script. You can use the Name method of a Collection to get the name.
func (*Transaction) Exec ¶ added in v0.9.0
func (t *Transaction) Exec() error
Exec executes the transaction, sequentially sending each action and calling all the action handlers with the corresponding replies.
func (*Transaction) Exists ¶ added in v0.18.0
func (t *Transaction) Exists(c *Collection, id string, exists *bool)
Exists sets the value of exists to true if a model exists in the given collection with the given id, and sets it to false otherwise. The first error encountered (if any) will be added to the transaction and returned when the transaction is executed.
func (*Transaction) ExtractIDsFromFieldIndex ¶ added in v0.19.0
func (t *Transaction) ExtractIDsFromFieldIndex(setKey string, destKey string, min interface{}, max interface{})
ExtractIDsFromFieldIndex is a small function wrapper around a Lua script. The script will get all the ids from the sorted set identified by setKey using ZRANGEBYSCORE with the given min and max, and then store them in a sorted set identified by destKey. The members of the sorted set should be model ids. Note that this method will not work on sorted sets that represents string indexes because they are stored differently.
func (*Transaction) ExtractIDsFromStringIndex ¶ added in v0.19.0
func (t *Transaction) ExtractIDsFromStringIndex(setKey, destKey, min, max string)
ExtractIDsFromStringIndex is a small function wrapper around a Lua script. The script will extract the ids from a sorted set identified by setKey using ZRANGEBYLEX with the given min and max, and then store them in a sorted set identified by destKey. All the scores for the sorted set should be 0, and the members should follow the format <value>\x00<id>, where <value> is the string value, \x000 is the NULL ASCII character and <id> is the id of the model with that value. As with all string indexes in Zoom, the value cannot contain the NULL ASCII character or the DEL character (codepoints 0 and 127 respectively). Note that the stored ids are sorted in ASCII order according to their corresponding string values.
func (*Transaction) Find ¶ added in v0.9.0
func (t *Transaction) Find(c *Collection, id string, model Model)
Find retrieves a model with the given id from redis and scans its values into model in an existing transaction. model should be a pointer to a struct of a registered type corresponding to the Collection. find will mutate the struct, filling in its fields and overwriting any previous values. Any errors encountered will be added to the transaction and returned as an error when the transaction is executed.
func (*Transaction) FindAll ¶ added in v0.9.0
func (t *Transaction) FindAll(c *Collection, models interface{})
FindAll finds all the models of the given type and scans the values of the models into models in an existing transaction. See http://redis.io/topics/transactions. models must be a pointer to a slice of models with a type corresponding to the Collection. findAll will grow the models slice as needed and if any of the models in the models slice are nil, FindAll will use reflection to allocate memory for them. Any errors encountered will be added to the transaction and returned as an error when the transaction is executed.
func (*Transaction) FindFields ¶ added in v0.13.0
func (t *Transaction) FindFields(c *Collection, id string, fieldNames []string, model Model)
FindFields is like Find but finds and sets only the specified fields. Any fields of the model which are not in the given fieldNames are not mutated. FindFields will return an error if any of the given fieldNames are not found in the model type.
func (*Transaction) Query ¶ added in v0.17.0
func (tx *Transaction) Query(collection *Collection) *TransactionQuery
Query is used to construct a query in the context of an existing Transaction It can be used to run a query atomically along with commands, scripts, or other queries in a single round trip. Note that this method returns a TransactionQuery, whereas Collection.NewQuery returns a Query. The two types are very similar, but there are differences in how they are eventually executed. Like a regular Query, a TransactionQuery can be chained together with one or more query modifiers (e.g. Filter or Order). You also need to finish the query with a method such as Run, RunOne, or Count. The major difference is that TransactionQueries are not actually run until you call Transaction.Exec(). As a consequence, the finisher methods (e.g. Run, RunOne, Count, etc) do not return anything. Instead they accept arguments which are then mutated after the transaction is executed.
func (*Transaction) Save ¶ added in v0.9.0
func (t *Transaction) Save(c *Collection, model Model)
Save writes a model (a struct which satisfies the Model interface) to the redis database inside an existing transaction. save will set the err property of the transaction if the type of model does not match the registered Collection, which will cause exec to fail immediately and return the error. To make a struct satisfy the Model interface, you can embed zoom.RandomID, which will generate pseudo-random ids for each model. Any errors encountered will be added to the transaction and returned as an error when the transaction is executed.
func (*Transaction) SaveFields ¶ added in v0.17.0
func (t *Transaction) SaveFields(c *Collection, fieldNames []string, model Model)
SaveFields saves only the given fields of the model inside an existing transaction. SaveFields will set the err property of the transaction if the type of model does not match the registered Collection, or if any of the given fieldNames are not found in the model type. In either case, the transaction will return the error when you call Exec. SaveFields uses "last write wins" semantics. If another caller updates the the same fields concurrently, your updates may be overwritten. If SaveFields is called on a model that has not yet been saved, it will not return an error. Instead, only the given fields will be saved in the database.
func (*Transaction) Script ¶ added in v0.9.0
func (t *Transaction) Script(script *redis.Script, args redis.Args, handler ReplyHandler)
Script adds a script action to the transaction with the given args. handler will be called with the reply from this specific script when the transaction is executed.
func (*Transaction) Watch ¶ added in v0.18.0
func (t *Transaction) Watch(model Model) error
Watch issues a Redis WATCH command using the key for the given model. If the model changes before the transaction is executed, Exec will return a WatchError and the commands in the transaction will not be executed. Unlike most other transaction methods, Watch does not use delayed execution. Because of how the WATCH command works, Watch must send a command to Redis immediately. You must call Watch or WatchKey before any other transaction methods.
func (*Transaction) WatchKey ¶ added in v0.18.0
func (t *Transaction) WatchKey(key string) error
WatchKey issues a Redis WATCH command using the given key. If the key changes before the transaction is executed, Exec will return a WatchError and the commands in the transaction will not be executed. Unlike most other transaction methods, WatchKey does not use delayed execution. Because of how the WATCH command works, WatchKey must send a command to Redis immediately. You must call Watch or WatchKey before any other transaction methods.
type TransactionQuery ¶ added in v0.17.0
type TransactionQuery struct {
// contains filtered or unexported fields
}
TransactionQuery represents a query which will be run inside an existing transaction. A TransactionQuery may consist of one or more query modifiers (e.g. Filter or Order) and should always be finished with a query finisher (e.g. Run or IDs). Unlike Query, the finisher methods for TransactionQuery always expect pointers as arguments and will set the values when the corresponding Transaction is executed.
func (*TransactionQuery) Count ¶ added in v0.17.0
func (q *TransactionQuery) Count(count *int)
Count will count the number of models that match the query criteria and set the value of count. It works very similarly to Query.Count, so you can check the documentation for Query.Count for more information. The first error encountered will be saved to the corresponding Transaction (if there is not already an error for the Transaction) and returned when you call Transaction.Exec.
func (*TransactionQuery) Exclude ¶ added in v0.17.0
func (q *TransactionQuery) Exclude(fields ...string) *TransactionQuery
Exclude works exactly like Query.Exclude. See the documentation for Query.Exclude for more information.
func (*TransactionQuery) Filter ¶ added in v0.17.0
func (q *TransactionQuery) Filter(filterString string, value interface{}) *TransactionQuery
Filter works exactly like Query.Filter. See the documentation for Query.Filter for more information.
func (*TransactionQuery) IDs ¶ added in v0.19.0
func (q *TransactionQuery) IDs(ids *[]string)
IDs will find the ids for models matching the query criteria and set the value of ids. It works very similarly to Query.IDs, so you can check the documentation for Query.IDs for more information. The first error encountered will be saved to the corresponding Transaction (if there is not already an error for the Transaction) and returned when you call Transaction.Exec.
func (*TransactionQuery) Include ¶ added in v0.17.0
func (q *TransactionQuery) Include(fields ...string) *TransactionQuery
Include works exactly like Query.Include. See the documentation for Query.Include for more information.
func (*TransactionQuery) Limit ¶ added in v0.17.0
func (q *TransactionQuery) Limit(amount uint) *TransactionQuery
Limit works exactly like Query.Limit. See the documentation for Query.Limit for more information.
func (*TransactionQuery) Offset ¶ added in v0.17.0
func (q *TransactionQuery) Offset(amount uint) *TransactionQuery
Offset works exactly like Query.Offset. See the documentation for Query.Offset for more information.
func (*TransactionQuery) Order ¶ added in v0.17.0
func (q *TransactionQuery) Order(fieldName string) *TransactionQuery
Order works exactly like Query.Order. See the documentation for Query.Order for a full description.
func (*TransactionQuery) Run ¶ added in v0.17.0
func (q *TransactionQuery) Run(models interface{})
Run will run the query and scan the results into models when the Transaction is executed. It works very similarly to Query.Run, so you can check the documentation for Query.Run for more information. The first error encountered will be saved to the corresponding Transaction (if there is not already an error for the Transaction) and returned when you call Transaction.Exec.
func (*TransactionQuery) RunOne ¶ added in v0.17.0
func (q *TransactionQuery) RunOne(model Model)
RunOne will run the query and scan the first model which matches the query criteria into model. If no model matches the query criteria, it will set a ModelNotFoundError on the Transaction. It works very similarly to Query.RunOne, so you can check the documentation for Query.RunOne for more information. The first error encountered will be saved to the corresponding Transaction (if there is not already an error for the Transaction) and returned when you call Transaction.Exec.
func (*TransactionQuery) StoreIDs ¶ added in v0.19.0
func (q *TransactionQuery) StoreIDs(destKey string)
StoreIDs will store the ids for for models matching the criteria in a list identified by destKey. It works very similarly to Query.StoreIDs, so you can check the documentation for Query.StoreIDs for more information. The first error encountered will be saved to the corresponding Transaction (if there is not already an error for the Transaction) and returned when you call Transaction.Exec.
type WatchError ¶ added in v0.18.0
type WatchError struct {
// contains filtered or unexported fields
}
WatchError is returned whenever a watched key is modified before a transaction can execute. It is part of the implementation of optimistic locking in Zoom. You can watch a key with the Transaction.WatchKey method.
func (WatchError) Error ¶ added in v0.18.0
func (e WatchError) Error() string