Documentation
¶
Index ¶
- Variables
- func Cache(ctx context.Context, opts ...QueryOption) context.Context
- func CacheOnlySentinelColumns() []string
- func NewContext(ctx context.Context, levels ...AddGetDeleter) context.Context
- type AddGetDeleter
- type Driver
- func (d *Driver) ExecContext(ctx context.Context, query string, args ...any) (stdsql.Result, error)
- func (d *Driver) Query(ctx context.Context, query string, args, v any) error
- func (d *Driver) QueryContext(ctx context.Context, query string, args ...any) (*stdsql.Rows, error)
- func (d *Driver) Stats() Stats
- type Entry
- type Key
- type LRU
- type Option
- type Options
- type QueryOption
- type Redis
- type Stats
Constants ¶
This section is empty.
Variables ¶
var ErrNotFound = errors.New("entcache: entry was not found")
ErrNotFound returned by Get when and Entry does not exist in the cache.
Functions ¶
func Cache ¶ added in v0.2.0
func Cache(ctx context.Context, opts ...QueryOption) context.Context
Cache returns a context that enables caching for the query. Accepts optional configuration via functional options.
Examples:
// Basic caching
ctx := entcache.Cache(ctx)
// With custom TTL
ctx := entcache.Cache(ctx, WithTTL(time.Hour))
// Cache-only read (no DB fallback)
ctx := entcache.Cache(ctx, CacheOnly())
// Invalidate without execution
ctx := entcache.Cache(ctx, CacheOnly(), Evict())
// Execute, cache, and set custom key
ctx := entcache.Cache(ctx, WithKey("my-key"), WithTTL(time.Minute))
func CacheOnlySentinelColumns ¶ added in v0.3.0
func CacheOnlySentinelColumns() []string
CacheOnlySentinelColumns returns the sentinel column names used for CacheOnly miss scenarios. This is exported for testing purposes.
func NewContext ¶
func NewContext(ctx context.Context, levels ...AddGetDeleter) context.Context
NewContext returns a new Context that carries a cache.
Types ¶
type AddGetDeleter ¶
type AddGetDeleter interface {
Del(context.Context, Key) error
Add(context.Context, Key, *Entry, time.Duration) error
Get(context.Context, Key) (*Entry, error)
}
AddGetDeleter defines the interface for getting, adding and deleting entries from the cache.
func FromContext ¶
func FromContext(ctx context.Context) (AddGetDeleter, bool)
FromContext returns the cache value stored in ctx, if any.
type Driver ¶
A Driver is an SQL-cached client. Users should use the constructor below for creating a new driver.
func NewDriver ¶
NewDriver returns a new Driver an existing driver and optional configuration functions. For example,
entcache.NewDriver(
drv,
entcache.TTL(time.Minute),
entcache.Levels(
NewLRU(256),
NewRedis(redis.NewClient(&redis.Options{
Addr: ":6379",
})),
)
)
func (*Driver) ExecContext ¶
ExecContext calls ExecContext of the underlying driver, or fails if it is not supported.
func (*Driver) Query ¶
Query implements the Querier interface for the driver. It falls back to the underlying wrapped driver in case of caching error.
Note that unless Singleflight is enabled, the driver does not synchronize identical queries that are executed concurrently. Hence, if two identical queries are executed at the ~same time, and there is no cache entry for them, the driver will execute both of them and the last successful one will be stored in the cache.
func (*Driver) QueryContext ¶
QueryContext calls QueryContext of the underlying driver, or fails if it is not supported. Note, this method is not part of the caching layer since Ent does not use it by default.
type Entry ¶
type Entry struct {
Columns []string `cbor:"0,keyasint" json:"c" bson:"c"`
Values [][]driver.Value `cbor:"1,keyasint" json:"v" bson:"v"`
}
func (Entry) MarshalBinary ¶
MarshalBinary implements the encoding.BinaryMarshaler interface.
func (*Entry) UnmarshalBinary ¶
UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
type Key ¶
type Key any
A Key defines a comparable Go value. See http://golang.org/ref/spec#Comparison_operators
type LRU ¶
LRU provides an LRU cache that implements the AddGetter interface.
type Option ¶
type Option func(*Options)
Option allows configuring the cache driver using functional options.
func ContextLevel ¶
func ContextLevel() Option
ContextLevel configures the driver to work with context/request level cache. Users that use this option should wrap the *http.Request context with the cache value as follows:
ctx = entcache.NewContext(ctx) ctx = entcache.NewContext(ctx, entcache.NewLRU(128))
func Hash ¶
Hash configures an optional Hash function for converting a query and its arguments to a cache key.
func Levels ¶
func Levels(levels ...AddGetDeleter) Option
Levels configure the Driver to work with the given cache levels. For example, in process LRU cache and a remote Redis cache.
func WithSingleflight ¶ added in v0.4.0
WithSingleflight enables or disables request coalescing for concurrent identical queries. When enabled, if multiple goroutines request the same uncached query simultaneously, only one will execute the database query and the result will be shared with all callers. This prevents cache stampedes where many concurrent requests hit the database for the same data.
type Options ¶
type Options struct {
// TTL defines the period of time that an Entry
// is valid in the cache.
TTL time.Duration
// Cache defines the GetAddDeleter (cache implementation)
// for holding the cache entries. If no cache implementation
// was provided, an LRU cache with no limit is used.
Cache AddGetDeleter
// Hash defines an optional Hash function for converting
// a query and its arguments to a cache key. If no Hash
// function was provided, the DefaultHash is used.
Hash func(query string, args []any) (Key, error)
// Logf function. If provided, the Driver will call it with
// errors that cannot be handled.
Log func(...any)
// Singleflight enables request coalescing for concurrent identical queries.
// When enabled, concurrent queries with the same cache key will be deduplicated,
// with only one query executed and the result shared among all callers.
// Default is false.
Singleflight bool
}
Options wrap the basic configuration cache options.
type QueryOption ¶ added in v0.3.0
type QueryOption func(*ctxOptions)
QueryOption configures cache behavior for a query.
func CacheOnly ¶ added in v0.3.0
func CacheOnly() QueryOption
CacheOnly configures the driver to skip database execution. When used alone, reads from cache and returns empty result if not cached. When combined with Evict(), invalidates the cache without executing the query.
// Read from cache only (no DB fallback) users, err := client.User.Query().All(entcache.Cache(ctx, CacheOnly())) // Invalidate without executing query _, err := client.User.Query().Where(...).All(entcache.Cache(ctx, CacheOnly(), Evict()))
func Evict ¶
func Evict() QueryOption
Evict invalidates the cache entry after determining its key. When used alone, executes the query and invalidates the cached result. When combined with CacheOnly(), invalidates without executing.
// Execute and invalidate users, err := client.User.Query().All(entcache.Cache(ctx, Evict())) // Invalidate only (no execution) _, err := client.User.Query().Where(...).All(entcache.Cache(ctx, CacheOnly(), Evict()))
func WithKey ¶
func WithKey(key Key) QueryOption
WithKey sets a custom cache key instead of generating one from the query. Note that this option should not be used if the ent.Client query involves more than 1 SQL query (e.g., eager loading).
users, err := client.User.Query().All(entcache.Cache(ctx, WithKey("my-key")))
func WithTTL ¶
func WithTTL(ttl time.Duration) QueryOption
WithTTL sets a custom TTL for this cache entry.
users, err := client.User.Query().All(entcache.Cache(ctx, WithTTL(time.Hour)))
type Redis ¶
type Redis struct {
// contains filtered or unexported fields
}
Redis provides a remote cache backed by Redis and implements the SetGetter interface.


