glacier-web 0.4.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! SQL fragments with bound values, rendered per database.

use super::value::Value;

/// Which SQL dialect a connection speaks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Dialect {
    Postgres,
    Sqlite,
}

/// A SQL statement under construction: text interleaved with values that
/// become placeholders (`$1` on Postgres, `?1` on SQLite).
///
/// `Null` values are written inline as `NULL` rather than bound: Postgres
/// types every parameter, and a text-typed null can't go into an integer
/// column.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Sql {
    parts: Vec<Part>,
}

#[derive(Debug, Clone, PartialEq)]
enum Part {
    Text(String),
    Value(Value),
    /// Text that differs between databases.
    Dialect {
        postgres: String,
        sqlite: String,
    },
}

impl Sql {
    pub fn new() -> Self {
        Self::default()
    }

    /// Parses `text`, replacing each `?` (outside quotes) with the next
    /// value, so raw SQL is portable across databases.
    ///
    /// # Panics
    ///
    /// If the number of `?`s and values differ: that's a bug in the query.
    pub fn raw(text: &str, values: impl IntoIterator<Item = Value>) -> Self {
        let mut values = values.into_iter();
        let mut sql = Sql::new();
        let mut quote: Option<char> = None;
        let mut start = 0;
        for (i, c) in text.char_indices() {
            match (quote, c) {
                (None, '\'' | '"') => quote = Some(c),
                (Some(q), c) if c == q => quote = None,
                (None, '?') => {
                    sql.push(&text[start..i]);
                    let value = values
                        .next()
                        .unwrap_or_else(|| panic!("more `?` than values in `{text}`"));
                    sql.push_value(value);
                    start = i + 1;
                }
                _ => {}
            }
        }
        sql.push(&text[start..]);
        assert!(values.next().is_none(), "more values than `?` in `{text}`");
        sql
    }

    pub fn push(&mut self, text: &str) -> &mut Self {
        if text.is_empty() {
            return self;
        }
        match self.parts.last_mut() {
            Some(Part::Text(last)) => last.push_str(text),
            _ => self.parts.push(Part::Text(text.to_owned())),
        }
        self
    }

    /// Pushes a quoted identifier (table or column name).
    pub fn push_ident(&mut self, name: &str) -> &mut Self {
        self.push(&quote_ident(name))
    }

    /// Pushes text that differs between databases.
    pub fn push_dialect(&mut self, postgres: &str, sqlite: &str) -> &mut Self {
        self.parts.push(Part::Dialect {
            postgres: postgres.to_owned(),
            sqlite: sqlite.to_owned(),
        });
        self
    }

    pub fn push_value(&mut self, value: Value) -> &mut Self {
        self.parts.push(Part::Value(value));
        self
    }

    /// ` IN (…)` after a column, for `values`. On Postgres, a list of ids,
    /// text or UUIDs is ` = ANY($1)` with one array bound instead, so the
    /// statement's text, and its prepared statement, are the same however
    /// many values there are.
    pub fn push_in(&mut self, values: Vec<Value>) -> &mut Self {
        self.parts.push(Part::Value(Value::List(values)));
        self
    }

    pub fn append(&mut self, other: Sql) -> &mut Self {
        for part in other.parts {
            match part {
                Part::Text(text) => {
                    self.push(&text);
                }
                Part::Value(value) => {
                    self.push_value(value);
                }
                part @ Part::Dialect { .. } => self.parts.push(part),
            }
        }
        self
    }

