Skip to main content

halephant_core/pool/
prepared.rs

1//! Global, reference-counted storage of `Parse` messages keyed by
2//! canonical name.
3//!
4//! The proxy's prepared-statement rewriter
5//! ([`crate::proxy::prepared`]) assigns each incoming client `Parse`
6//! a canonical name based on a hash of its query text and parameter
7//! types, then calls `StatementStore::add_ref` so every subsequent
8//! client that submits the same statement text shares a single
9//! entry. When a server connection is missing a canonical statement,
10//! the pool looks up the original `Parse` via [`StatementStore::get`]
11//! and replays it; when the last referencing client drops, the entry
12//! is reclaimed.
13
14use std::collections::HashMap;
15
16use crate::proto::frontend::Parse;
17
18/// Stores the original Parse messages keyed by canonical name, with reference
19/// counting. Entries are removed when no client references them.
20#[derive(Default)]
21pub struct StatementStore {
22    statements: HashMap<String, StoreEntry>,
23}
24
25struct StoreEntry {
26    parse: Parse,
27    refs: usize,
28}
29
30impl StatementStore {
31    pub fn new() -> Self {
32        Self::default()
33    }
34
35    /// Increment the reference count for a canonical name, inserting the Parse
36    /// if this is the first reference.
37    pub(crate) fn add_ref(&mut self, canon: String, mut parse: Parse) {
38        let entry = self.statements.entry(canon).or_insert_with(|| {
39            parse.name = String::new();
40            StoreEntry { parse, refs: 0 }
41        });
42        entry.refs += 1;
43    }
44
45    /// Decrement the reference count. Removes the entry when it reaches zero.
46    pub(crate) fn release(&mut self, canon: &str) {
47        if let Some(entry) = self.statements.get_mut(canon) {
48            entry.refs = entry.refs.saturating_sub(1);
49            if entry.refs == 0 {
50                self.statements.remove(canon);
51            }
52        }
53    }
54
55    /// Get the stored Parse for a canonical name.
56    pub fn get(&self, canon: &str) -> Option<&Parse> {
57        self.statements.get(canon).map(|e| &e.parse)
58    }
59}