Skip to content

Caching & Hashing

from sqlspec.core import (
    CacheConfig,
    CachedStatement,
    CacheKey,
    CacheStats,
    LRUCache,
    NamespacedCache,
    clear_all_caches,
    create_cache_key,
    get_cache,
    get_cache_config,
    get_cache_statistics,
    hash_expression,
    hash_sql_statement,
    log_cache_stats,
    reset_stats_only,
    update_cache_config,
)

Multi-tier LRU caching and deterministic structural hashing for SQL statements, SQLGlot AST expressions, and parameter bindings. See the Performance Guide for tuning guidance.

Cache Configuration & Statistics

CacheConfig

Global cache configuration for SQLSpec.

CacheStats

Cache statistics tracking.

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

CachedStatement

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.

CacheKey

Immutable cache key.

Parameters:

Name Type Description Default
key_data tuple[Any, ...]

Tuple of hashable values that uniquely identify the cached item

required

Cache Implementations

LRUCache

Cache with LRU eviction and TTL support.

Parameters:

Name Type Description Default
max_size int

Maximum number of items to cache (LRU eviction when exceeded)

DEFAULT_MAX_SIZE
ttl_seconds int | None

Time-to-live in seconds (None for no expiration)

DEFAULT_TTL_SECONDS

get

get(key)

Get value from cache.

Parameters:

Name Type Description Default
key CacheKey

Cache key to lookup

required

Returns:

Type Description
Any | None

Cached value or None if not found or expired

put

put(key, value)

Put value in cache.

Parameters:

Name Type Description Default
key CacheKey

Cache key

required
value Any

Value to cache

required

delete

delete(key)

Delete entry from cache.

Parameters:

Name Type Description Default
key CacheKey

Cache key to delete

required

Returns:

Type Description
bool

True if key was found and deleted, False otherwise

clear

clear()

Clear all cache entries.

get_stats

get_stats()

Get cache statistics.

NamespacedCache

Single cache with namespace isolation.

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

Cache Management & Hashing Functions

get_cache_config

get_cache_config()

Get the global cache configuration.

Returns:

Type Description
CacheConfig

Current global cache configuration instance

update_cache_config

update_cache_config(config)

Update the global cache configuration.

Clears all existing caches when configuration changes.

Parameters:

Name Type Description Default
config CacheConfig

New cache configuration to apply globally

required

get_cache_statistics

get_cache_statistics()

Get statistics from all cache instances.

Returns:

Type Description
dict[str, CacheStats]

Dictionary mapping cache type to statistics

clear_all_caches

clear_all_caches()

Clear all cache instances.

reset_stats_only

reset_stats_only()

Reset cache statistics without evicting cached entries.

log_cache_stats

log_cache_stats()

Log cache statistics.

hash_sql_statement

hash_sql_statement(statement)

Generate cache key for a SQL statement.

Parameters:

Name Type Description Default
statement SQL

SQL statement object

required

Returns:

Type Description
str

Cache key string

hash_expression

hash_expression(expr, _seen=None)

Generate hash from AST structure.

Parameters:

Name Type Description Default
expr Expr | None

SQLGlot Expression to hash

required
_seen set[int] | None

Set of seen object IDs to handle circular references

None

Returns:

Type Description
int

Hash of the AST structure

hash_parameters

hash_parameters(
    positional_parameters=None, named_parameters=None, original_parameters=None
)

Generate hash for SQL parameters.

Parameters:

Name Type Description Default
positional_parameters list[Any] | None

List of positional parameters

None
named_parameters dict[str, Any] | None

Dictionary of named parameters

None
original_parameters Any | None

Original parameters (for execute_many)

None

Returns:

Type Description
int

Combined hash of all parameters