use std::sync::Arc;
use postgres::types::ToSql;
use crate::column_value::UntypedColumnValue;
use crate::prelude::ColumnType;
#[derive(Clone)]
pub struct BoxedSql {
pub sql: String,
pub values: Vec<Arc<Box<dyn ToSql + Sync + Send + 'static>>>,
}
impl BoxedSql {
pub fn new(
sql: String,
value: Vec<Arc<Box<dyn ToSql + Sync + Send + 'static>>>,
) -> Self {
Self { sql, values: value }
}
pub fn resolve(
&self,
mut index: usize,
) -> (String, Vec<Arc<Box<dyn ToSql + Sync + Send>>>, usize) {
let mut sql = self.sql.clone();
while sql.contains("_$i") {
sql = sql.replacen("_$i", &*format!("${index}"), 1);
index += 1;
}
(sql, self.values.clone(), index)
}
pub fn modify<F: FnOnce(&String) -> String>(&mut self, f: F) {
self.sql = f(&self.sql);
}
}
#[allow(clippy::wrong_self_convention)]
pub trait IntoSql<T> {
fn into_boxed_sql(&self) -> BoxedSql;
}
impl<T: ColumnType + UntypedColumnValue> IntoSql<T> for T {
fn into_boxed_sql(&self) -> BoxedSql {
self.get_sql()
}
}
impl<T: ColumnType + UntypedColumnValue> IntoSql<T> for &T {
fn into_boxed_sql(&self) -> BoxedSql {
self.get_sql()
}
}
impl<'a> IntoSql<String> for &'a str {
fn into_boxed_sql(&self) -> BoxedSql {
self.to_string().into_boxed_sql()
}
}