Skip to main content

orbit_orm/
driver.rs

1//! The databases Orbit supports, and what differs between them in SQL.
2//!
3//! Each database is a Cargo feature: `mysql` (the default), `postgres` and `sqlite`. Only the
4//! enabled ones exist in the build, so a crate built with `sqlite` alone has no MySQL types.
5
6use sqlx::FromRow;
7
8use crate::Value;
9
10/// A database that Orbit can talk to. The variants are the enabled Cargo features.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12pub enum Driver {
13    /// MySQL and MariaDB.
14    #[cfg(feature = "mysql")]
15    MySql,
16    /// PostgreSQL.
17    #[cfg(feature = "postgres")]
18    Postgres,
19    /// SQLite, in a file or in memory.
20    #[cfg(feature = "sqlite")]
21    Sqlite,
22}
23
24impl Driver {
25    /// The name of the database, for messages.
26    pub fn name(self) -> &'static str {
27        match self {
28            #[cfg(feature = "mysql")]
29            Self::MySql => "MySQL",
30            #[cfg(feature = "postgres")]
31            Self::Postgres => "PostgreSQL",
32            #[cfg(feature = "sqlite")]
33            Self::Sqlite => "SQLite",
34        }
35    }
36
37    /// Quotes a table or column name. The name is checked by the caller: it is never empty and
38    /// has no quote character.
39    pub(crate) fn quote(self, name: &str) -> String {
40        match self {
41            #[cfg(feature = "mysql")]
42            Self::MySql => format!("`{name}`"),
43            #[cfg(any(feature = "postgres", feature = "sqlite"))]
44            _ => format!("\"{name}\""),
45        }
46    }
47
48    /// The placeholder for the `n`th bound value, counted from 1. PostgreSQL numbers them;
49    /// MySQL and SQLite take `?`.
50    #[cfg_attr(not(feature = "postgres"), allow(unused_variables))]
51    pub(crate) fn placeholder(self, n: usize) -> String {
52        match self {
53            #[cfg(feature = "mysql")]
54            Self::MySql => "?".to_owned(),
55            #[cfg(feature = "postgres")]
56            Self::Postgres => format!("${n}"),
57            #[cfg(feature = "sqlite")]
58            Self::Sqlite => "?".to_owned(),
59        }
60    }
61
62    /// The clause that locks the selected rows, or nothing. SQLite has no row locks: its writers
63    /// are serialised by the database, so the clause is left out, as Laravel's SQLite grammar
64    /// does.
65    pub(crate) fn lock_clause(self) -> &'static str {
66        match self {
67            #[cfg(feature = "mysql")]
68            Self::MySql => " FOR UPDATE",
69            #[cfg(feature = "postgres")]
70            Self::Postgres => " FOR UPDATE",
71            #[cfg(feature = "sqlite")]
72            Self::Sqlite => "",
73        }
74    }
75
76    /// The `LIMIT` that an `OFFSET` without a `LIMIT` needs. MySQL and SQLite require one;
77    /// PostgreSQL does not.
78    pub(crate) fn offset_only_limit(self) -> Option<&'static str> {
79        match self {
80            #[cfg(feature = "mysql")]
81            Self::MySql => Some("18446744073709551615"),
82            #[cfg(feature = "postgres")]
83            Self::Postgres => None,
84            #[cfg(feature = "sqlite")]
85            Self::Sqlite => Some("-1"),
86        }
87    }
88
89    /// The part of an `INSERT` that has no columns.
90    pub(crate) fn empty_insert(self) -> &'static str {
91        match self {
92            #[cfg(feature = "mysql")]
93            Self::MySql => "() VALUES ()",
94            #[cfg(any(feature = "postgres", feature = "sqlite"))]
95            _ => "DEFAULT VALUES",
96        }
97    }
98
99    /// The integer type for a `CAST`, wide enough for a count.
100    pub(crate) fn bigint(self) -> &'static str {
101        match self {
102            #[cfg(feature = "mysql")]
103            Self::MySql => "SIGNED",
104            #[cfg(feature = "postgres")]
105            Self::Postgres => "BIGINT",
106            #[cfg(feature = "sqlite")]
107            Self::Sqlite => "INTEGER",
108        }
109    }
110
111    /// The `LIKE` comparison on a quoted column, before its placeholder. Laravel's `whereLike` is
112    /// case-insensitive by default: MySQL and SQLite take `LIKE`, which ignores case there, and
113    /// PostgreSQL takes `ILIKE` on the column cast to text, as Laravel's PostgreSQL grammar does.
114    pub(crate) fn like(self, column: &str) -> String {
115        match self {
116            #[cfg(feature = "mysql")]
117            Self::MySql => format!("{column} LIKE"),
118            #[cfg(feature = "postgres")]
119            Self::Postgres => format!("{column}::text ILIKE"),
120            #[cfg(feature = "sqlite")]
121            Self::Sqlite => format!("{column} LIKE"),
122        }
123    }
124
125    /// Whether `replace` can run. MySQL and SQLite have `REPLACE INTO`; PostgreSQL has no such
126    /// statement, and `INSERT ... ON CONFLICT` would not delete the old row, so it is refused.
127    pub(crate) fn supports_replace(self) -> bool {
128        match self {
129            #[cfg(feature = "mysql")]
130            Self::MySql => true,
131            #[cfg(feature = "postgres")]
132            Self::Postgres => false,
133            #[cfg(feature = "sqlite")]
134            Self::Sqlite => true,
135        }
136    }
137
138    /// Whether a `NULL` value is written into the SQL, not bound. PostgreSQL types a bound
139    /// parameter, so a bound `NULL` would not fit every column; a literal `NULL` fits any.
140    pub(crate) fn inlines_null(self) -> bool {
141        match self {
142            #[cfg(feature = "mysql")]
143            Self::MySql => false,
144            #[cfg(feature = "postgres")]
145            Self::Postgres => true,
146            #[cfg(feature = "sqlite")]
147            Self::Sqlite => false,
148        }
149    }
150
151    /// Whether the insert id comes from `RETURNING` (PostgreSQL), not from the statement result.
152    pub(crate) fn insert_returns_id(self) -> bool {
153        match self {
154            #[cfg(feature = "mysql")]
155            Self::MySql => false,
156            #[cfg(feature = "postgres")]
157            Self::Postgres => true,
158            #[cfg(feature = "sqlite")]
159            Self::Sqlite => false,
160        }
161    }
162
163    /// Prepares a raw statement: `?` placeholders become this driver's placeholders, and the
164    /// values are the ones that stay bound. On PostgreSQL a `NULL` is written into the SQL, as
165    /// for the query builder, so it is not bound. Question marks inside quotes are left alone.
166    pub(crate) fn prepare(self, sql: &str, binds: &[Value]) -> (String, Vec<Value>) {
167        match self {
168            #[cfg(feature = "mysql")]
169            Self::MySql => (sql.to_owned(), binds.to_vec()),
170            #[cfg(feature = "postgres")]
171            Self::Postgres => prepare_postgres(sql, binds),
172            #[cfg(feature = "sqlite")]
173            Self::Sqlite => (sql.to_owned(), binds.to_vec()),
174        }
175    }
176}
177
178/// Numbers the `?` placeholders of `sql` as `$1`, `$2`, ..., skipping any inside a string,
179/// identifier or comment. A placeholder whose value is `NULL` becomes the literal `NULL`.
180#[cfg(feature = "postgres")]
181fn prepare_postgres(sql: &str, binds: &[Value]) -> (String, Vec<Value>) {
182    let mut out = String::with_capacity(sql.len() + 8);
183    let mut kept = Vec::new();
184    let mut seen = 0usize;
185    let mut chars = sql.chars().peekable();
186    let mut quote: Option<char> = None;
187    while let Some(c) = chars.next() {
188        match quote {
189            Some(q) => {
190                out.push(c);
191                if c == q {
192                    quote = None;
193                }
194            }
195            None => match c {
196                '\'' | '"' => {
197                    quote = Some(c);
198                    out.push(c);
199                }
200                '-' if chars.peek() == Some(&'-') => {
201                    out.push(c);
202                    for next in chars.by_ref() {
203                        out.push(next);
204                        if next == '\n' {
205                            break;
206                        }
207                    }
208                }
209                '?' => {
210                    let value = binds.get(seen).cloned().unwrap_or(Value::Null);
211                    seen += 1;
212                    if matches!(value, Value::Null) {
213                        out.push_str("NULL");
214                    } else {
215                        kept.push(value);
216                        out.push_str(&format!("${}", kept.len()));
217                    }
218                }
219                _ => out.push(c),
220            },
221        }
222    }
223    (out, kept)
224}
225
226/// Row decoding for each enabled driver. A model must decode from every enabled database's row
227/// type, so `Model` bounds on these. Each trait is implemented for every type when its driver is
228/// not enabled, so it adds nothing to the bound then.
229#[doc(hidden)]
230pub mod rows {
231    #[cfg(feature = "mysql")]
232    pub trait RowMySql: for<'r> super::FromRow<'r, sqlx::mysql::MySqlRow> {}
233    #[cfg(feature = "mysql")]
234    impl<T: for<'r> super::FromRow<'r, sqlx::mysql::MySqlRow>> RowMySql for T {}
235    #[cfg(not(feature = "mysql"))]
236    pub trait RowMySql {}
237    #[cfg(not(feature = "mysql"))]
238    impl<T> RowMySql for T {}
239
240    #[cfg(feature = "postgres")]
241    pub trait RowPostgres: for<'r> super::FromRow<'r, sqlx::postgres::PgRow> {}
242    #[cfg(feature = "postgres")]
243    impl<T: for<'r> super::FromRow<'r, sqlx::postgres::PgRow>> RowPostgres for T {}
244    #[cfg(not(feature = "postgres"))]
245    pub trait RowPostgres {}
246    #[cfg(not(feature = "postgres"))]
247    impl<T> RowPostgres for T {}
248
249    #[cfg(feature = "sqlite")]
250    pub trait RowSqlite: for<'r> super::FromRow<'r, sqlx::sqlite::SqliteRow> {}
251    #[cfg(feature = "sqlite")]
252    impl<T: for<'r> super::FromRow<'r, sqlx::sqlite::SqliteRow>> RowSqlite for T {}
253    #[cfg(not(feature = "sqlite"))]
254    pub trait RowSqlite {}
255    #[cfg(not(feature = "sqlite"))]
256    impl<T> RowSqlite for T {}
257
258    /// Decodes from every enabled driver's row type.
259    pub trait DriverRows: RowMySql + RowPostgres + RowSqlite {}
260    impl<T: RowMySql + RowPostgres + RowSqlite> DriverRows for T {}
261}
262
263#[cfg(not(any(feature = "mysql", feature = "postgres", feature = "sqlite")))]
264compile_error!("orbit-orm needs at least one database feature: mysql, postgres or sqlite");