Skip to main content

navree_orm/sql/
mod.rs

1//! SQL for PostgreSQL / TimescaleDB, MySQL and SQLite: the [`Dialect`]s,
2//! the [`Statement`]s the ORM runs, and the functions that write the IR as
3//! statements ([`render_select`], [`render_insert`], ...).
4//!
5//! The SQL is navree-orm's own: the IR is lowered into the
6//! [render tree](crate::render::ast) and written by the dialect's
7//! [grammar](crate::render::grammar), which quotes identifiers, binds every
8//! value and numbers the placeholders (`$n` on PostgreSQL, `?` elsewhere).
9
10use std::fmt;
11
12use navree_db::Backend;
13
14use crate::error::OrmError;
15use crate::ir::Where;
16use crate::value::Value;
17
18pub(crate) use crate::render::grammar::is_identifier;
19pub(crate) use crate::render::lower::timeout_millis;
20pub use crate::render::{
21    render_aggregate, render_delete, render_exists, render_insert, render_select, render_truncate,
22    render_update, render_update_from,
23};
24
25/// An SQL dialect.
26///
27/// TimescaleDB is PostgreSQL with the extension: its helpers
28/// (`time_bucket`, `first`, `last`) compile on [`Dialect::Postgres`].
29#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
30pub enum Dialect {
31    /// PostgreSQL and TimescaleDB.
32    Postgres,
33    /// MySQL and MariaDB.
34    MySql,
35    /// SQLite.
36    Sqlite,
37}
38
39impl Dialect {
40    /// navree-db's backend of this dialect.
41    pub fn backend(self) -> Backend {
42        match self {
43            Dialect::Postgres => Backend::Postgres,
44            Dialect::MySql => Backend::MySql,
45            Dialect::Sqlite => Backend::Sqlite,
46        }
47    }
48
49    /// The database's name in messages.
50    pub fn name(self) -> &'static str {
51        match self {
52            Dialect::Postgres => "PostgreSQL",
53            Dialect::MySql => "MySQL",
54            Dialect::Sqlite => "SQLite",
55        }
56    }
57
58    /// Whether `INSERT`, `UPDATE` and `DELETE` can return rows.
59    pub fn supports_returning(self) -> bool {
60        !matches!(self, Dialect::MySql)
61    }
62
63    /// The most values one statement can bind: 65,535 on PostgreSQL and
64    /// MySQL, 32,766 on SQLite. Multi-row inserts are split to stay under
65    /// it.
66    pub fn max_bind_values(self) -> usize {
67        match self {
68            Dialect::Postgres | Dialect::MySql => 65_535,
69            Dialect::Sqlite => 32_766,
70        }
71    }
72
73    /// `name` quoted as an identifier (`"deals"`, `` `deals` ``), each part
74    /// of a schema-qualified name on its own.
75    ///
76    /// ```
77    /// use navree_orm::Dialect;
78    ///
79    /// assert_eq!(Dialect::Postgres.quote_identifier("audit.events"), r#""audit"."events""#);
80    /// assert_eq!(Dialect::MySql.quote_identifier("odd`name"), "`odd``name`");
81    /// ```
82    pub fn quote_identifier(self, name: &str) -> String {
83        quote_identifier(name, self)
84    }
85}
86
87/// `name` quoted as an identifier for `dialect`.
88pub(crate) fn quote_identifier(name: &str, dialect: Dialect) -> String {
89    let quote = match dialect {
90        Dialect::MySql => '`',
91        Dialect::Postgres | Dialect::Sqlite => '"',
92    };
93    name.split('.')
94        .map(|part| {
95            let escaped = part.replace(quote, &format!("{quote}{quote}"));
96            format!("{quote}{escaped}{quote}")
97        })
98        .collect::<Vec<_>>()
99        .join(".")
100}
101
102/// The dialect a navree-db backend speaks.
103///
104/// ```
105/// use navree_db::Backend;
106/// use navree_orm::Dialect;
107///
108/// assert_eq!(Dialect::from(Backend::MySql), Dialect::MySql);
109/// assert_eq!(Dialect::Postgres.backend(), Backend::Postgres);
110/// ```
111impl From<Backend> for Dialect {
112    fn from(backend: Backend) -> Self {
113        match backend {
114            Backend::Postgres => Dialect::Postgres,
115            Backend::MySql => Dialect::MySql,
116            Backend::Sqlite => Dialect::Sqlite,
117        }
118    }
119}
120
121impl From<Dialect> for Backend {
122    fn from(dialect: Dialect) -> Self {
123        dialect.backend()
124    }
125}
126
127impl fmt::Display for Dialect {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        f.write_str(self.name())
130    }
131}
132
133/// The SQL a statement is written in: a [`Dialect`], and on MySQL's
134/// whether the server is MariaDB (and which version), where its SQL
135/// differs from MySQL 8's. A [`Dialect`] converts into its own syntax
136/// (MySQL's is MySQL 8's); the ORM asks a [`navree_db::Db`] once which it
137/// is.
138///
139/// On MariaDB a JSON value is `JSON_EXTRACT(?, '$')` (there is no `CAST(..
140/// AS JSON)`), a shared lock is always `LOCK IN SHARE MODE`, a regular
141/// expression is `REGEXP` with its case flag in the pattern, and a time
142/// limit is `SET STATEMENT max_statement_time = .. FOR`. What MariaDB
143/// lacks is refused: lateral joins, locks of named tables, indexes from
144/// the end of a JSON array (MariaDB 10.9 to 11.4 answer them wrongly), and
145/// before 10.9 `json_overlaps`, before 11.7 vector distances.
146///
147/// ```
148/// use navree_orm::{Dialect, Syntax};
149///
150/// let mariadb = Syntax::mariadb(11, 4);
151/// assert_eq!(mariadb.dialect(), Dialect::MySql);
152/// assert_eq!(mariadb.name(), "MariaDB");
153/// assert_eq!(Syntax::from(Dialect::MySql).mariadb_version(), None);
154/// ```
155#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
156pub struct Syntax {
157    dialect: Dialect,
158    mariadb: Option<(u16, u16)>,
159}
160
161impl Syntax {
162    /// MariaDB `major.minor` (MySQL's dialect).
163    pub fn mariadb(major: u16, minor: u16) -> Syntax {
164        Syntax {
165            dialect: Dialect::MySql,
166            mariadb: Some((major, minor)),
167        }
168    }
169
170    /// The syntax of a server of `dialect`: MariaDB's when `mariadb` holds
171    /// its version (on MySQL's dialect only).
172    pub fn of(dialect: Dialect, mariadb: Option<(u16, u16)>) -> Syntax {
173        match (dialect, mariadb) {
174            (Dialect::MySql, Some((major, minor))) => Syntax::mariadb(major, minor),
175            (dialect, _) => Syntax::from(dialect),
176        }
177    }
178
179    /// The dialect.
180    pub fn dialect(self) -> Dialect {
181        self.dialect
182    }
183
184    /// The MariaDB version, `None` on other servers.
185    pub fn mariadb_version(self) -> Option<(u16, u16)> {
186        self.mariadb
187    }
188
189    /// Whether the server is MariaDB.
190    pub fn is_mariadb(self) -> bool {
191        self.mariadb.is_some()
192    }
193
194    /// Whether the server is a MariaDB older than `major.minor`.
195    pub(crate) fn mariadb_before(self, major: u16, minor: u16) -> bool {
196        self.mariadb.is_some_and(|version| version < (major, minor))
197    }
198
199    /// The database's name in messages: `MariaDB`, else the dialect's.
200    pub fn name(self) -> &'static str {
201        if self.is_mariadb() {
202            "MariaDB"
203        } else {
204            self.dialect.name()
205        }
206    }
207}
208
209impl From<Dialect> for Syntax {
210    fn from(dialect: Dialect) -> Self {
211        Syntax {
212            dialect,
213            mariadb: None,
214        }
215    }
216}
217
218impl fmt::Display for Syntax {
219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220        match self.mariadb {
221            Some((major, minor)) => write!(f, "MariaDB {major}.{minor}"),
222            None => f.write_str(self.dialect.name()),
223        }
224    }
225}
226
227/// A compiled statement: SQL with placeholders and the values bound to
228/// them.
229#[derive(Clone, Debug, PartialEq)]
230pub struct Statement {
231    /// The SQL (`$1` placeholders on PostgreSQL, `?` elsewhere).
232    pub sql: String,
233    /// The bound values, in placeholder order.
234    pub values: Vec<Value>,
235    /// The dialect it was compiled for.
236    pub dialect: Dialect,
237}
238
239impl Statement {
240    /// The statement as navree-db runs it (its SQL, written in the
241    /// dialect's own placeholders, and its values).
242    pub fn to_db(&self) -> navree_db::Statement {
243        navree_db::Statement::new(
244            self.dialect.backend(),
245            self.sql.clone(),
246            self.values.clone(),
247        )
248    }
249}
250
251impl From<Statement> for navree_db::Statement {
252    fn from(statement: Statement) -> Self {
253        navree_db::Statement::new(statement.dialect.backend(), statement.sql, statement.values)
254    }
255}
256
257impl fmt::Display for Statement {
258    /// The SQL followed by the values, one statement per line:
259    /// `SELECT ... WHERE "id" = $1 -- [I64(1)]`.
260    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261        f.write_str(&self.sql)?;
262        if !self.values.is_empty() {
263            write!(f, " -- {:?}", self.values)?;
264        }
265        Ok(())
266    }
267}
268
269/// A filter alone, as `WHERE` would hold it (for tests and debugging).
270pub(crate) fn render_filter(filter: &Where, dialect: Dialect) -> Result<Statement, OrmError> {
271    let condition = crate::render::lower::Lowerer::new(dialect).where_(filter)?;
272    crate::render::render_expr(&condition, dialect)
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278
279    #[test]
280    fn identifiers() {
281        assert!(is_identifier("time_bucket"));
282        assert!(is_identifier("public.my_fn"));
283        assert!(!is_identifier("drop table x; --"));
284        assert!(!is_identifier("1abc"));
285        assert!(!is_identifier(""));
286    }
287
288    #[test]
289    fn filters_render_alone() {
290        let filter = Where::Raw {
291            sql: "a = ?".into(),
292            values: vec![Value::from(1)],
293        };
294        let statement = render_filter(&filter, Dialect::Postgres).unwrap();
295        assert_eq!(statement.sql, "a = $1");
296        assert_eq!(statement.values, [Value::from(1)]);
297    }
298}