1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
mod filter;
mod join;
mod table;
pub use filter::Filter;
pub use join::{Join, JoinType};
pub use table::{Column, TypedColumn};
pub type DynCol = dyn Deref<Target = Column>;
use tokio_postgres::types::ToSql;
use std::ops::Deref;
use crate::{Error, Model, _get_client};
/// An executable query. Built using a [`QueryBuilder`].
pub struct Query {
stmt: String,
args: Vec<Box<dyn ToSql + Sync + Send>>,
}
/// A trait for building a [`Query`].
pub trait QueryBuilder {
fn build(self) -> Query;
}
/// This trait is implemented by anything
/// that goes into a query.
pub trait ToQuery {
fn to_sql(&self) -> String;
}
/// [`QueryBuilder`] for `SELECT` queries.
pub struct SelectBuilder {
cols: Vec<&'static DynCol>,
filter: Filter,
joins: Vec<Join>,
limit: Option<usize>,
}
impl Query {
/// Create a new query.
fn new(stmt: String, args: Vec<Box<dyn ToSql + Send + Sync>>) -> Query {
Query { stmt, args }
}
/// Start building a new SELECT query.
///
/// # Panics
/// Panics if an empty array is provided.
pub fn select<const N: usize>(cols: [&'static DynCol; N]) -> SelectBuilder {
SelectBuilder::new(cols.into_iter().collect())
}
/// Get the query's statement
pub fn stmt(&self) -> &str {
&self.stmt
}
/// Execute a query.
pub async fn exec<M: Model<M>>(&self) -> Result<Vec<M>, pg_worm::Error> {
let client = _get_client()?;
let rows = client
.query(
&self.stmt,
self.args
.iter()
.map(|i| &**i as _)
.collect::<Vec<_>>()
.as_slice(),
)
.await?;
let res = rows
.iter()
.map(|i| M::try_from(i))
.collect::<Result<Vec<M>, Error>>()?;
Ok(res)
}
}
impl SelectBuilder {
/// Start building a new SELECT query.
///
/// # Panics
/// Panics if an empty vec is provided.
pub fn new(cols: Vec<&'static DynCol>) -> SelectBuilder {
assert_ne!(cols.len(), 0, "must SELECT at least one column");
SelectBuilder {
cols,
filter: Filter::all(),
joins: Vec::new(),
limit: None,
}
}
/// Add a [`Filter`] to the select query.
///
/// # Example
///
/// ```
/// use pg_worm::{Model, Query, QueryBuilder};
///
/// #[derive(Model)]
/// struct Book {
/// id: i64,
/// title: String
/// }
///
/// let q = Query::select([&Book::title])
/// .filter(Book::id.eq(5))
/// .build();
/// ```
pub fn filter(mut self, new_filter: Filter) -> SelectBuilder {
self.filter = self.filter & new_filter;
self
}
/// Add a [`Join`] to the select query.
///
/// # Example
///
/// ```ignore
/// use pg_worm::{Model, Query, QueryBuilder, JoinType};
///
/// #[derive(Model)]
/// struct Book {
/// #[column(primary_key, auto)]
/// id: i64,
/// title: String,
/// author_id: i64
/// }
///
/// #[derive(Model)]
/// struct Author {
/// #[column(primary_key, auto)]
/// id: i64,
/// name: String
/// }
///
/// let q = Query::select([&Book::id, &Book::title, &Author::name])
/// .join(&Book::author_id, &Author::id, JoinType::Inner)
/// .filter(Author::name.eq("Marx"))
/// .build();
/// ```
pub fn join(
mut self,
column: &'static DynCol,
on_column: &'static DynCol,
join_type: JoinType,
) -> SelectBuilder {
let join = Join::new(column, on_column, join_type);
self.joins.push(join);
self
}
/// Add a LIMIT to your query.
pub fn limit(mut self, n: usize) -> SelectBuilder {
self.limit = Some(n);
self
}
}
impl QueryBuilder for SelectBuilder {
/// Build the query.
fn build(self) -> Query {
let select_cols = self
.cols
.iter()
.map(|i| i.full_name())
.collect::<Vec<_>>()
.join(", ");
let joins = self
.joins
.iter()
.map(|i| i.to_sql())
.collect::<Vec<String>>()
.join(" ");
let stmt = format!(
"SELECT {select_cols} FROM {} {} {} {}",
self.cols[0].table_name(),
joins,
self.filter.to_sql(),
self.limit.to_sql()
);
let args: Vec<Box<dyn ToSql + Sync + Send>> = self.filter.args();
Query::new(stmt, args)
}
}
impl<T: ToQuery> ToQuery for Option<T> {
fn to_sql(&self) -> String {
if let Some(x) = self {
format!("LIMIT {}", x.to_sql())
} else {
String::new()
}
}
}
impl ToQuery for usize {
fn to_sql(&self) -> String {
self.to_string()
}
}