Cache

Thread-safe LRU caching system with configurable TTL, size limits, and namespace support. Used internally for statement caching, expression caching, and builder result caching.

CacheConfig

class sqlspec.core.cache.CacheConfig[source]

Bases: object

Global cache configuration for SQLSpec.

__init__(*, compiled_cache_enabled=True, sql_cache_enabled=True, fragment_cache_enabled=True, optimized_cache_enabled=True, sql_cache_size=1000, fragment_cache_size=5000, optimized_cache_size=2000)[source]

Initialize cache configuration.

Parameters:
  • compiled_cache_enabled (bool) – Master switch for namespaced caches and compiled SQL caching.

  • sql_cache_enabled (bool) – Enable statement and builder caching.

  • fragment_cache_enabled (bool) – Enable expression, parameter, and file caching.

  • optimized_cache_enabled (bool) – Enable optimized expression caching.

  • sql_cache_size (int) – Maximum statement/builder cache entries.

  • fragment_cache_size (int) – Maximum expression/parameter/file cache entries.

  • optimized_cache_size (int) – Maximum optimized cache entries.

LRUCache

class sqlspec.core.cache.LRUCache[source]

Bases: object

Cache with LRU eviction and TTL support.

Parameters:
  • max_size (int) – Maximum number of items to cache (LRU eviction when exceeded)

  • ttl_seconds (int | None) – Time-to-live in seconds (None for no expiration)

__init__(max_size=10000, ttl_seconds=3600, namespace=None)[source]

Initialize LRU cache.

Parameters:
  • max_size (int) – Maximum number of cache entries

  • ttl_seconds (int | None) – Time-to-live in seconds (None for no expiration)

  • namespace (str | None) – Optional namespace identifier for logging context

get(key)[source]

Get value from cache.

Parameters:

key (CacheKey) – Cache key to lookup

Return type:

Any | None

Returns:

Cached value or None if not found or expired

put(key, value)[source]

Put value in cache.

Parameters:
Return type:

None

delete(key)[source]

Delete entry from cache.

Parameters:

key (CacheKey) – Cache key to delete

Return type:

bool

Returns:

True if key was found and deleted, False otherwise

clear()[source]

Clear all cache entries.

Return type:

None

size()[source]

Get current cache size.

Return type:

int

is_empty()[source]

Check if cache is empty.

Return type:

bool

get_stats()[source]

Get cache statistics.

Return type:

CacheStats

__len__()[source]

Get current cache size.

Return type:

int

__contains__(key)[source]

Check if key exists in cache.

Return type:

bool

NamespacedCache

class sqlspec.core.cache.NamespacedCache[source]

Bases: object

Single cache with namespace isolation.

Uses per-namespace LRU caches sized by CacheConfig to keep memory usage predictable while avoiding stringly-typed cache access.

__init__(config=None, ttl_seconds=3600)[source]

Initialize namespaced cache.

Parameters:
  • config (CacheConfig | None) – Cache configuration to apply.

  • ttl_seconds (int | None) – Time-to-live in seconds (None for no expiration).

get_statement(key, dialect=None)[source]

Get cached statement data.

Parameters:
  • key (str) – Cache key.

  • dialect (str | None) – Optional SQL dialect.

Return type:

Any | None

Returns:

Cached value or None if not found.

put_statement(key, value, dialect=None)[source]

Cache compiled statement data.

Parameters:
  • key (str) – Cache key.

  • value (Any) – Value to cache.

  • dialect (str | None) – Optional SQL dialect.

Return type:

None

delete_statement(key, dialect=None)[source]

Delete cached statement data.

Parameters:
  • key (str) – Cache key.

  • dialect (str | None) – Optional SQL dialect.

Return type:

bool

Returns:

True when the key was found and deleted.

get_expression(key, dialect=None)[source]

Get cached expression data.

Parameters:
  • key (str) – Cache key.

  • dialect (str | None) – Optional SQL dialect.

