class

Ralph::StatementCache(V)

Inherits Reference / Object

LRU (Least Recently Used) Cache for prepared statements

This cache stores compiled/prepared statements to avoid reparsing SQL queries. When the cache is full, the least recently used statement is evicted.

Thread Safety

Crystal uses fibers (green threads) with cooperative scheduling, so a mutex is used to ensure fiber-safety when accessing the cache.

Example

cache = Ralph::StatementCache(String).new(max_size: 100)
cache.set("SELECT * FROM users WHERE id = ?", "prepared_stmt_handle")
stmt = cache.get("SELECT * FROM users WHERE id = ?")

Constructors

new(max_size : Int32 = 100, enabled : Bool = true)

Creates a new statement cache

Parameters

  • max_size: Maximum number of statements to cache (default: 100)
  • enabled: Whether caching is enabled (default: true)
Source

Instance methods

clear

Clear all cached statements

Returns an array of all evicted values so they can be cleaned up.

Source
delete(key : String) : V | Nil

Remove a specific entry from the cache

Returns the removed value if found.

Source
enabled=(value : Bool)

Enable or disable the cache

When disabled, get always returns nil and set is a no-op. Existing entries are preserved but not accessible until re-enabled.

Source
enabled?
Source
get(key : String) : V | Nil

Get a cached value, marking it as recently used

Returns nil if not found or caching is disabled.

Source
has?(key : String) : Bool

Check if a key exists in the cache

Source
max_size
Source
set(key : String, value : V) : V | Nil

Store a value in the cache

If the cache is full, the least recently used entry is evicted. Returns the evicted value (if any) so it can be cleaned up.

Source
size

Get current number of cached statements

Source
stats

Get cache statistics

Source