Documentation
¶
Overview ¶
Package repositorycache provides cached repository decorators for go-repository-bun.
Overview ¶
This package implements the repository decorator pattern to add caching capabilities to existing repository implementations from go-repository-bun. The cached repository wraps a base repository and intercepts read operations to provide caching while delegating write operations directly to the base repository.
Key Features ¶
- **Type-safe caching**: Uses Go generics to maintain type safety across cached operations
- **Selective caching**: Only read operations are cached; write operations pass through
- **Transaction awareness**: Transaction-based operations bypass cache for consistency
- **Pluggable key strategy**: Configurable key serialization via KeySerializer interface
- **Cache invalidation ready**: Structured for future cache invalidation strategies
Basic Usage ¶
Create a cached repository by wrapping an existing repository:
base := myrepo.New(db) // Your existing go-repository-bun repository
cache := internal.NewSturdycService(cacheConfig)
keySerializer := cache.NewDefaultKeySerializer()
cached := repositorycache.New(base, cache, keySerializer)
// Use exactly like your base repository
user, err := cached.GetByID(ctx, "user-123")
users, total, err := cached.List(ctx, repository.Where("active", true))
Cached vs Pass-through Operations ¶
## Cached Operations (Read-only)
These operations use the cache for improved performance:
- Get, GetByID, GetByIdentifier
- List, Count
## Pass-through Operations
These operations bypass the cache and go directly to the base repository:
- All write operations (Create, Update, Upsert, Delete and variants)
- All transaction-based operations (*Tx methods)
- Raw SQL queries
Caching Behavior ¶
The cached repository follows a read-through caching pattern:
- Check cache for the serialized key
- If cache hit, return cached result
- If cache miss, call base repository
- Store result in cache
- Return result to caller
Key serialization includes the method name and deterministic value parameters. Reads with function-valued SelectCriteria bypass the cache because closure code pointers do not include captured query values.
Transaction Handling ¶
Operations within transactions (*Tx methods) bypass the cache entirely to ensure transaction isolation and consistency. This prevents:
- Reading stale cached data within transactions
- Cache pollution from uncommitted transaction data
- Inconsistent reads across transaction boundaries
Cache Invalidation Strategy ¶
The invalidation strategy is documented in REPOSITORY_CACHE.md and implemented in this package. When the cache service implements cache.TagRegistry, read operations register tags and write operations invalidate by tags for scope- and record-aware eviction. If TagRegistry is not available, the decorator falls back to prefix-based invalidation.
Custom read paths can attach extra tags using repositorycache.WithCacheTags.
Integration with Dependency Injection ¶
This package is designed to work with the dependency injection container provided in pkg/di:
container, err := di.NewContainer(cacheConfig)
if err != nil {
return err
}
cachedRepo := container.NewCachedRepository(baseRepo)
Compatibility ¶
The CachedRepository[T] fully implements the repository.Repository[T] interface from go-repository-bun, making it a drop-in replacement for existing repository usage. The decorator pattern ensures that all methods are available and maintain the same signatures as the base interface.
Performance Considerations ¶
- Cache hits avoid database roundtrips for read operations
- Key serialization has minimal overhead using reflection
- List operations cache both records and total count as a unit
- Function-valued criteria pass through to preserve query correctness
Error Handling ¶
Errors from the base repository are propagated unchanged. Cache errors (serialization failures, cache backend issues) are handled gracefully without breaking the underlying repository operations.
See Also ¶
For cache configuration and key serialization details, see the cache package. For dependency injection setup, see the pkg/di package.
Index ¶
- func WithCacheTags(ctx context.Context, tags ...string) context.Context
- type CachedRepository
- func (c *CachedRepository[T]) Count(ctx context.Context, criteria ...repository.SelectCriteria) (int, error)
- func (c *CachedRepository[T]) CountTx(ctx context.Context, tx bun.IDB, criteria ...repository.SelectCriteria) (int, error)
- func (c *CachedRepository[T]) Create(ctx context.Context, record T, criteria ...repository.InsertCriteria) (T, error)
- func (c *CachedRepository[T]) CreateMany(ctx context.Context, records []T, criteria ...repository.InsertCriteria) ([]T, error)
- func (c *CachedRepository[T]) CreateManyTx(ctx context.Context, tx bun.IDB, records []T, ...) ([]T, error)
- func (c *CachedRepository[T]) CreateTx(ctx context.Context, tx bun.IDB, record T, ...) (T, error)
- func (c *CachedRepository[T]) Delete(ctx context.Context, record T) error
- func (c *CachedRepository[T]) DeleteMany(ctx context.Context, criteria ...repository.DeleteCriteria) error
- func (c *CachedRepository[T]) DeleteManyTx(ctx context.Context, tx bun.IDB, criteria ...repository.DeleteCriteria) error
- func (c *CachedRepository[T]) DeleteTx(ctx context.Context, tx bun.IDB, record T) error
- func (c *CachedRepository[T]) DeleteWhere(ctx context.Context, criteria ...repository.DeleteCriteria) error
- func (c *CachedRepository[T]) DeleteWhereTx(ctx context.Context, tx bun.IDB, criteria ...repository.DeleteCriteria) error
- func (c *CachedRepository[T]) ForceDelete(ctx context.Context, record T) error
- func (c *CachedRepository[T]) ForceDeleteTx(ctx context.Context, tx bun.IDB, record T) error
- func (c *CachedRepository[T]) Get(ctx context.Context, criteria ...repository.SelectCriteria) (T, error)
- func (c *CachedRepository[T]) GetByID(ctx context.Context, id string, criteria ...repository.SelectCriteria) (T, error)
- func (c *CachedRepository[T]) GetByIDTx(ctx context.Context, tx bun.IDB, id string, ...) (T, error)
- func (c *CachedRepository[T]) GetByIdentifier(ctx context.Context, identifier string, criteria ...repository.SelectCriteria) (T, error)
- func (c *CachedRepository[T]) GetByIdentifierTx(ctx context.Context, tx bun.IDB, identifier string, ...) (T, error)
- func (c *CachedRepository[T]) GetOrCreate(ctx context.Context, record T) (T, error)
- func (c *CachedRepository[T]) GetOrCreateTx(ctx context.Context, tx bun.IDB, record T) (T, error)
- func (c *CachedRepository[T]) GetScopeDefaults() repository.ScopeDefaults
- func (c *CachedRepository[T]) GetTx(ctx context.Context, tx bun.IDB, criteria ...repository.SelectCriteria) (T, error)
- func (c *CachedRepository[T]) Handlers() repository.ModelHandlers[T]
- func (c *CachedRepository[T]) List(ctx context.Context, criteria ...repository.SelectCriteria) ([]T, int, error)
- func (c *CachedRepository[T]) ListTx(ctx context.Context, tx bun.IDB, criteria ...repository.SelectCriteria) ([]T, int, error)
- func (c *CachedRepository[T]) Raw(ctx context.Context, sql string, args ...any) ([]T, error)
- func (c *CachedRepository[T]) RawTx(ctx context.Context, tx bun.IDB, sql string, args ...any) ([]T, error)
- func (c *CachedRepository[T]) RegisterScope(name string, scope repository.ScopeDefinition)
- func (c *CachedRepository[T]) SetScopeDefaults(defaults repository.ScopeDefaults) error
- func (c *CachedRepository[T]) Update(ctx context.Context, record T, criteria ...repository.UpdateCriteria) (T, error)
- func (c *CachedRepository[T]) UpdateMany(ctx context.Context, records []T, criteria ...repository.UpdateCriteria) ([]T, error)
- func (c *CachedRepository[T]) UpdateManyTx(ctx context.Context, tx bun.IDB, records []T, ...) ([]T, error)
- func (c *CachedRepository[T]) UpdateTx(ctx context.Context, tx bun.IDB, record T, ...) (T, error)
- func (c *CachedRepository[T]) Upsert(ctx context.Context, record T, criteria ...repository.UpdateCriteria) (T, error)
- func (c *CachedRepository[T]) UpsertMany(ctx context.Context, records []T, criteria ...repository.UpdateCriteria) ([]T, error)
- func (c *CachedRepository[T]) UpsertManyTx(ctx context.Context, tx bun.IDB, records []T, ...) ([]T, error)
- func (c *CachedRepository[T]) UpsertTx(ctx context.Context, tx bun.IDB, record T, ...) (T, error)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type CachedRepository ¶
type CachedRepository[T any] struct { // contains filtered or unexported fields }
CachedRepository decorates a base repository with caching functionality
func New ¶
func New[T any](base repository.Repository[T], cacheService cache.CacheService, keySerializer cache.KeySerializer) *CachedRepository[T]
New creates a new CachedRepository that wraps the base repository with caching
func NewWithIdentifierFields ¶ added in v0.4.0
func NewWithIdentifierFields[T any](base repository.Repository[T], cacheService cache.CacheService, keySerializer cache.KeySerializer, identifierFields ...string) *CachedRepository[T]
NewWithIdentifierFields creates a CachedRepository with custom identifier field names. Field names must match the struct field names returned by the repository handlers.
func (*CachedRepository[T]) Count ¶
func (c *CachedRepository[T]) Count(ctx context.Context, criteria ...repository.SelectCriteria) (int, error)
Count caches value-only reads and passes criteria-bearing reads through to the base repository.
func (*CachedRepository[T]) CountTx ¶
func (c *CachedRepository[T]) CountTx(ctx context.Context, tx bun.IDB, criteria ...repository.SelectCriteria) (int, error)
CountTx returns the number of records matching the criteria within a transaction
func (*CachedRepository[T]) Create ¶
func (c *CachedRepository[T]) Create(ctx context.Context, record T, criteria ...repository.InsertCriteria) (T, error)
Create creates a new record. Write operations pass through to base repository
func (*CachedRepository[T]) CreateMany ¶
func (c *CachedRepository[T]) CreateMany(ctx context.Context, records []T, criteria ...repository.InsertCriteria) ([]T, error)
CreateMany creates multiple records
func (*CachedRepository[T]) CreateManyTx ¶
func (c *CachedRepository[T]) CreateManyTx(ctx context.Context, tx bun.IDB, records []T, criteria ...repository.InsertCriteria) ([]T, error)
CreateManyTx creates multiple records within a transaction
func (*CachedRepository[T]) CreateTx ¶
func (c *CachedRepository[T]) CreateTx(ctx context.Context, tx bun.IDB, record T, criteria ...repository.InsertCriteria) (T, error)
CreateTx creates a new record within a transaction
func (*CachedRepository[T]) Delete ¶
func (c *CachedRepository[T]) Delete(ctx context.Context, record T) error
Delete deletes a record
func (*CachedRepository[T]) DeleteMany ¶
func (c *CachedRepository[T]) DeleteMany(ctx context.Context, criteria ...repository.DeleteCriteria) error
DeleteMany deletes multiple records based on criteria
func (*CachedRepository[T]) DeleteManyTx ¶
func (c *CachedRepository[T]) DeleteManyTx(ctx context.Context, tx bun.IDB, criteria ...repository.DeleteCriteria) error
DeleteManyTx deletes multiple records based on criteria within a transaction
func (*CachedRepository[T]) DeleteWhere ¶
func (c *CachedRepository[T]) DeleteWhere(ctx context.Context, criteria ...repository.DeleteCriteria) error
DeleteWhere deletes records based on criteria
func (*CachedRepository[T]) DeleteWhereTx ¶
func (c *CachedRepository[T]) DeleteWhereTx(ctx context.Context, tx bun.IDB, criteria ...repository.DeleteCriteria) error
DeleteWhereTx deletes records based on criteria within a transaction
func (*CachedRepository[T]) ForceDelete ¶
func (c *CachedRepository[T]) ForceDelete(ctx context.Context, record T) error
ForceDelete force deletes a record (bypassing soft delete)
func (*CachedRepository[T]) ForceDeleteTx ¶
ForceDeleteTx force deletes a record within a transaction (bypassing soft delete)
func (*CachedRepository[T]) Get ¶
func (c *CachedRepository[T]) Get(ctx context.Context, criteria ...repository.SelectCriteria) (T, error)
Get caches value-only reads and passes criteria-bearing reads through to the base repository.
func (*CachedRepository[T]) GetByID ¶
func (c *CachedRepository[T]) GetByID(ctx context.Context, id string, criteria ...repository.SelectCriteria) (T, error)
GetByID caches value-only reads and passes criteria-bearing reads through to the base repository.
func (*CachedRepository[T]) GetByIDTx ¶
func (c *CachedRepository[T]) GetByIDTx(ctx context.Context, tx bun.IDB, id string, criteria ...repository.SelectCriteria) (T, error)
GetByIDTx retrieves a record by ID with optional criteria within a transaction
func (*CachedRepository[T]) GetByIdentifier ¶
func (c *CachedRepository[T]) GetByIdentifier(ctx context.Context, identifier string, criteria ...repository.SelectCriteria) (T, error)
GetByIdentifier caches value-only reads and passes criteria-bearing reads through to the base repository.
func (*CachedRepository[T]) GetByIdentifierTx ¶
func (c *CachedRepository[T]) GetByIdentifierTx(ctx context.Context, tx bun.IDB, identifier string, criteria ...repository.SelectCriteria) (T, error)
GetByIdentifierTx retrieves a record by identifier with optional criteria within a transaction
func (*CachedRepository[T]) GetOrCreate ¶
func (c *CachedRepository[T]) GetOrCreate(ctx context.Context, record T) (T, error)
GetOrCreate gets a record or creates it if it doesn't exist
func (*CachedRepository[T]) GetOrCreateTx ¶
GetOrCreateTx gets a record or creates it if it doesn't exist within a transaction
func (*CachedRepository[T]) GetScopeDefaults ¶ added in v0.5.0
func (c *CachedRepository[T]) GetScopeDefaults() repository.ScopeDefaults
func (*CachedRepository[T]) GetTx ¶
func (c *CachedRepository[T]) GetTx(ctx context.Context, tx bun.IDB, criteria ...repository.SelectCriteria) (T, error)
GetTx retrieves a single record using the provided criteria within a transaction
func (*CachedRepository[T]) Handlers ¶
func (c *CachedRepository[T]) Handlers() repository.ModelHandlers[T]
Handlers returns the model handlers from the base repository
func (*CachedRepository[T]) List ¶
func (c *CachedRepository[T]) List(ctx context.Context, criteria ...repository.SelectCriteria) ([]T, int, error)
List caches value-only reads and passes criteria-bearing reads through to the base repository.
func (*CachedRepository[T]) ListTx ¶
func (c *CachedRepository[T]) ListTx(ctx context.Context, tx bun.IDB, criteria ...repository.SelectCriteria) ([]T, int, error)
ListTx retrieves multiple records using the provided criteria within a transaction
func (*CachedRepository[T]) RawTx ¶
func (c *CachedRepository[T]) RawTx(ctx context.Context, tx bun.IDB, sql string, args ...any) ([]T, error)
RawTx executes a raw SQL query within a transaction and returns the results
func (*CachedRepository[T]) RegisterScope ¶ added in v0.5.0
func (c *CachedRepository[T]) RegisterScope(name string, scope repository.ScopeDefinition)
func (*CachedRepository[T]) SetScopeDefaults ¶ added in v0.5.0
func (c *CachedRepository[T]) SetScopeDefaults(defaults repository.ScopeDefaults) error
func (*CachedRepository[T]) Update ¶
func (c *CachedRepository[T]) Update(ctx context.Context, record T, criteria ...repository.UpdateCriteria) (T, error)
Update updates a record
func (*CachedRepository[T]) UpdateMany ¶
func (c *CachedRepository[T]) UpdateMany(ctx context.Context, records []T, criteria ...repository.UpdateCriteria) ([]T, error)
UpdateMany updates multiple records
func (*CachedRepository[T]) UpdateManyTx ¶
func (c *CachedRepository[T]) UpdateManyTx(ctx context.Context, tx bun.IDB, records []T, criteria ...repository.UpdateCriteria) ([]T, error)
UpdateManyTx updates multiple records within a transaction
func (*CachedRepository[T]) UpdateTx ¶
func (c *CachedRepository[T]) UpdateTx(ctx context.Context, tx bun.IDB, record T, criteria ...repository.UpdateCriteria) (T, error)
UpdateTx updates a record within a transaction
func (*CachedRepository[T]) Upsert ¶
func (c *CachedRepository[T]) Upsert(ctx context.Context, record T, criteria ...repository.UpdateCriteria) (T, error)
Upsert inserts or updates a record
func (*CachedRepository[T]) UpsertMany ¶
func (c *CachedRepository[T]) UpsertMany(ctx context.Context, records []T, criteria ...repository.UpdateCriteria) ([]T, error)
UpsertMany inserts or updates multiple records
func (*CachedRepository[T]) UpsertManyTx ¶
func (c *CachedRepository[T]) UpsertManyTx(ctx context.Context, tx bun.IDB, records []T, criteria ...repository.UpdateCriteria) ([]T, error)
UpsertManyTx inserts or updates multiple records within a transaction
func (*CachedRepository[T]) UpsertTx ¶
func (c *CachedRepository[T]) UpsertTx(ctx context.Context, tx bun.IDB, record T, criteria ...repository.UpdateCriteria) (T, error)
UpsertTx inserts or updates a record within a transaction