Skip to main content

sqlx_core/common/
statement_cache.rs

1use hashlink::lru_cache::LruCache;
2
3/// A cache for prepared statements. When full, the least recently used
4/// statement gets removed.
5#[derive(Debug)]
6pub struct StatementCache<T> {
7    inner: LruCache<String, T>,
8}
9
10impl<T> StatementCache<T> {
11    /// Create a new cache with the given capacity.
12    pub fn new(capacity: usize) -> Self {
13        Self {
14            inner: LruCache::new(capacity),
15        }
16    }
17
18    /// Returns a mutable reference to the value corresponding to the given key
19    /// in the cache, if any.
20    pub fn get_mut(&mut self, k: &str) -> Option<&mut T> {
21        self.inner.get_mut(k)
22    }
23
24    /// Removes statement by key, returning removed statement if removed
25    pub fn remove(&mut self, k: &str) -> Option<T> {
26        self.inner.remove(k)
27    }
28
29    /// Inserts a new statement to the cache, returning the least recently used
30    /// statement id if the cache is full, or if inserting with an existing key,
31    /// the replaced existing statement.
32    pub fn insert(&mut self, k: &str, v: T) -> Option<T> {
33        let mut lru_item = None;
34
35        if self.capacity() == self.len() && !self.contains_key(k) {
36            lru_item = self.remove_lru();
37        } else if self.contains_key(k) {
38            lru_item = self.inner.remove(k);
39        }
40
41        self.inner.insert(k.into(), v);
42
43        lru_item
44    }
45
46    /// The number of statements in the cache.
47    pub fn len(&self) -> usize {
48        self.inner.len()
49    }
50
51    pub fn is_empty(&self) -> bool {
52        self.inner.is_empty()
53    }
54
55    /// Removes the least recently used item from the cache.
56    pub fn remove_lru(&mut self) -> Option<T> {
57        self.inner.remove_lru().map(|(_, v)| v)
58    }
59
60    /// Clear all cached statements from the cache.
61    pub fn clear(&mut self) {
62        self.inner.clear();
63    }
64
65    /// True if cache has a value for the given key.
66    pub fn contains_key(&mut self, k: &str) -> bool {
67        self.inner.contains_key(k)
68    }
69
70    /// Returns the maximum number of statements the cache can hold.
71    pub fn capacity(&self) -> usize {
72        self.inner.capacity()
73    }
74
75    /// Returns true if the cache capacity is more than 0.
76    #[allow(dead_code)] // Only used for some `cfg`s
77    pub fn is_enabled(&self) -> bool {
78        self.capacity() > 0
79    }
80}