Skip to main content

glacier/db/
sql.rs

1//! SQL fragments with bound values, rendered per database.
2
3use super::value::Value;
4
5/// Which SQL dialect a connection speaks.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum Dialect {
8    Postgres,
9    Sqlite,
10}
11
12/// A SQL statement under construction: text interleaved with values that
13/// become placeholders (`$1` on Postgres, `?1` on SQLite).
14///
15/// `Null` values are written inline as `NULL` rather than bound: Postgres
16/// types every parameter, and a text-typed null can't go into an integer
17/// column.
18#[derive(Debug, Clone, Default, PartialEq)]
19pub struct Sql {
20    parts: Vec<Part>,
21}
22
23#[derive(Debug, Clone, PartialEq)]
24enum Part {
25    Text(String),
26    Value(Value),
27    /// Text that differs between databases.
28    Dialect {
29        postgres: String,
30        sqlite: String,
31    },
32}
33
34impl Sql {
35    pub fn new() -> Self {
36        Self::default()
37    }
38
39    /// Parses `text`, replacing each `?` (outside quotes) with the next
40    /// value, so raw SQL is portable across databases.
41    ///
42    /// # Panics
43    ///
44    /// If the number of `?`s and values differ: that's a bug in the query.
45    pub fn raw(text: &str, values: impl IntoIterator<Item = Value>) -> Self {
46        let mut values = values.into_iter();
47        let mut sql = Sql::new();
48        let mut quote: Option<char> = None;
49        let mut start = 0;
50        for (i, c) in text.char_indices() {
51            match (quote, c) {
52                (None, '\'' | '"') => quote = Some(c),
53                (Some(q), c) if c == q => quote = None,
54                (None, '?') => {
55                    sql.push(&text[start..i]);
56                    let value = values
57                        .next()
58                        .unwrap_or_else(|| panic!("more `?` than values in `{text}`"));
59                    sql.push_value(value);
60                    start = i + 1;
61                }
62                _ => {}
63            }
64        }
65        sql.push(&text[start..]);
66        assert!(values.next().is_none(), "more values than `?` in `{text}`");
67        sql
68    }
69
70    pub fn push(&mut self, text: &str) -> &mut Self {
71        if text.is_empty() {
72            return self;
73        }
74        match self.parts.last_mut() {
75            Some(Part::Text(last)) => last.push_str(text),
76            _ => self.parts.push(Part::Text(text.to_owned())),
77        }
78        self
79    }
80
81    /// Pushes a quoted identifier (table or column name).
82    pub fn push_ident(&mut self, name: &str) -> &mut Self {
83        self.push(&quote_ident(name))
84    }
85
86    /// Pushes text that differs between databases.
87    pub fn push_dialect(&mut self, postgres: &str, sqlite: &str) -> &mut Self {
88        self.parts.push(Part::Dialect {
89            postgres: postgres.to_owned(),
90            sqlite: sqlite.to_owned(),
91        });
92        self
93    }
94
95    pub fn push_value(&mut self, value: Value) -> &mut Self {
96        self.parts.push(Part::Value(value));
97        self
98    }
99
100    /// ` IN (…)` after a column, for `values`. On Postgres, a list of ids,
101    /// text or UUIDs is ` = ANY($1)` with one array bound instead, so the
102    /// statement's text, and its prepared statement, are the same however
103    /// many values there are.
104    pub fn push_in(&mut self, values: Vec<Value>) -> &mut Self {
105        self.parts.push(Part::Value(Value::List(values)));
106        self
107    }
108
109    pub fn append(&mut self, other: Sql) -> &mut Self {
110        for part in other.parts {
111            match part {
112                Part::Text(text) => {
113                    self.push(&text);
114                }
115                Part::Value(value) => {
116                    self.push_value(value);
117                }
118                part @ Part::Dialect { .. } => self.parts.push(part),
119            }
120        }
121        self
122    }
123
124    /// The final SQL text and the values to bind, in order.
125    pub fn render(&self, dialect: Dialect) -> (String, Vec<Value>) {
126        let mut text = String::new();
127        let mut values = Vec::new();
128        for part in &self.parts {
129            match part {
130                Part::Text(t) => text.push_str(t),
131                Part::Dialect { postgres, sqlite } => text.push_str(match dialect {
132                    Dialect::Postgres => postgres,
133                    Dialect::Sqlite => sqlite,
134                }),
135                Part::Value(Value::Null) => text.push_str("NULL"),
136                Part::Value(Value::List(items)) => {
137                    let placeholder = |values: &mut Vec<Value>, value: Value| {
138                        values.push(value);
139                        let n = values.len();
140                        match dialect {
141                            Dialect::Postgres => format!("${n}"),
142                            Dialect::Sqlite => format!("?{n}"),
143                        }
144                    };
145                    if dialect == Dialect::Postgres && is_array_bindable(items) {
146                        let p = placeholder(&mut values, Value::List(items.clone()));
147                        text.push_str(&format!(" = ANY({p})"));
148                    } else {
149                        text.push_str(" IN (");
150                        for (i, item) in items.iter().enumerate() {
151                            if i > 0 {
152                                text.push_str(", ");
153                            }
154                            if item.is_null() {
155                                text.push_str("NULL");
156                            } else {
157                                let p = placeholder(&mut values, item.clone());
158                                text.push_str(&p);
159                            }
160                        }
161                        text.push(')');
162                    }
163                }
164                Part::Value(value) => {
165                    values.push(value.clone());
166                    let n = values.len();
167                    match dialect {
168                        Dialect::Postgres => text.push_str(&format!("${n}")),
169                        Dialect::Sqlite => text.push_str(&format!("?{n}")),
170                    }
171                }
172            }
173        }
174        (text, values)
175    }
176}
177
178/// Whether every value is an id, text or a UUID, all of one kind: what
179/// Postgres can take as one array.
180fn is_array_bindable(items: &[Value]) -> bool {
181    let kind = |value: &Value| match value {
182        Value::Int(_) => 1,
183        Value::Text(_) => 2,
184        Value::Uuid(_) => 3,
185        _ => 0,
186    };
187    let first = items.first().map_or(0, kind);
188    first != 0 && items.iter().all(|item| kind(item) == first)
189}
190
191/// Double-quotes an identifier; both Postgres and SQLite accept this.
192pub fn quote_ident(name: &str) -> String {
193    format!("\"{}\"", name.replace('"', "\"\""))
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199
200    #[test]
201    fn renders_placeholders_per_dialect() {
202        let sql = Sql::raw(
203            "SELECT * FROM t WHERE a = ? AND b = '?' AND c = ? AND d = ?",
204            [Value::Int(1), Value::Null, Value::Text("x".into())],
205        );
206        let (pg, values) = sql.render(Dialect::Postgres);
207        assert_eq!(
208            pg,
209            "SELECT * FROM t WHERE a = $1 AND b = '?' AND c = NULL AND d = $2"
210        );
211        assert_eq!(values, [Value::Int(1), Value::Text("x".into())]);
212        let (lite, _) = sql.render(Dialect::Sqlite);
213        assert_eq!(
214            lite,
215            "SELECT * FROM t WHERE a = ?1 AND b = '?' AND c = NULL AND d = ?2"
216        );
217    }
218
219    #[test]
220    fn in_lists_are_one_array_on_postgres() {
221        let list = |values: Vec<Value>| {
222            let mut sql = Sql::new();
223            sql.push("SELECT * FROM t WHERE id").push_in(values);
224            sql
225        };
226        // The same text however many ids, so one prepared statement.
227        for n in [1, 3, 40] {
228            let ids: Vec<Value> = (1..=n).map(Value::Int).collect();
229            let (pg, values) = list(ids.clone()).render(Dialect::Postgres);
230            assert_eq!(pg, "SELECT * FROM t WHERE id = ANY($1)");
231            assert_eq!(values, [Value::List(ids)]);
232        }
233        let (lite, values) = list(vec![Value::Int(1), Value::Int(2)]).render(Dialect::Sqlite);
234        assert_eq!(lite, "SELECT * FROM t WHERE id IN (?1, ?2)");
235        assert_eq!(values.len(), 2);
236        // Mixed kinds, or a NULL, keep separate values.
237        let (pg, _) = list(vec![Value::Int(1), Value::Text("a".into())]).render(Dialect::Postgres);
238        assert_eq!(pg, "SELECT * FROM t WHERE id IN ($1, $2)");
239        let (pg, _) = list(vec![Value::Int(1), Value::Null]).render(Dialect::Postgres);
240        assert_eq!(pg, "SELECT * FROM t WHERE id IN ($1, NULL)");
241    }
242
243    #[test]
244    fn quotes_identifiers() {
245        assert_eq!(quote_ident("posts"), "\"posts\"");
246        assert_eq!(quote_ident("we\"ird"), "\"we\"\"ird\"");
247    }
248
249    #[test]
250    #[should_panic(expected = "more `?` than values")]
251    fn rejects_missing_values() {
252        Sql::raw("a = ? AND b = ?", [Value::Int(1)]);
253    }
254}