use std::fmt;
use navree_db::Backend;
use crate::error::OrmError;
use crate::ir::Where;
use crate::value::Value;
pub(crate) use crate::render::grammar::is_identifier;
pub(crate) use crate::render::lower::timeout_millis;
pub use crate::render::{
render_aggregate, render_delete, render_exists, render_insert, render_select, render_truncate,
render_update, render_update_from,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Dialect {
Postgres,
MySql,
Sqlite,
}
impl Dialect {
pub fn backend(self) -> Backend {
match self {
Dialect::Postgres => Backend::Postgres,
Dialect::MySql => Backend::MySql,
Dialect::Sqlite => Backend::Sqlite,
}
}
pub fn name(self) -> &'static str {
match self {
Dialect::Postgres => "PostgreSQL",
Dialect::MySql => "MySQL",
Dialect::Sqlite => "SQLite",
}
}
pub fn supports_returning(self) -> bool {
!matches!(self, Dialect::MySql)
}
pub fn max_bind_values(self) -> usize {
match self {
Dialect::Postgres | Dialect::MySql => 65_535,
Dialect::Sqlite => 32_766,
}
}
pub fn quote_identifier(self, name: &str) -> String {
quote_identifier(name, self)
}
}
pub(crate) fn quote_identifier(name: &str, dialect: Dialect) -> String {
let quote = match dialect {
Dialect::MySql => '`',
Dialect::Postgres | Dialect::Sqlite => '"',
};
name.split('.')
.map(|part| {
let escaped = part.replace(quote, &format!("{quote}{quote}"));
format!("{quote}{escaped}{quote}")
})
.collect::<Vec<_>>()
.join(".")
}
impl From<Backend> for Dialect {
fn from(backend: Backend) -> Self {
match backend {
Backend::Postgres => Dialect::Postgres,
Backend::MySql => Dialect::MySql,
Backend::Sqlite => Dialect::Sqlite,
}
}
}
impl From<Dialect> for Backend {
fn from(dialect: Dialect) -> Self {
dialect.backend()
}
}
impl fmt::Display for Dialect {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Syntax {
dialect: Dialect,
mariadb: Option<(u16, u16)>,
}
impl Syntax {
pub fn mariadb(major: u16, minor: u16) -> Syntax {
Syntax {
dialect: Dialect::MySql,
mariadb: Some((major, minor)),
}
}
pub fn of(dialect: Dialect, mariadb: Option<(u16, u16)>) -> Syntax {
match (dialect, mariadb) {
(Dialect::MySql, Some((major, minor))) => Syntax::mariadb(major, minor),
(dialect, _) => Syntax::from(dialect),
}
}
pub fn dialect(self) -> Dialect {
self.dialect
}
pub fn mariadb_version(self) -> Option<(u16, u16)> {
self.mariadb
}
pub fn is_mariadb(self) -> bool {
self.mariadb.is_some()
}
pub(crate) fn mariadb_before(self, major: u16, minor: u16) -> bool {
self.mariadb.is_some_and(|version| version < (major, minor))
}
pub fn name(self) -> &'static str {
if self.is_mariadb() {
"MariaDB"
} else {
self.dialect.name()
}
}
}
impl From<Dialect> for Syntax {
fn from(dialect: Dialect) -> Self {
Syntax {
dialect,
mariadb: None,
}
}
}
impl fmt::Display for Syntax {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.mariadb {
Some((major, minor)) => write!(f, "MariaDB {major}.{minor}"),
None => f.write_str(self.dialect.name()),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Statement {
pub sql: String,
pub values: Vec<Value>,
pub dialect: Dialect,
}
impl Statement {
pub fn to_db(&self) -> navree_db::Statement {
navree_db::Statement::new(
self.dialect.backend(),
self.sql.clone(),
self.values.clone(),
)
}
}
impl From<Statement> for navree_db::Statement {
fn from(statement: Statement) -> Self {
navree_db::Statement::new(statement.dialect.backend(), statement.sql, statement.values)
}
}
impl fmt::Display for Statement {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.sql)?;
if !self.values.is_empty() {
write!(f, " -- {:?}", self.values)?;
}
Ok(())
}
}
pub(crate) fn render_filter(filter: &Where, dialect: Dialect) -> Result<Statement, OrmError> {
let condition = crate::render::lower::Lowerer::new(dialect).where_(filter)?;
crate::render::render_expr(&condition, dialect)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn identifiers() {
assert!(is_identifier("time_bucket"));
assert!(is_identifier("public.my_fn"));
assert!(!is_identifier("drop table x; --"));
assert!(!is_identifier("1abc"));
assert!(!is_identifier(""));
}
#[test]
fn filters_render_alone() {
let filter = Where::Raw {
sql: "a = ?".into(),
values: vec![Value::from(1)],
};
let statement = render_filter(&filter, Dialect::Postgres).unwrap();
assert_eq!(statement.sql, "a = $1");
assert_eq!(statement.values, [Value::from(1)]);
}
}