glacier-web 0.1.0

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
    }

    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) => {
                    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)
    }
}

/// 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 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)]);
    }
}