115 lines
2.7 KiB
Rust
115 lines
2.7 KiB
Rust
//! Database Driver for MySQL
|
|
//!
|
|
//! Use of this driver requires enabling the `mysql` feature.
|
|
//!
|
|
//! Contains database-specific query data
|
|
//! Uses the [Mysql](https://crates.io/crates/mysql) crate for
|
|
//! interfacing with the database
|
|
use super::*;
|
|
|
|
use std::any::Any;
|
|
use std::cell::RefCell;
|
|
use my::{Pool};
|
|
|
|
/// The struct implementing the `DatabaseDriver` trait
|
|
#[derive(Debug)]
|
|
pub struct MySQLDriver {
|
|
connection: RefCell<Option<Pool>>,
|
|
}
|
|
|
|
impl MySQLDriver {
|
|
/// Create a MySQLDriver driver
|
|
pub fn new(dsn: &str) -> Self {
|
|
let mut driver = MySQLDriver {
|
|
connection: RefCell::new(None)
|
|
};
|
|
|
|
driver.connect(dsn);
|
|
|
|
driver
|
|
}
|
|
|
|
fn test_new() -> Self {
|
|
MySQLDriver {
|
|
connection: RefCell::new(None)
|
|
}
|
|
}
|
|
|
|
fn connect(&mut self, dsn: &str) {
|
|
let connection = Pool::new(dsn).unwrap();
|
|
|
|
self.connection = RefCell::new(Some(connection));
|
|
}
|
|
}
|
|
|
|
impl DatabaseDriver for MySQLDriver {
|
|
/// Get which characters are used to delimit identifiers
|
|
/// such as tables, and columns
|
|
fn _quotes(&self) -> (char, char) {
|
|
('`', '`')
|
|
}
|
|
|
|
fn query(&self, sql: &str) -> Result<Box<dyn Any>, Box<dyn Any>> {
|
|
unimplemented!();
|
|
}
|
|
|
|
fn limit(&self, sql: &str, limit: Option<usize>, offset: Option<usize>) -> String {
|
|
if limit.is_none() {
|
|
return sql.to_string();
|
|
}
|
|
|
|
// Limit and Offset are defined
|
|
if offset.is_some() {
|
|
return format!("{} LIMIT {}.{}", sql, offset.unwrap(), limit.unwrap());
|
|
}
|
|
|
|
// Limit is defined
|
|
format!("{} LIMIT {}", sql, limit.unwrap())
|
|
}
|
|
|
|
fn explain(&self, sql: &str) -> String {
|
|
format!("EXPLAIN EXTENDED {}", sql)
|
|
}
|
|
|
|
fn random(&self) -> String {
|
|
String::from(" RAND() DESC")
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn test_quote_identifier_backtick_quote() {
|
|
let driver = MySQLDriver::test_new();
|
|
|
|
assert_eq!(
|
|
driver.quote_identifier("foo, bar, baz"),
|
|
"`foo`,`bar`,`baz`"
|
|
);
|
|
assert_eq!(
|
|
driver.quote_identifier("foo.bar, baz, fizz"),
|
|
"`foo`.`bar`,`baz`,`fizz`"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn test_quote_identifiers_backtick_quote() {
|
|
let driver = MySQLDriver::test_new();
|
|
|
|
assert_eq!(
|
|
driver.quote_identifiers(vec![
|
|
"\tfoo. bar".to_string(),
|
|
"baz".to_string(),
|
|
"fizz.\n\tbuzz.baz".to_string(),
|
|
]),
|
|
vec![
|
|
"`foo`.`bar`".to_string(),
|
|
"`baz`".to_string(),
|
|
"`fizz`.`buzz`.`baz`".to_string(),
|
|
]
|
|
);
|
|
}
|
|
}
|