use crate::error::Result;
use crate::traits::{ExecuteResult, FromRow, Pool, ToValue};
use crate::value::Value;
#[derive(Debug, Clone)]
pub struct Query<'q> {
sql: &'q str,
params: Vec<Value>,
}
impl<'q> Query<'q> {
pub fn new(sql: &'q str) -> Self {
Self {
sql,
params: Vec::new(),
}
}
pub fn bind<T: ToValue>(mut self, value: T) -> Self {
self.params.push(value.to_value());
self
}
pub fn bind_all<T: ToValue>(mut self, values: &[T]) -> Self {
for value in values {
self.params.push(value.to_value());
}
self
}
pub fn sql(&self) -> &str {
self.sql
}
pub fn params(&self) -> &[Value] {
&self.params
}
pub fn into_params(self) -> Vec<Value> {
self.params
}
pub async fn execute<P: Pool>(self, pool: &P) -> Result<ExecuteResult> {
pool.execute(self.sql, self.params).await
}
pub async fn fetch_all<T: FromRow + Send, P: Pool>(self, pool: &P) -> Result<Vec<T>> {
pool.fetch_all(self.sql, self.params).await
}
pub async fn fetch_optional<T: FromRow + Send, P: Pool>(self, pool: &P) -> Result<Option<T>> {
pool.fetch_optional(self.sql, self.params).await
}
pub async fn fetch_one<T: FromRow + Send, P: Pool>(self, pool: &P) -> Result<T> {
pool.fetch_one(self.sql, self.params).await
}
pub async fn fetch_scalar<T: crate::FromValue + Send, P: Pool>(self, pool: &P) -> Result<T> {
pool.fetch_scalar(self.sql, self.params).await
}
}
#[derive(Debug, Clone)]
pub struct DynamicQuery {
sql: String,
params: Vec<Value>,
}
impl DynamicQuery {
pub fn new(sql: impl Into<String>) -> Self {
Self {
sql: sql.into(),
params: Vec::new(),
}
}
pub fn bind<T: ToValue>(mut self, value: T) -> Self {
self.params.push(value.to_value());
self
}
pub fn bind_all<T: ToValue>(mut self, values: &[T]) -> Self {
for value in values {
self.params.push(value.to_value());
}
self
}
pub fn sql(&self) -> &str {
&self.sql
}
pub fn params(&self) -> &[Value] {
&self.params
}
pub async fn execute<P: Pool>(self, pool: &P) -> Result<ExecuteResult> {
pool.execute(&self.sql, self.params).await
}
pub async fn fetch_all<T: FromRow + Send, P: Pool>(self, pool: &P) -> Result<Vec<T>> {
pool.fetch_all(&self.sql, self.params).await
}
pub async fn fetch_optional<T: FromRow + Send, P: Pool>(self, pool: &P) -> Result<Option<T>> {
pool.fetch_optional(&self.sql, self.params).await
}
pub async fn fetch_one<T: FromRow + Send, P: Pool>(self, pool: &P) -> Result<T> {
pool.fetch_one(&self.sql, self.params).await
}
pub async fn fetch_scalar<T: crate::FromValue + Send, P: Pool>(self, pool: &P) -> Result<T> {
pool.fetch_scalar(&self.sql, self.params).await
}
}