2021-02-13 23:44:41 +03:00
|
|
|
use crate::StdResult;
|
2021-01-31 13:39:00 +03:00
|
|
|
|
2021-02-15 13:06:09 +03:00
|
|
|
pub trait ToSql {
|
|
|
|
fn to_sql(&self) -> String;
|
|
|
|
}
|
|
|
|
|
2021-02-19 22:17:01 +03:00
|
|
|
pub type ToSqlParams<'a> = &'a [&'a dyn ToSql];
|
|
|
|
|
2021-02-15 13:06:09 +03:00
|
|
|
impl ToSql for &str {
|
|
|
|
fn to_sql(&self) -> String {
|
2021-02-15 23:22:13 +03:00
|
|
|
format!("'{}'", self)
|
2021-02-15 13:06:09 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub trait TryFromSql<QueryResultRow>: Sized {
|
|
|
|
fn try_from_sql(row: QueryResultRow) -> StdResult<Self>;
|
|
|
|
}
|
|
|
|
|
2021-02-18 12:29:09 +03:00
|
|
|
pub trait OpenDatabaseConnection: Sized {
|
2021-02-15 13:06:09 +03:00
|
|
|
fn open(connection_string: &str) -> StdResult<Self>;
|
2021-02-18 12:29:09 +03:00
|
|
|
}
|
2021-02-15 13:06:09 +03:00
|
|
|
|
2021-02-18 12:29:09 +03:00
|
|
|
pub trait DatabaseConnection {
|
2021-02-15 13:06:09 +03:00
|
|
|
fn batch_execute(&mut self, query: &str) -> StdResult<()>;
|
|
|
|
|
2021-02-19 22:17:01 +03:00
|
|
|
fn execute<'b>(&mut self, query: &str, params: ToSqlParams<'b>) -> StdResult<u64>;
|
|
|
|
|
|
|
|
fn query<'b>(&mut self, query: &str, params: ToSqlParams<'b>) -> StdResult<Vec<Vec<String>>>;
|
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) fn merge_query_with_params(query: &str, params: ToSqlParams) -> String {
|
|
|
|
params
|
|
|
|
.iter()
|
|
|
|
.enumerate()
|
|
|
|
.fold(query.to_string(), |acc, (i, p)| {
|
|
|
|
str::replace(&acc, &format!("${}", i + 1), &p.to_sql())
|
|
|
|
})
|
|
|
|
}
|
2021-02-15 13:06:09 +03:00
|
|
|
|
2021-02-19 22:17:01 +03:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
2021-02-20 22:31:56 +03:00
|
|
|
fn replace_one_param_in_query() {
|
2021-02-19 22:17:01 +03:00
|
|
|
assert_eq!(
|
|
|
|
merge_query_with_params("SELECT $1", &[&"foo"]),
|
|
|
|
"SELECT 'foo'"
|
|
|
|
);
|
2021-02-20 22:31:56 +03:00
|
|
|
}
|
2021-02-19 22:17:01 +03:00
|
|
|
|
2021-02-20 22:31:56 +03:00
|
|
|
#[test]
|
|
|
|
fn replace_two_params_in_query() {
|
2021-02-19 22:17:01 +03:00
|
|
|
assert_eq!(
|
|
|
|
merge_query_with_params("SELECT $1, $2", &[&"foo", &"bar"]),
|
|
|
|
"SELECT 'foo', 'bar'"
|
|
|
|
);
|
2021-02-20 22:31:56 +03:00
|
|
|
}
|
2021-02-19 22:17:01 +03:00
|
|
|
|
2021-02-20 22:31:56 +03:00
|
|
|
#[test]
|
|
|
|
fn replace_all_bonds_in_query_with_first_param() {
|
2021-02-19 22:17:01 +03:00
|
|
|
assert_eq!(
|
|
|
|
merge_query_with_params("SELECT $1, $1", &[&"foo"]),
|
|
|
|
"SELECT 'foo', 'foo'"
|
|
|
|
);
|
|
|
|
}
|
2021-02-15 13:06:09 +03:00
|
|
|
}
|