use crate::pool::{backend, read_pool, Backend};
use larust_core::{axum, AppError};
use sqlx::any::{Any, AnyArguments};
use sqlx::query::QueryAs;
use sqlx::AnyPool;
use std::marker::PhantomData;
#[derive(Clone)]
pub enum BindValue {
Text(String),
Int(i64),
Bool(bool),
}
impl From<String> for BindValue {
fn from(v: String) -> Self {
BindValue::Text(v)
}
}
impl From<&str> for BindValue {
fn from(v: &str) -> Self {
BindValue::Text(v.to_string())
}
}
impl From<i64> for BindValue {
fn from(v: i64) -> Self {
BindValue::Int(v)
}
}
impl From<bool> for BindValue {
fn from(v: bool) -> Self {
BindValue::Bool(v)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Op {
Ne,
Gt,
Gte,
Lt,
Lte,
Like,
}
impl Op {
fn as_sql(self) -> &'static str {
match self {
Op::Ne => "!=",
Op::Gt => ">",
Op::Gte => ">=",
Op::Lt => "<",
Op::Lte => "<=",
Op::Like => "LIKE",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Order {
Asc,
Desc,
}
#[derive(Clone, Copy)]
enum Conj {
And,
Or,
}
#[derive(Clone)]
enum Condition {
Eq(&'static str, BindValue),
Op(&'static str, Op, BindValue),
In(&'static str, Vec<BindValue>),
Null(&'static str),
NotNull(&'static str),
Group(Vec<(Conj, Condition)>),
InQuery {
column: &'static str,
sub_table: &'static str,
sub_column: &'static str,
sub_wheres: Vec<(Conj, Condition)>,
},
}
#[derive(Clone, Copy)]
enum SoftDeleteFilter {
Normal,
WithTrashed,
OnlyTrashed,
}
pub struct QueryBuilder<T> {
table: &'static str,
wheres: Vec<(Conj, Condition)>,
order_by: Vec<(&'static str, Order)>,
limit: Option<i64>,
soft_delete: Option<(&'static str, SoftDeleteFilter)>,
_marker: PhantomData<fn() -> T>,
}
impl<T> QueryBuilder<T>
where
T: for<'r> sqlx::FromRow<'r, sqlx::any::AnyRow> + Send + Unpin,
{
pub fn new(table: &'static str) -> Self {
Self {
table,
wheres: Vec::new(),
order_by: Vec::new(),
limit: None,
soft_delete: None,
_marker: PhantomData,
}
}
#[doc(hidden)]
#[must_use]
pub fn __with_soft_delete_column(mut self, column: &'static str) -> Self {
self.soft_delete = Some((column, SoftDeleteFilter::Normal));
self
}
#[must_use]
pub fn where_eq(mut self, column: &'static str, value: impl Into<BindValue>) -> Self {
self.wheres
.push((Conj::And, Condition::Eq(column, value.into())));
self
}
#[must_use]
pub fn where_op(mut self, column: &'static str, op: Op, value: impl Into<BindValue>) -> Self {
self.wheres
.push((Conj::And, Condition::Op(column, op, value.into())));
self
}
#[must_use]
pub fn where_null(mut self, column: &'static str) -> Self {
self.wheres.push((Conj::And, Condition::Null(column)));
self
}
#[must_use]
pub fn where_not_null(mut self, column: &'static str) -> Self {
self.wheres.push((Conj::And, Condition::NotNull(column)));
self
}
#[must_use]
pub fn where_in<V: Into<BindValue>>(mut self, column: &'static str, values: Vec<V>) -> Self {
self.wheres.push((
Conj::And,
Condition::In(column, values.into_iter().map(Into::into).collect()),
));
self
}
#[must_use]
pub fn or_where_eq(mut self, column: &'static str, value: impl Into<BindValue>) -> Self {
self.wheres
.push((Conj::Or, Condition::Eq(column, value.into())));
self
}
#[must_use]
pub fn or_where_op(
mut self,
column: &'static str,
op: Op,
value: impl Into<BindValue>,
) -> Self {
self.wheres
.push((Conj::Or, Condition::Op(column, op, value.into())));
self
}
#[must_use]
pub fn or_where_in<V: Into<BindValue>>(mut self, column: &'static str, values: Vec<V>) -> Self {
self.wheres.push((
Conj::Or,
Condition::In(column, values.into_iter().map(Into::into).collect()),
));
self
}
#[must_use]
pub fn or_where_null(mut self, column: &'static str) -> Self {
self.wheres.push((Conj::Or, Condition::Null(column)));
self
}
#[must_use]
pub fn where_group(self, f: impl FnOnce(Self) -> Self) -> Self {
self.push_group(Conj::And, f)
}
#[must_use]
pub fn or_where_group(self, f: impl FnOnce(Self) -> Self) -> Self {
self.push_group(Conj::Or, f)
}
fn push_group(mut self, conj: Conj, f: impl FnOnce(Self) -> Self) -> Self {
let group_wheres = f(Self::new(self.table)).wheres;
self.wheres.push((conj, Condition::Group(group_wheres)));
self
}
#[must_use]
pub fn scope(mut self, f: impl FnOnce(Self) -> Self) -> Self {
let scope_wheres = f(Self::new(self.table)).wheres;
let needs_group = scope_wheres
.iter()
.any(|(conj, _)| matches!(conj, Conj::Or));
if needs_group {
self.wheres
.push((Conj::And, Condition::Group(scope_wheres)));
} else {
self.wheres.extend(scope_wheres);
}
self
}
#[must_use]
pub fn where_in_query<U>(
mut self,
column: &'static str,
sub_column: &'static str,
sub: QueryBuilder<U>,
) -> Self {
self.wheres.push((
Conj::And,
Condition::InQuery {
column,
sub_table: sub.table,
sub_column,
sub_wheres: sub.wheres,
},
));
self
}
#[must_use]
pub fn latest(mut self, column: &'static str) -> Self {
self.order_by.push((column, Order::Desc));
self
}
#[must_use]
pub fn oldest(mut self, column: &'static str) -> Self {
self.order_by.push((column, Order::Asc));
self
}
#[must_use]
pub fn order_by(mut self, column: &'static str, direction: Order) -> Self {
self.order_by.push((column, direction));
self
}
#[must_use]
pub fn limit(mut self, n: i64) -> Self {
self.limit = Some(n);
self
}
pub async fn paginate(mut self, per_page: i64) -> Result<Vec<T>, AppError> {
if per_page <= 0 {
return Err(AppError::Http {
status: axum::http::StatusCode::UNPROCESSABLE_ENTITY,
message: "pagination size must be greater than zero".to_string(),
});
}
self.limit = Some(per_page);
self.get().await
}
pub async fn get(self) -> Result<Vec<T>, AppError> {
self.get_on(read_pool()?).await
}
pub async fn get_on(self, database: &AnyPool) -> Result<Vec<T>, AppError> {
let sql = self.build_sql(backend(), None);
let combined = self.soft_delete_combined_wheres();
let wheres = combined.as_deref().unwrap_or(&self.wheres);
let query = bind_all(sqlx::query_as::<_, T>(&sql), wheres);
query
.fetch_all(database)
.await
.map_err(|e| AppError::Internal(Box::new(e)))
}
pub async fn first(self) -> Result<Option<T>, AppError> {
self.first_on(read_pool()?).await
}
pub async fn first_on(self, database: &AnyPool) -> Result<Option<T>, AppError> {
let sql = self.build_sql(backend(), Some(1));
let combined = self.soft_delete_combined_wheres();
let wheres = combined.as_deref().unwrap_or(&self.wheres);
let query = bind_all(sqlx::query_as::<_, T>(&sql), wheres);
query
.fetch_optional(database)
.await
.map_err(|e| AppError::Internal(Box::new(e)))
}
pub async fn count(self) -> Result<i64, AppError> {
self.count_on(read_pool()?).await
}
pub async fn count_on(self, database: &AnyPool) -> Result<i64, AppError> {
let sql = self.build_count_sql(backend());
let combined = self.soft_delete_combined_wheres();
let wheres = combined.as_deref().unwrap_or(&self.wheres);
let query = bind_all(sqlx::query_as::<_, (i64,)>(&sql), wheres);
query
.fetch_one(database)
.await
.map(|(count,)| count)
.map_err(|e| AppError::Internal(Box::new(e)))
}
pub async fn exists(self) -> Result<bool, AppError> {
Ok(self.first().await?.is_some())
}
fn build_sql(&self, backend: Backend, first_limit: Option<i64>) -> String {
let mut sql = format!("SELECT * FROM \"{}\"", self.table);
let combined = self.soft_delete_combined_wheres();
let wheres = combined.as_deref().unwrap_or(&self.wheres);
if !wheres.is_empty() {
let mut next_placeholder = 1usize;
sql.push_str(" WHERE ");
sql.push_str(&render_wheres(wheres, backend, &mut next_placeholder));
}
if !self.order_by.is_empty() {
let parts: Vec<String> = self
.order_by
.iter()
.map(|(column, direction)| {
let direction = match direction {
Order::Asc => "ASC",
Order::Desc => "DESC",
};
format!("\"{column}\" {direction}")
})
.collect();
sql.push_str(&format!(" ORDER BY {}", parts.join(", ")));
}
if let Some(limit) = first_limit.or(self.limit) {
sql.push_str(&format!(" LIMIT {limit}"));
}
sql
}
fn build_count_sql(&self, backend: Backend) -> String {
let mut sql = format!("SELECT COUNT(*) FROM \"{}\"", self.table);
let combined = self.soft_delete_combined_wheres();
let wheres = combined.as_deref().unwrap_or(&self.wheres);
if !wheres.is_empty() {
let mut next_placeholder = 1usize;
sql.push_str(" WHERE ");
sql.push_str(&render_wheres(wheres, backend, &mut next_placeholder));
}
sql
}
fn soft_delete_combined_wheres(&self) -> Option<Vec<(Conj, Condition)>> {
let (column, filter) = self.soft_delete?;
let filter_condition = match filter {
SoftDeleteFilter::WithTrashed => return None,
SoftDeleteFilter::Normal => Condition::Null(column),
SoftDeleteFilter::OnlyTrashed => Condition::NotNull(column),
};
if self.wheres.is_empty() {
return Some(vec![(Conj::And, filter_condition)]);
}
let has_top_level_or = self.wheres.iter().any(|(conj, _)| matches!(conj, Conj::Or));
let mut combined = vec![(Conj::And, filter_condition)];
if has_top_level_or {
combined.push((Conj::And, Condition::Group(self.wheres.clone())));
} else {
combined.extend(self.wheres.iter().cloned());
}
Some(combined)
}
}
pub trait SoftDeletes: crate::Model {}
impl<T> QueryBuilder<T>
where
T: for<'r> sqlx::FromRow<'r, sqlx::any::AnyRow> + Send + Unpin + SoftDeletes,
{
#[must_use]
pub fn with_trashed(mut self) -> Self {
if let Some((column, _)) = self.soft_delete {
self.soft_delete = Some((column, SoftDeleteFilter::WithTrashed));
}
self
}
#[must_use]
pub fn only_trashed(mut self) -> Self {
if let Some((column, _)) = self.soft_delete {
self.soft_delete = Some((column, SoftDeleteFilter::OnlyTrashed));
}
self
}
}
fn next_placeholder_str(backend: Backend, next_placeholder: &mut usize) -> String {
match backend {
Backend::Sqlite | Backend::MySql => "?".to_string(),
Backend::Postgres => {
let n = *next_placeholder;
*next_placeholder += 1;
format!("${n}")
}
}
}
fn render_wheres(
wheres: &[(Conj, Condition)],
backend: Backend,
next_placeholder: &mut usize,
) -> String {
let mut out = String::new();
for (i, (conj, condition)) in wheres.iter().enumerate() {
if i > 0 {
out.push_str(match conj {
Conj::And => " AND ",
Conj::Or => " OR ",
});
}
out.push_str(&render_condition(condition, backend, next_placeholder));
}
out
}
fn render_condition(
condition: &Condition,
backend: Backend,
next_placeholder: &mut usize,
) -> String {
match condition {
Condition::Eq(column, _) => {
format!(
"\"{column}\" = {}",
next_placeholder_str(backend, next_placeholder)
)
}
Condition::Op(column, op, _) => {
format!(
"\"{column}\" {} {}",
op.as_sql(),
next_placeholder_str(backend, next_placeholder)
)
}
Condition::In(_, values) if values.is_empty() => "1=0".to_string(),
Condition::In(column, values) => {
let placeholders = values
.iter()
.map(|_| next_placeholder_str(backend, next_placeholder))
.collect::<Vec<_>>()
.join(", ");
format!("\"{column}\" IN ({placeholders})")
}
Condition::Null(column) => format!("\"{column}\" IS NULL"),
Condition::NotNull(column) => format!("\"{column}\" IS NOT NULL"),
Condition::Group(inner) => {
format!("({})", render_wheres(inner, backend, next_placeholder))
}
Condition::InQuery {
column,
sub_table,
sub_column,
sub_wheres,
} => {
let sub_where = if sub_wheres.is_empty() {
String::new()
} else {
format!(
" WHERE {}",
render_wheres(sub_wheres, backend, next_placeholder)
)
};
format!("\"{column}\" IN (SELECT \"{sub_column}\" FROM \"{sub_table}\"{sub_where})")
}
}
}
fn bind_all<'q, T>(
mut query: QueryAs<'q, Any, T, AnyArguments<'q>>,
wheres: &'q [(Conj, Condition)],
) -> QueryAs<'q, Any, T, AnyArguments<'q>> {
for (_, condition) in wheres {
query = bind_condition(query, condition);
}
query
}
fn bind_condition<'q, T>(
mut query: QueryAs<'q, Any, T, AnyArguments<'q>>,
condition: &'q Condition,
) -> QueryAs<'q, Any, T, AnyArguments<'q>> {
match condition {
Condition::Eq(_, value) | Condition::Op(_, _, value) => {
query = bind_value(query, value);
}
Condition::In(_, values) => {
for value in values {
query = bind_value(query, value);
}
}
Condition::Null(_) | Condition::NotNull(_) => {}
Condition::Group(inner) => {
query = bind_all(query, inner);
}
Condition::InQuery { sub_wheres, .. } => {
query = bind_all(query, sub_wheres);
}
}
query
}
fn bind_value<'q, T>(
query: QueryAs<'q, Any, T, AnyArguments<'q>>,
value: &'q BindValue,
) -> QueryAs<'q, Any, T, AnyArguments<'q>> {
match value {
BindValue::Text(s) => query.bind(s),
BindValue::Int(i) => query.bind(i),
BindValue::Bool(b) => query.bind(b),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(sqlx::FromRow)]
struct Dummy {
#[allow(dead_code)]
id: i64,
}
#[derive(sqlx::FromRow)]
struct SoftDeletedDummy {
#[allow(dead_code)]
id: i64,
}
impl crate::Model for SoftDeletedDummy {
type New = ();
const TABLE: &'static str = "soft_deleted_dummies";
const SOFT_DELETE_COLUMN: Option<&'static str> = Some("deleted_at");
async fn create(_data: Self::New) -> Result<Self, AppError> {
unimplemented!("not exercised by these tests")
}
}
impl SoftDeletes for SoftDeletedDummy {}
#[test]
fn quotes_table_and_column_identifiers_so_reserved_keywords_are_safe() {
let qb: QueryBuilder<Dummy> = QueryBuilder::new("order")
.where_eq("group", 1i64)
.latest("select");
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"order\" WHERE \"group\" = ? ORDER BY \"select\" DESC"
);
}
#[test]
fn build_sql_with_no_conditions() {
let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts");
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\""
);
assert_eq!(
qb.build_sql(Backend::Sqlite, Some(1)),
"SELECT * FROM \"posts\" LIMIT 1"
);
}
#[test]
fn where_in_renders_one_placeholder_per_value() {
let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_in("id", vec![1i64, 2, 3]);
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\" WHERE \"id\" IN (?, ?, ?)"
);
}
#[test]
fn where_in_with_a_single_value() {
let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_in("id", vec![1i64]);
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\" WHERE \"id\" IN (?)"
);
}
#[test]
fn where_in_with_an_empty_list_renders_an_always_false_condition() {
let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_in("id", Vec::<i64>::new());
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\" WHERE 1=0"
);
}
#[test]
fn where_in_quotes_the_column_identifier() {
let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_in("order", vec![1i64]);
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\" WHERE \"order\" IN (?)"
);
}
#[test]
fn where_eq_and_where_in_combine_with_and() {
let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
.where_eq("title", "hi")
.where_in("id", vec![1i64, 2]);
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\" WHERE \"title\" = ? AND \"id\" IN (?, ?)"
);
}
#[test]
fn mysql_renders_the_same_question_mark_placeholders_as_sqlite() {
let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
.where_eq("title", "hi")
.where_in("id", vec![1i64, 2]);
assert_eq!(
qb.build_sql(Backend::MySql, None),
"SELECT * FROM \"posts\" WHERE \"title\" = ? AND \"id\" IN (?, ?)"
);
}
#[test]
fn postgres_renders_numbered_placeholders_incrementing_across_the_whole_where_clause() {
let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
.where_eq("title", "hi")
.where_in("id", vec![1i64, 2, 3]);
assert_eq!(
qb.build_sql(Backend::Postgres, None),
"SELECT * FROM \"posts\" WHERE \"title\" = $1 AND \"id\" IN ($2, $3, $4)"
);
}
#[test]
fn postgres_where_in_with_an_empty_list_still_renders_an_always_false_condition() {
let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_in("id", Vec::<i64>::new());
assert_eq!(
qb.build_sql(Backend::Postgres, None),
"SELECT * FROM \"posts\" WHERE 1=0"
);
}
#[test]
fn build_count_sql_renders_numbered_placeholders_for_postgres() {
let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_eq("title", "hi");
assert_eq!(
qb.build_count_sql(Backend::Postgres),
"SELECT COUNT(*) FROM \"posts\" WHERE \"title\" = $1"
);
}
#[test]
fn where_op_renders_the_chosen_comparison() {
let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_op("views", Op::Gt, 10i64);
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\" WHERE \"views\" > ?"
);
}
#[test]
fn where_null_and_where_not_null_render_with_no_placeholder() {
let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
.where_null("deleted_at")
.where_not_null("published_at");
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\" WHERE \"deleted_at\" IS NULL AND \"published_at\" IS NOT NULL"
);
}
#[test]
fn or_where_variants_join_with_or_instead_of_and() {
let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
.where_eq("status", "draft")
.or_where_eq("status", "published")
.or_where_null("archived_at");
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\" WHERE \"status\" = ? OR \"status\" = ? OR \"archived_at\" IS NULL"
);
}
#[test]
fn where_group_parenthesizes_only_its_own_conditions() {
let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
.where_eq("user_id", 1i64)
.where_group(|q| {
q.where_eq("status", "draft")
.or_where_eq("status", "published")
});
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\" WHERE \"user_id\" = ? AND (\"status\" = ? OR \"status\" = ?)"
);
}
#[test]
fn scope_flattens_an_all_and_scope_with_no_parens() {
fn published(q: QueryBuilder<Dummy>) -> QueryBuilder<Dummy> {
q.where_not_null("published_at")
}
let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
.where_eq("user_id", 1i64)
.scope(published);
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\" WHERE \"user_id\" = ? AND \"published_at\" IS NOT NULL"
);
}
#[test]
fn scope_groups_a_scope_that_uses_or_so_it_cannot_leak_precedence() {
fn recent_or_pinned(q: QueryBuilder<Dummy>) -> QueryBuilder<Dummy> {
q.where_eq("pinned", true).or_where_eq("recent", true)
}
let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
.where_eq("user_id", 1i64)
.scope(recent_or_pinned);
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\" WHERE \"user_id\" = ? AND (\"pinned\" = ? OR \"recent\" = ?)"
);
}
#[test]
fn where_in_query_renders_a_subquery_with_its_own_where() {
let sub: QueryBuilder<Dummy> = QueryBuilder::new("users").where_eq("country_id", 7i64);
let qb: QueryBuilder<Dummy> =
QueryBuilder::new("posts").where_in_query("user_id", "id", sub);
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\" WHERE \"user_id\" IN (SELECT \"id\" FROM \"users\" WHERE \"country_id\" = ?)"
);
}
#[test]
fn where_in_query_with_no_sub_conditions_omits_the_subquerys_where() {
let sub: QueryBuilder<Dummy> = QueryBuilder::new("users");
let qb: QueryBuilder<Dummy> =
QueryBuilder::new("posts").where_in_query("user_id", "id", sub);
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\" WHERE \"user_id\" IN (SELECT \"id\" FROM \"users\")"
);
}
#[test]
fn postgres_numbers_placeholders_in_order_across_a_group_and_a_subquery() {
let sub: QueryBuilder<Dummy> = QueryBuilder::new("users").where_eq("country_id", 7i64);
let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
.where_eq("archived", false)
.where_group(|q| {
q.where_eq("status", "draft")
.or_where_eq("status", "published")
})
.where_in_query("user_id", "id", sub);
assert_eq!(
qb.build_sql(Backend::Postgres, None),
"SELECT * FROM \"posts\" WHERE \"archived\" = $1 AND (\"status\" = $2 OR \"status\" = $3) AND \"user_id\" IN (SELECT \"id\" FROM \"users\" WHERE \"country_id\" = $4)"
);
}
#[test]
fn order_by_chains_multiple_sort_keys_in_call_order() {
let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
.order_by("priority", Order::Desc)
.oldest("created_at");
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\" ORDER BY \"priority\" DESC, \"created_at\" ASC"
);
}
#[test]
fn limit_sets_the_same_clause_paginate_does() {
let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").limit(5);
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\" LIMIT 5"
);
}
#[test]
fn a_non_soft_delete_model_renders_with_no_filter_at_all() {
let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts");
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\""
);
}
#[test]
fn soft_deletable_query_excludes_trashed_rows_by_default() {
let qb: QueryBuilder<SoftDeletedDummy> =
QueryBuilder::new("posts").__with_soft_delete_column("deleted_at");
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\" WHERE \"deleted_at\" IS NULL"
);
}
#[test]
fn soft_delete_filter_prepends_plainly_when_no_or_is_present() {
let qb: QueryBuilder<SoftDeletedDummy> = QueryBuilder::new("posts")
.__with_soft_delete_column("deleted_at")
.where_eq("status", "draft");
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\" WHERE \"deleted_at\" IS NULL AND \"status\" = ?"
);
}
#[test]
fn soft_delete_filter_wraps_an_or_containing_where_clause_in_parens() {
let qb: QueryBuilder<SoftDeletedDummy> = QueryBuilder::new("posts")
.__with_soft_delete_column("deleted_at")
.where_eq("status", "draft")
.or_where_eq("status", "published");
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\" WHERE \"deleted_at\" IS NULL AND (\"status\" = ? OR \"status\" = ?)"
);
}
#[test]
fn with_trashed_removes_the_default_exclusion_filter() {
let qb: QueryBuilder<SoftDeletedDummy> = QueryBuilder::new("posts")
.__with_soft_delete_column("deleted_at")
.with_trashed();
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\""
);
}
#[test]
fn only_trashed_filters_to_deleted_rows_only() {
let qb: QueryBuilder<SoftDeletedDummy> = QueryBuilder::new("posts")
.__with_soft_delete_column("deleted_at")
.only_trashed();
assert_eq!(
qb.build_sql(Backend::Sqlite, None),
"SELECT * FROM \"posts\" WHERE \"deleted_at\" IS NOT NULL"
);
}
}