Skip to main content

reylo_engine_core/
host.rs

1//! The engine's view of the database: answers the host already gave, and the needs it records
2//! for the ones it has not. A lookup that misses records the need and answers `None`, and the
3//! caller goes on with whatever else it can do this round, so one round collects every need
4//! that does not depend on another's answer.
5//!
6//! The host is generic over what a `describe` need is answered with, which is the database's own:
7//! Postgres's Parse/Describe, MySQL's prepare metadata, nothing for SQLite, which prepares inside
8//! the engine. Each database crate names its host once (`pub type Host<'a> = …`).
9
10use crate::api::{Answer, Answers, DbError, Describe, Need, Scope};
11use serde_json::Value;
12use std::cell::RefCell;
13
14pub struct Host<'a, D> {
15    answers: &'a Answers<D>,
16    needs: RefCell<Vec<Need>>,
17}
18
19/// `None` is "not answered yet"; the need is recorded.
20pub type Lazy<T> = Option<T>;
21
22impl<'a, D: Describe> Host<'a, D> {
23    pub fn new(answers: &'a Answers<D>) -> Host<'a, D> {
24        Host { answers, needs: RefCell::new(Vec::new()) }
25    }
26
27    /// Run `f` over these answers on the engine's stack ([`crate::stack`]), with the needs it
28    /// records recorded here.
29    pub fn on_engine_stack<T: Send>(&self, f: impl FnOnce(&Host<'_, D>) -> T + Send) -> T {
30        let answers = self.answers;
31        let (value, needs) = crate::stack::run(move || {
32            let host = Host::new(answers);
33            let value = f(&host);
34            (value, host.needs.into_inner())
35        });
36        for need in needs {
37            self.record(need);
38        }
39        value
40    }
41
42    pub fn needs(&self) -> Vec<Need> {
43        self.needs.borrow().clone()
44    }
45
46    pub fn pending(&self) -> bool {
47        !self.needs.borrow().is_empty()
48    }
49
50    fn record(&self, need: Need) {
51        let mut needs = self.needs.borrow_mut();
52        if !needs.contains(&need) {
53            needs.push(need);
54        }
55    }
56
57    /// The database's describe of `sql`: its own payload, or the error the database answered with.
58    pub fn describe(&self, sql: &str) -> Lazy<Result<D, DbError>> {
59        let id = format!("describe:{sql}");
60        match self.answers.get(&id) {
61            Some(Answer::Describe { describe }) => Some(Ok(describe.clone())),
62            Some(Answer::Error { error }) => Some(Err(error.clone())),
63            Some(Answer::Rows { .. }) => Some(Err(DbError { message: "the host answered a describe with something else".into(), code: None, position: None })),
64            None => {
65                self.record(Need::Describe { id, sql: sql.to_string() });
66                None
67            }
68        }
69    }
70
71    pub fn query(&self, sql: &str, params: Vec<Value>, scope: Scope) -> Lazy<Result<Vec<Vec<Value>>, DbError>> {
72        let id = format!("query:{sql}|{}", serde_json::to_string(&params).unwrap_or_default());
73        match self.answers.get(&id) {
74            Some(Answer::Rows { rows }) => Some(Ok(rows.clone())),
75            Some(Answer::Error { error }) => Some(Err(error.clone())),
76            Some(Answer::Describe { .. }) => Some(Err(DbError { message: "the host answered a query with a describe".into(), code: None, position: None })),
77            None => {
78                self.record(Need::Query { id, sql: sql.to_string(), params, scope });
79                None
80            }
81        }
82    }
83
84    /// A catalog query asked once per set of parameters, its rows together: the host keeps the
85    /// answers by what each asks, so what a later statement asks again of the same relation costs
86    /// no round trip, where a list of a statement's own relations would be a new question each time.
87    /// `None` until each is answered; the first error otherwise.
88    pub fn query_each(&self, sql: &str, each: impl IntoIterator<Item = Vec<Value>>, scope: Scope) -> Lazy<Result<Vec<Vec<Value>>, DbError>> {
89        let mut asked = Vec::new();
90        let (mut rows, mut error, mut pending) = (Vec::new(), None, false);
91        for params in each {
92            if asked.contains(&params) {
93                continue;
94            }
95            asked.push(params.clone());
96            match self.query(sql, params, scope) {
97                Some(Ok(found)) => rows.extend(found),
98                Some(Err(e)) => error = error.or(Some(e)),
99                None => pending = true,
100            }
101        }
102        if pending {
103            return None;
104        }
105        Some(error.map_or(Ok(rows), Err))
106    }
107}
108
109/// A number the driver may have decoded as a JSON number or, for `int8`, as a string.
110pub fn as_u32(v: &Value) -> Option<u32> {
111    match v {
112        Value::Number(n) => n.as_u64().map(|n| n as u32),
113        Value::String(s) => s.parse().ok(),
114        _ => None,
115    }
116}
117
118pub fn as_str(v: &Value) -> Option<&str> {
119    v.as_str()
120}
121
122pub fn as_bool(v: &Value) -> Option<bool> {
123    match v {
124        Value::Bool(b) => Some(*b),
125        Value::String(s) => match s.as_str() {
126            "t" | "true" => Some(true),
127            "f" | "false" => Some(false),
128            _ => None,
129        },
130        _ => None,
131    }
132}
133
134pub fn as_strings(v: &Value) -> Option<Vec<String>> {
135    match v {
136        Value::Array(items) => items.iter().map(|i| i.as_str().map(String::from)).collect(),
137        Value::Null => None,
138        _ => None,
139    }
140}