    /// The final SQL text and the values to bind, in order.
    pub fn render(&self, dialect: Dialect) -> (String, Vec<Value>) {
        let mut text = String::new();
        let mut values = Vec::new();
        for part in &self.parts {
            match part {
                Part::Text(t) => text.push_str(t),
                Part::Dialect { postgres, sqlite } => text.push_str(match dialect {
                    Dialect::Postgres => postgres,
                    Dialect::Sqlite => sqlite,
                }),
                Part::Value(Value::Null) => text.push_str("NULL"),
                Part::Value(Value::List(items)) => {
                    let placeholder = |values: &mut Vec<Value>, value: Value| {
                        values.push(value);
                        let n = values.len();
                        match dialect {
                            Dialect::Postgres => format!("${n}"),
                            Dialect::Sqlite => format!("?{n}"),
                        }
                    };
                    if dialect == Dialect::Postgres && is_array_bindable(items) {
                        let p = placeholder(&mut values, Value::List(items.clone()));
                        text.push_str(&format!(" = ANY({p})"));
                    } else {
                        text.push_str(" IN (");
                        for (i, item) in items.iter().enumerate() {
                            if i > 0 {
                                text.push_str(", ");
                            }
                            if item.is_null() {
                                text.push_str("NULL");
                            } else {
                                let p = placeholder(&mut values, item.clone());
                                text.push_str(&p);
                            }
                        }
                        text.push(')');
                    }
                }
                Part::Value(value) => {
                    values.push(value.clone());
                    let n = values.len();
                    match dialect {
                        Dialect::Postgres => text.push_str(&format!("${n}")),
                        Dialect::Sqlite => text.push_str(&format!("?{n}")),
                    }
                }
            }
        }
        (text, values)
    }
}

/// Whether every value is an id, text or a UUID, all of one kind: what
/// Postgres can take as one array.
fn is_array_bindable(items: &[Value]) -> bool {
    let kind = |value: &Value| match value {
        Value::Int(_) => 1,
        Value::Text(_) => 2,
        Value::Uuid(_) => 3,
        _ => 0,
    };
    let first = items.first().map_or(0, kind);
    first != 0 && items.iter().all(|item| kind(item) == first)
}

/// Double-quotes an identifier; both Postgres and SQLite accept this.
pub fn quote_ident(name: &str) -> String {
    format!("\"{}\"", name.replace('"', "\"\""))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn renders_placeholders_per_dialect() {
        let sql = Sql::raw(
            "SELECT * FROM t WHERE a = ? AND b = '?' AND c = ? AND d = ?",
            [Value::Int(1), Value::Null, Value::Text("x".into())],
        );
        let (pg, values) = sql.render(Dialect::Postgres);
        assert_eq!(
            pg,
            "SELECT * FROM t WHERE a = $1 AND b = '?' AND c = NULL AND d = $2"
        );
        assert_eq!(values, [Value::Int(1), Value::Text("x".into())]);
        let (lite, _) = sql.render(Dialect::Sqlite);
        assert_eq!(
            lite,
            "SELECT * FROM t WHERE a = ?1 AND b = '?' AND c = NULL AND d = ?2"
        );
    }

    #[test]
    fn in_lists_are_one_array_on_postgres() {
        let list = |values: Vec<Value>| {
            let mut sql = Sql::new();
            sql.push("SELECT * FROM t WHERE id").push_in(values);
            sql
        };
        // The same text however many ids, so one prepared statement.
        for n in [1, 3, 40] {
            let ids: Vec<Value> = (1..=n).map(Value::Int).collect();
            let (pg, values) = list(ids.clone()).render(Dialect::Postgres);
            assert_eq!(pg, "SELECT * FROM t WHERE id = ANY($1)");
            assert_eq!(values, [Value::List(ids)]);
        }
        let (lite, values) = list(vec![Value::Int(1), Value::Int(2)]).render(Dialect::Sqlite);
        assert_eq!(lite, "SELECT * FROM t WHERE id IN (?1, ?2)");
        assert_eq!(values.len(), 2);
        // Mixed kinds, or a NULL, keep separate values.
        let (pg, _) = list(vec![Value::Int(1), Value::Text("a".into())]).render(Dialect::Postgres);
        assert_eq!(pg, "SELECT * FROM t WHERE id IN ($1, $2)");
        let (pg, _) = list(vec![Value::Int(1), Value::Null]).render(Dialect::Postgres);
        assert_eq!(pg, "SELECT * FROM t WHERE id IN ($1, NULL)");
    }

    #[test]
    fn quotes_identifiers() {
        assert_eq!(quote_ident("posts"), "\"posts\"");
        assert_eq!(quote_ident("we\"ird"), "\"we\"\"ird\"");
    }

    #[test]
    #[should_panic(expected = "more `?` than values")]
    fn rejects_missing_values() {
        Sql::raw("a = ? AND b = ?", [Value::Int(1)]);
    }
}