1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
30pub enum Dialect {
31 Postgres,
33 MySql,
35 Sqlite,
37}
38
39impl Dialect {
40 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 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 pub fn supports_returning(self) -> bool {
60 !matches!(self, Dialect::MySql)
61 }
62
63 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 pub fn quote_identifier(self, name: &str) -> String {
83 quote_identifier(name, self)
84 }
85}
86
87pub(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
102impl 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
156pub struct Syntax {
157 dialect: Dialect,
158 mariadb: Option<(u16, u16)>,
159}
160
161impl Syntax {
162 pub fn mariadb(major: u16, minor: u16) -> Syntax {
164 Syntax {
165 dialect: Dialect::MySql,
166 mariadb: Some((major, minor)),
167 }
168 }
169
170 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 pub fn dialect(self) -> Dialect {
181 self.dialect
182 }
183
184 pub fn mariadb_version(self) -> Option<(u16, u16)> {
186 self.mariadb
187 }
188
189 pub fn is_mariadb(self) -> bool {
191 self.mariadb.is_some()
192 }
193
194 pub(crate) fn mariadb_before(self, major: u16, minor: u16) -> bool {
196 self.mariadb.is_some_and(|version| version < (major, minor))
197 }
198
199 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#[derive(Clone, Debug, PartialEq)]
230pub struct Statement {
231 pub sql: String,
233 pub values: Vec<Value>,
235 pub dialect: Dialect,
237}
238
239impl Statement {
240 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 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
269pub(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}