Return type:

Any | None

Returns:

Cached value or None if not found.

put_expression(key, value, dialect=None)[source]

Cache parsed expression data.

Parameters:
  • key (str) – Cache key.

  • value (Any) – Value to cache.

  • dialect (str | None) – Optional SQL dialect.

Return type:

None

delete_expression(key, dialect=None)[source]

Delete cached expression data.

Parameters:
  • key (str) – Cache key.

  • dialect (str | None) – Optional SQL dialect.

Return type:

bool

Returns:

True when the key was found and deleted.

get_optimized(key, dialect=None)[source]

Get cached optimized expression data.

Parameters:
  • key (str) – Cache key.

  • dialect (str | None) – Optional SQL dialect.

Return type:

Any | None

Returns:

Cached value or None if not found.

put_optimized(key, value, dialect=None)[source]

Cache optimized expression data.

Parameters:
  • key (str) – Cache key.

  • value (Any) – Value to cache.

  • dialect (str | None) – Optional SQL dialect.

Return type:

None

delete_optimized(key, dialect=None)[source]

Delete cached optimized expression data.

Parameters:
  • key (str) – Cache key.

  • dialect (str | None) – Optional SQL dialect.

Return type:

bool

Returns:

True when the key was found and deleted.

get_builder(key, dialect=None)[source]

Get cached builder statement data.

Parameters:
  • key (str) – Cache key.

  • dialect (str | None) – Optional SQL dialect.

Return type:

Any | None

Returns:

Cached value or None if not found.

put_builder(key, value, dialect=None)[source]

Cache builder statement data.

Parameters:
  • key (str) – Cache key.

  • value (Any) – Value to cache.

  • dialect (str | None) – Optional SQL dialect.

Return type:

None

delete_builder(key, dialect=None)[source]

Delete cached builder statement data.

Parameters:
  • key (str) – Cache key.

  • dialect (str | None) – Optional SQL dialect.

Return type:

bool

Returns:

True when the key was found and deleted.

get_file(key, dialect=None)[source]

Get cached SQL file data.

Parameters:
  • key (str) – Cache key.

  • dialect (str | None) – Optional SQL dialect.

Return type:

Any | None

Returns:

Cached value or None if not found.

put_file(key, value, dialect=None)[source]

Cache SQL file data.

Parameters:
  • key (str) – Cache key.

  • value (Any) – Value to cache.

  • dialect (str | None) – Optional SQL dialect.

Return type:

None

delete_file(key, dialect=None)[source]

Delete cached SQL file data.

Parameters:
  • key (str) – Cache key.

  • dialect (str | None) – Optional SQL dialect.

Return type:

bool

Returns:

True when the key was found and deleted.

clear()[source]

Clear all cache entries.

Return type:

None

get_stats()[source]

Get cache statistics.

Return type:

CacheStats

CachedStatement

class sqlspec.core.cache.CachedStatement[source]

Bases: object

Immutable cached statement result.

This class stores compiled SQL and parameters in an immutable format that can be safely shared between different parts of the system without risk of mutation. List parameters are preserved for execute_many operations where drivers require list type.

__init__(compiled_sql, parameters, expression)[source]

Supporting Types

class sqlspec.core.cache.CacheKey[source]

Bases: object

Immutable cache key.

Parameters:

key_data (tuple[typing.Any, ...]) – Tuple of hashable values that uniquely identify the cached item

__init__(key_data)[source]

Initialize cache key.

Parameters:

key_data (tuple[typing.Any, ...]) – Tuple of hashable values for the cache key

property key_data: tuple[TypeAliasForwardRef('typing.Any'), ...]

Get the key data tuple.

__hash__()[source]

Return cached hash value.

Return type:

int

__eq__(other)[source]

Equality comparison.

Return type:

bool

__repr__()[source]

String representation of the cache key.

Return type:

str

