Skip to main content

relate_core/
auto_literal.rs

1//! Bound `$__AUTO_*__` values visible to compile-time literal checks.
2//!
3//! The plan cache compiles the auto-parameterized statement (ADR-0503).
4//! Those placeholders stand for the literals they replaced, so a check
5//! that rejects a literal must reject the placeholder the same way. The
6//! map is installed for one parse or plan and restored on drop, including
7//! when that plan compiles a nested statement on the same thread.
8
9use std::cell::RefCell;
10use std::collections::BTreeMap;
11use std::sync::Arc;
12
13use crate::Value;
14
15thread_local! {
16    static AUTO_LITERALS: RefCell<Option<Arc<BTreeMap<String, Value>>>> = const { RefCell::new(None) };
17}
18
19/// Installs `params` for the guard's lifetime. A map with no `$__AUTO_*__`
20/// name installs nothing: a caller's own parameters stay runtime-typed.
21pub struct AutoLiteralGuard {
22    prev: Option<Arc<BTreeMap<String, Value>>>,
23}
24
25impl AutoLiteralGuard {
26    pub fn install(params: &BTreeMap<String, Value>) -> Self {
27        let next = params
28            .keys()
29            .any(|name| name.starts_with("__AUTO_"))
30            .then(|| Arc::new(params.clone()));
31        let prev = AUTO_LITERALS.with(|slot| slot.replace(next));
32        Self { prev }
33    }
34}
35
36impl Drop for AutoLiteralGuard {
37    fn drop(&mut self) {
38        let prev = self.prev.take();
39        AUTO_LITERALS.with(|slot| *slot.borrow_mut() = prev);
40    }
41}
42
43/// The literal a plan-cache placeholder stands for, when one is installed.
44/// Any other name, including a caller's parameter, is `None`.
45pub fn auto_literal(name: &str) -> Option<Value> {
46    if !name.starts_with("__AUTO_") {
47        return None;
48    }
49    AUTO_LITERALS.with(|slot| {
50        slot.borrow()
51            .as_ref()
52            .and_then(|map| map.get(name).cloned())
53    })
54}