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    /// Inserts a new statement to the cache, returning the least recently used
25    /// statement id if the cache is full, or if inserting with an existing key,
26    /// the replaced existing statement.
27    pub fn insert(&mut self, k: &str, v: T) -> Option<T> {
28        let mut lru_item = None;
29
30        if self.capacity() == self.len() && !self.contains_key(k) {
31            lru_item = self.remove_lru();
32        } else if self.contains_key(k) {
33            lru_item = self.inner.remove(k);
34        }
35
36        self.inner.insert(k.into(), v);
37
38        lru_item
39    }
40
41    /// The number of statements in the cache.
42    pub fn len(&self) -> usize {
43        self.inner.len()
44    }
45
46    pub fn is_empty(&self) -> bool {
47        self.inner.is_empty()
48    }
49
50    /// Removes the least recently used item from the cache.
51    pub fn remove_lru(&mut self) -> Option<T> {
52        self.inner.remove_lru().map(|(_, v)| v)
53    }
54
55    /// Clear all cached statements from the cache.
56    pub fn clear(&mut self) {
57        self.inner.clear();
58    }
59
60    /// True if cache has a value for the given key.
61    pub fn contains_key(&mut self, k: &str) -> bool {
62        self.inner.contains_key(k)
63    }
64
65    /// Returns the maximum number of statements the cache can hold.
66    pub fn capacity(&self) -> usize {
67        self.inner.capacity()
68    }
69
70    /// Returns true if the cache capacity is more than 0.
71    #[allow(dead_code)] // Only used for some `cfg`s
72    pub fn is_enabled(&self) -> bool {
73        self.capacity() > 0
74    }
75}