class sqlspec.core.cache.CacheStats[source]

Bases: object

Cache statistics tracking.

Tracks cache metrics including hit rates, evictions, and memory usage.

__init__()[source]

Initialize cache statistics.

property hit_rate: float

Calculate cache hit rate as percentage.

property miss_rate: float

Calculate cache miss rate as percentage.

record_hit()[source]

Record a cache hit.

Return type:

None

record_miss()[source]

Record a cache miss.

Return type:

None

record_eviction()[source]

Record a cache eviction.

Return type:

None

reset()[source]

Reset all statistics.

Return type:

None

__repr__()[source]

String representation of cache statistics.

Return type:

str

class sqlspec.core.cache.CacheNode[source]

Bases: object

Internal cache node for LRU linked list implementation.

__init__(key, value)[source]

Initialize cache node.

Parameters:
  • key (CacheKey) – Cache key for this node

  • value (Any) – Cached value

class sqlspec.core.cache.FiltersView[source]

Bases: object

Read-only view of filters without copying.

Provides zero-copy access to filters with methods for querying, iteration, and canonical representation generation.

__init__(filters)[source]

Initialize filters view.

Parameters:

filters (list[typing.Any]) – List of filters (will be referenced, not copied)

__len__()[source]

Get number of filters.

Return type:

int

__iter__()[source]

Iterate over filters.

Return type:

Iterator[typing.Any]

get_by_field(field_name)[source]

Get all filters for a specific field.

Parameters:

field_name (str) – Field name to filter by

Return type:

list[typing.Any]

Returns:

List of filters matching the field name

has_field(field_name)[source]

Check if any filter exists for a field.

Parameters:

field_name (str) – Field name to check

Return type:

bool

Returns:

True if field has filters

to_canonical()[source]

Create canonical representation for cache keys.

Return type:

tuple[typing.Any, ...]

Returns:

Canonical tuple representation of filters

Module-Level Functions

sqlspec.core.cache.get_cache()[source]

Get the namespaced cache instance.

Return type:

NamespacedCache

Returns:

Singleton namespaced cache instance

sqlspec.core.cache.get_default_cache()[source]

Get the default LRU cache instance.

Return type:

LRUCache

Returns:

Singleton default cache instance

sqlspec.core.cache.get_cache_config()[source]

Get the global cache configuration.

Return type:

CacheConfig

Returns:

Current global cache configuration instance

sqlspec.core.cache.update_cache_config(config)[source]

Update the global cache configuration.

Clears all existing caches when configuration changes.

Parameters:

config (CacheConfig) – New cache configuration to apply globally

Return type:

None

sqlspec.core.cache.get_cache_statistics()[source]

Get statistics from all cache instances.

Return type:

dict[str, CacheStats]

Returns:

Dictionary mapping cache type to statistics

sqlspec.core.cache.get_cache_stats()[source]

Get cache statistics from all caches.

Return type:

dict[str, CacheStats]

Returns:

Dictionary of cache statistics

sqlspec.core.cache.log_cache_stats()[source]

Log cache statistics.

Return type:

None

sqlspec.core.cache.reset_cache_stats()[source]

Reset all cache statistics.

Return type:

None

sqlspec.core.cache.clear_all_caches()[source]

Clear all cache instances.

Return type:

None

sqlspec.core.cache.create_cache_key(namespace, key, dialect=None)[source]

Create optimized cache key using string concatenation.

Parameters:
  • namespace (str) – Cache namespace name.

  • key (str) – Base cache key.

  • dialect (str | None) – SQL dialect (optional).

Return type:

str

Returns:

Optimized cache key string.

sqlspec.core.cache.canonicalize_filters(filters)[source]

Create canonical representation of filters for cache keys.

Parameters:

filters (list[Filter]) – List of filters to canonicalize

Return type:

tuple[Filter, ...]

Returns:

Tuple of unique filters sorted by field_name, operation, then value