2021-02-18 12:29:09 +03:00
|
|
|
use crate::database::{DatabaseConnection, OpenDatabaseConnection, ToSql};
|
2021-02-16 18:11:39 +03:00
|
|
|
use crate::error::StdResult;
|
2021-02-18 12:29:09 +03:00
|
|
|
use postgres::{Client, NoTls};
|
2021-02-16 18:11:39 +03:00
|
|
|
|
|
|
|
pub struct PostgresConnection {
|
|
|
|
client: Client,
|
|
|
|
}
|
|
|
|
|
2021-02-18 12:29:09 +03:00
|
|
|
impl OpenDatabaseConnection for PostgresConnection {
|
2021-02-16 18:11:39 +03:00
|
|
|
fn open(connection_string: &str) -> StdResult<Self> {
|
|
|
|
let client = Client::connect(connection_string, NoTls)?;
|
|
|
|
Ok(PostgresConnection { client })
|
|
|
|
}
|
2021-02-18 12:29:09 +03:00
|
|
|
}
|
2021-02-16 18:11:39 +03:00
|
|
|
|
2021-02-18 12:29:09 +03:00
|
|
|
impl DatabaseConnection for PostgresConnection {
|
2021-02-16 18:11:39 +03:00
|
|
|
fn batch_execute(&mut self, query: &str) -> StdResult<()> {
|
|
|
|
self.client.batch_execute(query)?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn execute<'b>(&mut self, query: &str, params: &'b [&'b dyn ToSql]) -> StdResult<u64> {
|
|
|
|
let stmt = params
|
|
|
|
.iter()
|
|
|
|
.enumerate()
|
|
|
|
.fold(query.to_string(), |acc, (i, p)| {
|
|
|
|
str::replace(&acc, &format!("${}", i), &p.to_sql())
|
|
|
|
});
|
|
|
|
|
|
|
|
let res = self.client.execute(stmt.as_str(), &[])?;
|
|
|
|
Ok(res)
|
|
|
|
}
|
|
|
|
|
2021-02-18 12:29:09 +03:00
|
|
|
fn query<'b>(
|
2021-02-16 18:11:39 +03:00
|
|
|
&mut self,
|
|
|
|
query: &str,
|
|
|
|
params: &'b [&'b dyn ToSql],
|
2021-02-18 12:29:09 +03:00
|
|
|
) -> StdResult<Vec<Vec<String>>> {
|
2021-02-16 18:11:39 +03:00
|
|
|
let stmt = params
|
|
|
|
.iter()
|
|
|
|
.enumerate()
|
|
|
|
.fold(query.to_string(), |acc, (i, p)| {
|
|
|
|
str::replace(&acc, &format!("${}", i), &p.to_sql())
|
|
|
|
});
|
|
|
|
|
2021-02-18 12:29:09 +03:00
|
|
|
let res = self.client.query(stmt.as_str(), &[])?;
|
2021-02-16 18:11:39 +03:00
|
|
|
|
|
|
|
let res = res
|
|
|
|
.into_iter()
|
2021-02-18 12:29:09 +03:00
|
|
|
.map(|row| {
|
|
|
|
let column: String = row.get(0);
|
|
|
|
vec![column]
|
|
|
|
})
|
|
|
|
.collect::<Vec<_>>();
|
2021-02-16 18:11:39 +03:00
|
|
|
|
|
|
|
Ok(res)
|
|
|
|
}
|
|
|
|
}
|