1use crate::pool::{backend, read_pool, Backend};
2use larust_core::{axum, AppError};
3use sqlx::any::{Any, AnyArguments};
4use sqlx::query::QueryAs;
5use sqlx::AnyPool;
6use std::marker::PhantomData;
7
8#[derive(Clone)]
13pub enum BindValue {
14 Text(String),
15 Int(i64),
16 Bool(bool),
17}
18
19impl From<String> for BindValue {
20 fn from(v: String) -> Self {
21 BindValue::Text(v)
22 }
23}
24
25impl From<&str> for BindValue {
26 fn from(v: &str) -> Self {
27 BindValue::Text(v.to_string())
28 }
29}
30
31impl From<i64> for BindValue {
32 fn from(v: i64) -> Self {
33 BindValue::Int(v)
34 }
35}
36
37impl From<bool> for BindValue {
38 fn from(v: bool) -> Self {
39 BindValue::Bool(v)
40 }
41}
42
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum Op {
47 Ne,
48 Gt,
49 Gte,
50 Lt,
51 Lte,
52 Like,
53}
54
55impl Op {
56 fn as_sql(self) -> &'static str {
57 match self {
58 Op::Ne => "!=",
59 Op::Gt => ">",
60 Op::Gte => ">=",
61 Op::Lt => "<",
62 Op::Lte => "<=",
63 Op::Like => "LIKE",
64 }
65 }
66}
67
68#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70pub enum Order {
71 Asc,
72 Desc,
73}
74
75#[derive(Clone, Copy)]
80enum Conj {
81 And,
82 Or,
83}
84
85#[derive(Clone)]
89enum Condition {
90 Eq(&'static str, BindValue),
91 Op(&'static str, Op, BindValue),
92 In(&'static str, Vec<BindValue>),
93 Null(&'static str),
94 NotNull(&'static str),
95 Group(Vec<(Conj, Condition)>),
100 InQuery {
111 column: &'static str,
112 sub_table: &'static str,
113 sub_column: &'static str,
114 sub_wheres: Vec<(Conj, Condition)>,
115 },
116}
117
118#[derive(Clone, Copy)]
123enum SoftDeleteFilter {
124 Normal,
125 WithTrashed,
126 OnlyTrashed,
127}
128
129pub struct QueryBuilder<T> {
135 table: &'static str,
136 wheres: Vec<(Conj, Condition)>,
137 order_by: Vec<(&'static str, Order)>,
138 limit: Option<i64>,
139 soft_delete: Option<(&'static str, SoftDeleteFilter)>,
143 _marker: PhantomData<fn() -> T>,
144}
145
146impl<T> QueryBuilder<T>
202where
203 T: for<'r> sqlx::FromRow<'r, sqlx::any::AnyRow> + Send + Unpin,
204{
205 pub fn new(table: &'static str) -> Self {
206 Self {
207 table,
208 wheres: Vec::new(),
209 order_by: Vec::new(),
210 limit: None,
211 soft_delete: None,
212 _marker: PhantomData,
213 }
214 }
215
216 #[doc(hidden)]
223 #[must_use]
224 pub fn __with_soft_delete_column(mut self, column: &'static str) -> Self {
225 self.soft_delete = Some((column, SoftDeleteFilter::Normal));
226 self
227 }
228
229 #[must_use]
230 pub fn where_eq(mut self, column: &'static str, value: impl Into<BindValue>) -> Self {
231 self.wheres
232 .push((Conj::And, Condition::Eq(column, value.into())));
233 self
234 }
235
236 #[must_use]
240 pub fn where_op(mut self, column: &'static str, op: Op, value: impl Into<BindValue>) -> Self {
241 self.wheres
242 .push((Conj::And, Condition::Op(column, op, value.into())));
243 self
244 }
245
246 #[must_use]
248 pub fn where_null(mut self, column: &'static str) -> Self {
249 self.wheres.push((Conj::And, Condition::Null(column)));
250 self
251 }
252
253 #[must_use]
255 pub fn where_not_null(mut self, column: &'static str) -> Self {
256 self.wheres.push((Conj::And, Condition::NotNull(column)));
257 self
258 }
259
260 #[must_use]
269 pub fn where_in<V: Into<BindValue>>(mut self, column: &'static str, values: Vec<V>) -> Self {
270 self.wheres.push((
271 Conj::And,
272 Condition::In(column, values.into_iter().map(Into::into).collect()),
273 ));
274 self
275 }
276
277 #[must_use]
279 pub fn or_where_eq(mut self, column: &'static str, value: impl Into<BindValue>) -> Self {
280 self.wheres
281 .push((Conj::Or, Condition::Eq(column, value.into())));
282 self
283 }
284
285 #[must_use]
287 pub fn or_where_op(
288 mut self,
289 column: &'static str,
290 op: Op,
291 value: impl Into<BindValue>,
292 ) -> Self {
293 self.wheres
294 .push((Conj::Or, Condition::Op(column, op, value.into())));
295 self
296 }
297
298 #[must_use]
300 pub fn or_where_in<V: Into<BindValue>>(mut self, column: &'static str, values: Vec<V>) -> Self {
301 self.wheres.push((
302 Conj::Or,
303 Condition::In(column, values.into_iter().map(Into::into).collect()),
304 ));
305 self
306 }
307
308 #[must_use]
310 pub fn or_where_null(mut self, column: &'static str) -> Self {
311 self.wheres.push((Conj::Or, Condition::Null(column)));
312 self
313 }
314
315 #[must_use]
323 pub fn where_group(self, f: impl FnOnce(Self) -> Self) -> Self {
324 self.push_group(Conj::And, f)
325 }
326
327 #[must_use]
329 pub fn or_where_group(self, f: impl FnOnce(Self) -> Self) -> Self {
330 self.push_group(Conj::Or, f)
331 }
332
333 fn push_group(mut self, conj: Conj, f: impl FnOnce(Self) -> Self) -> Self {
334 let group_wheres = f(Self::new(self.table)).wheres;
335 self.wheres.push((conj, Condition::Group(group_wheres)));
336 self
337 }
338
339 #[must_use]
360 pub fn scope(mut self, f: impl FnOnce(Self) -> Self) -> Self {
361 let scope_wheres = f(Self::new(self.table)).wheres;
362 let needs_group = scope_wheres
363 .iter()
364 .any(|(conj, _)| matches!(conj, Conj::Or));
365 if needs_group {
366 self.wheres
367 .push((Conj::And, Condition::Group(scope_wheres)));
368 } else {
369 self.wheres.extend(scope_wheres);
370 }
371 self
372 }
373
374 #[must_use]
381 pub fn where_in_query<U>(
382 mut self,
383 column: &'static str,
384 sub_column: &'static str,
385 sub: QueryBuilder<U>,
386 ) -> Self {
387 self.wheres.push((
388 Conj::And,
389 Condition::InQuery {
390 column,
391 sub_table: sub.table,
392 sub_column,
393 sub_wheres: sub.wheres,
394 },
395 ));
396 self
397 }
398
399 #[must_use]
403 pub fn latest(mut self, column: &'static str) -> Self {
404 self.order_by.push((column, Order::Desc));
405 self
406 }
407
408 #[must_use]
410 pub fn oldest(mut self, column: &'static str) -> Self {
411 self.order_by.push((column, Order::Asc));
412 self
413 }
414
415 #[must_use]
418 pub fn order_by(mut self, column: &'static str, direction: Order) -> Self {
419 self.order_by.push((column, direction));
420 self
421 }
422
423 #[must_use]
430 pub fn limit(mut self, n: i64) -> Self {
431 self.limit = Some(n);
432 self
433 }
434
435 pub async fn paginate(mut self, per_page: i64) -> Result<Vec<T>, AppError> {
440 if per_page <= 0 {
441 return Err(AppError::Http {
442 status: axum::http::StatusCode::UNPROCESSABLE_ENTITY,
443 message: "pagination size must be greater than zero".to_string(),
444 });
445 }
446 self.limit = Some(per_page);
447 self.get().await
448 }
449
450 pub async fn get(self) -> Result<Vec<T>, AppError> {
451 self.get_on(read_pool()?).await
452 }
453
454 pub async fn get_on(self, database: &AnyPool) -> Result<Vec<T>, AppError> {
458 let sql = self.build_sql(backend(), None);
459 let combined = self.soft_delete_combined_wheres();
460 let wheres = combined.as_deref().unwrap_or(&self.wheres);
461 let query = bind_all(sqlx::query_as::<_, T>(&sql), wheres);
462 query
463 .fetch_all(database)
464 .await
465 .map_err(|e| AppError::Internal(Box::new(e)))
466 }
467
468 pub async fn first(self) -> Result<Option<T>, AppError> {
469 self.first_on(read_pool()?).await
470 }
471
472 pub async fn first_on(self, database: &AnyPool) -> Result<Option<T>, AppError> {
473 let sql = self.build_sql(backend(), Some(1));
474 let combined = self.soft_delete_combined_wheres();
475 let wheres = combined.as_deref().unwrap_or(&self.wheres);
476 let query = bind_all(sqlx::query_as::<_, T>(&sql), wheres);
477 query
478 .fetch_optional(database)
479 .await
480 .map_err(|e| AppError::Internal(Box::new(e)))
481 }
482
483 pub async fn count(self) -> Result<i64, AppError> {
484 self.count_on(read_pool()?).await
485 }
486
487 pub async fn count_on(self, database: &AnyPool) -> Result<i64, AppError> {
488 let sql = self.build_count_sql(backend());
489 let combined = self.soft_delete_combined_wheres();
490 let wheres = combined.as_deref().unwrap_or(&self.wheres);
491 let query = bind_all(sqlx::query_as::<_, (i64,)>(&sql), wheres);
492 query
493 .fetch_one(database)
494 .await
495 .map(|(count,)| count)
496 .map_err(|e| AppError::Internal(Box::new(e)))
497 }
498
499 pub async fn exists(self) -> Result<bool, AppError> {
500 Ok(self.first().await?.is_some())
501 }
502
503 fn build_sql(&self, backend: Backend, first_limit: Option<i64>) -> String {
512 let mut sql = format!("SELECT * FROM \"{}\"", self.table);
518
519 let combined = self.soft_delete_combined_wheres();
520 let wheres = combined.as_deref().unwrap_or(&self.wheres);
521 if !wheres.is_empty() {
522 let mut next_placeholder = 1usize;
523 sql.push_str(" WHERE ");
524 sql.push_str(&render_wheres(wheres, backend, &mut next_placeholder));
525 }
526
527 if !self.order_by.is_empty() {
528 let parts: Vec<String> = self
529 .order_by
530 .iter()
531 .map(|(column, direction)| {
532 let direction = match direction {
533 Order::Asc => "ASC",
534 Order::Desc => "DESC",
535 };
536 format!("\"{column}\" {direction}")
537 })
538 .collect();
539 sql.push_str(&format!(" ORDER BY {}", parts.join(", ")));
540 }
541
542 if let Some(limit) = first_limit.or(self.limit) {
543 sql.push_str(&format!(" LIMIT {limit}"));
544 }
545
546 sql
547 }
548
549 fn build_count_sql(&self, backend: Backend) -> String {
550 let mut sql = format!("SELECT COUNT(*) FROM \"{}\"", self.table);
551 let combined = self.soft_delete_combined_wheres();
552 let wheres = combined.as_deref().unwrap_or(&self.wheres);
553 if !wheres.is_empty() {
554 let mut next_placeholder = 1usize;
555 sql.push_str(" WHERE ");
556 sql.push_str(&render_wheres(wheres, backend, &mut next_placeholder));
557 }
558 sql
559 }
560
561 fn soft_delete_combined_wheres(&self) -> Option<Vec<(Conj, Condition)>> {
571 let (column, filter) = self.soft_delete?;
572 let filter_condition = match filter {
573 SoftDeleteFilter::WithTrashed => return None,
574 SoftDeleteFilter::Normal => Condition::Null(column),
575 SoftDeleteFilter::OnlyTrashed => Condition::NotNull(column),
576 };
577 if self.wheres.is_empty() {
578 return Some(vec![(Conj::And, filter_condition)]);
579 }
580 let has_top_level_or = self.wheres.iter().any(|(conj, _)| matches!(conj, Conj::Or));
581 let mut combined = vec![(Conj::And, filter_condition)];
582 if has_top_level_or {
583 combined.push((Conj::And, Condition::Group(self.wheres.clone())));
584 } else {
585 combined.extend(self.wheres.iter().cloned());
586 }
587 Some(combined)
588 }
589}
590
591pub trait SoftDeletes: crate::Model {}
597
598impl<T> QueryBuilder<T>
599where
600 T: for<'r> sqlx::FromRow<'r, sqlx::any::AnyRow> + Send + Unpin + SoftDeletes,
601{
602 #[must_use]
605 pub fn with_trashed(mut self) -> Self {
606 if let Some((column, _)) = self.soft_delete {
607 self.soft_delete = Some((column, SoftDeleteFilter::WithTrashed));
608 }
609 self
610 }
611
612 #[must_use]
614 pub fn only_trashed(mut self) -> Self {
615 if let Some((column, _)) = self.soft_delete {
616 self.soft_delete = Some((column, SoftDeleteFilter::OnlyTrashed));
617 }
618 self
619 }
620}
621
622fn next_placeholder_str(backend: Backend, next_placeholder: &mut usize) -> String {
630 match backend {
631 Backend::Sqlite | Backend::MySql => "?".to_string(),
632 Backend::Postgres => {
633 let n = *next_placeholder;
634 *next_placeholder += 1;
635 format!("${n}")
636 }
637 }
638}
639
640fn render_wheres(
646 wheres: &[(Conj, Condition)],
647 backend: Backend,
648 next_placeholder: &mut usize,
649) -> String {
650 let mut out = String::new();
651 for (i, (conj, condition)) in wheres.iter().enumerate() {
652 if i > 0 {
653 out.push_str(match conj {
654 Conj::And => " AND ",
655 Conj::Or => " OR ",
656 });
657 }
658 out.push_str(&render_condition(condition, backend, next_placeholder));
659 }
660 out
661}
662
663fn render_condition(
668 condition: &Condition,
669 backend: Backend,
670 next_placeholder: &mut usize,
671) -> String {
672 match condition {
673 Condition::Eq(column, _) => {
674 format!(
675 "\"{column}\" = {}",
676 next_placeholder_str(backend, next_placeholder)
677 )
678 }
679 Condition::Op(column, op, _) => {
680 format!(
681 "\"{column}\" {} {}",
682 op.as_sql(),
683 next_placeholder_str(backend, next_placeholder)
684 )
685 }
686 Condition::In(_, values) if values.is_empty() => "1=0".to_string(),
691 Condition::In(column, values) => {
692 let placeholders = values
693 .iter()
694 .map(|_| next_placeholder_str(backend, next_placeholder))
695 .collect::<Vec<_>>()
696 .join(", ");
697 format!("\"{column}\" IN ({placeholders})")
698 }
699 Condition::Null(column) => format!("\"{column}\" IS NULL"),
700 Condition::NotNull(column) => format!("\"{column}\" IS NOT NULL"),
701 Condition::Group(inner) => {
702 format!("({})", render_wheres(inner, backend, next_placeholder))
703 }
704 Condition::InQuery {
705 column,
706 sub_table,
707 sub_column,
708 sub_wheres,
709 } => {
710 let sub_where = if sub_wheres.is_empty() {
711 String::new()
712 } else {
713 format!(
714 " WHERE {}",
715 render_wheres(sub_wheres, backend, next_placeholder)
716 )
717 };
718 format!("\"{column}\" IN (SELECT \"{sub_column}\" FROM \"{sub_table}\"{sub_where})")
719 }
720 }
721}
722
723fn bind_all<'q, T>(
724 mut query: QueryAs<'q, Any, T, AnyArguments<'q>>,
725 wheres: &'q [(Conj, Condition)],
726) -> QueryAs<'q, Any, T, AnyArguments<'q>> {
727 for (_, condition) in wheres {
728 query = bind_condition(query, condition);
729 }
730 query
731}
732
733fn bind_condition<'q, T>(
738 mut query: QueryAs<'q, Any, T, AnyArguments<'q>>,
739 condition: &'q Condition,
740) -> QueryAs<'q, Any, T, AnyArguments<'q>> {
741 match condition {
742 Condition::Eq(_, value) | Condition::Op(_, _, value) => {
743 query = bind_value(query, value);
744 }
745 Condition::In(_, values) => {
746 for value in values {
747 query = bind_value(query, value);
748 }
749 }
750 Condition::Null(_) | Condition::NotNull(_) => {}
751 Condition::Group(inner) => {
752 query = bind_all(query, inner);
753 }
754 Condition::InQuery { sub_wheres, .. } => {
755 query = bind_all(query, sub_wheres);
756 }
757 }
758 query
759}
760
761fn bind_value<'q, T>(
762 query: QueryAs<'q, Any, T, AnyArguments<'q>>,
763 value: &'q BindValue,
764) -> QueryAs<'q, Any, T, AnyArguments<'q>> {
765 match value {
766 BindValue::Text(s) => query.bind(s),
767 BindValue::Int(i) => query.bind(i),
768 BindValue::Bool(b) => query.bind(b),
769 }
770}
771
772#[cfg(test)]
773mod tests {
774 use super::*;
775
776 #[derive(sqlx::FromRow)]
777 struct Dummy {
778 #[allow(dead_code)]
779 id: i64,
780 }
781
782 #[derive(sqlx::FromRow)]
783 struct SoftDeletedDummy {
784 #[allow(dead_code)]
785 id: i64,
786 }
787
788 impl crate::Model for SoftDeletedDummy {
789 type New = ();
790 const TABLE: &'static str = "soft_deleted_dummies";
791 const SOFT_DELETE_COLUMN: Option<&'static str> = Some("deleted_at");
792
793 async fn create(_data: Self::New) -> Result<Self, AppError> {
794 unimplemented!("not exercised by these tests")
795 }
796 }
797
798 impl SoftDeletes for SoftDeletedDummy {}
799
800 #[test]
801 fn quotes_table_and_column_identifiers_so_reserved_keywords_are_safe() {
802 let qb: QueryBuilder<Dummy> = QueryBuilder::new("order")
803 .where_eq("group", 1i64)
804 .latest("select");
805
806 assert_eq!(
807 qb.build_sql(Backend::Sqlite, None),
808 "SELECT * FROM \"order\" WHERE \"group\" = ? ORDER BY \"select\" DESC"
809 );
810 }
811
812 #[test]
813 fn build_sql_with_no_conditions() {
814 let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts");
815 assert_eq!(
816 qb.build_sql(Backend::Sqlite, None),
817 "SELECT * FROM \"posts\""
818 );
819 assert_eq!(
820 qb.build_sql(Backend::Sqlite, Some(1)),
821 "SELECT * FROM \"posts\" LIMIT 1"
822 );
823 }
824
825 #[test]
826 fn where_in_renders_one_placeholder_per_value() {
827 let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_in("id", vec![1i64, 2, 3]);
828 assert_eq!(
829 qb.build_sql(Backend::Sqlite, None),
830 "SELECT * FROM \"posts\" WHERE \"id\" IN (?, ?, ?)"
831 );
832 }
833
834 #[test]
835 fn where_in_with_a_single_value() {
836 let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_in("id", vec![1i64]);
837 assert_eq!(
838 qb.build_sql(Backend::Sqlite, None),
839 "SELECT * FROM \"posts\" WHERE \"id\" IN (?)"
840 );
841 }
842
843 #[test]
844 fn where_in_with_an_empty_list_renders_an_always_false_condition() {
845 let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_in("id", Vec::<i64>::new());
849 assert_eq!(
850 qb.build_sql(Backend::Sqlite, None),
851 "SELECT * FROM \"posts\" WHERE 1=0"
852 );
853 }
854
855 #[test]
856 fn where_in_quotes_the_column_identifier() {
857 let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_in("order", vec![1i64]);
858 assert_eq!(
859 qb.build_sql(Backend::Sqlite, None),
860 "SELECT * FROM \"posts\" WHERE \"order\" IN (?)"
861 );
862 }
863
864 #[test]
865 fn where_eq_and_where_in_combine_with_and() {
866 let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
867 .where_eq("title", "hi")
868 .where_in("id", vec![1i64, 2]);
869 assert_eq!(
870 qb.build_sql(Backend::Sqlite, None),
871 "SELECT * FROM \"posts\" WHERE \"title\" = ? AND \"id\" IN (?, ?)"
872 );
873 }
874
875 #[test]
876 fn mysql_renders_the_same_question_mark_placeholders_as_sqlite() {
877 let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
878 .where_eq("title", "hi")
879 .where_in("id", vec![1i64, 2]);
880 assert_eq!(
881 qb.build_sql(Backend::MySql, None),
882 "SELECT * FROM \"posts\" WHERE \"title\" = ? AND \"id\" IN (?, ?)"
883 );
884 }
885
886 #[test]
887 fn postgres_renders_numbered_placeholders_incrementing_across_the_whole_where_clause() {
888 let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
889 .where_eq("title", "hi")
890 .where_in("id", vec![1i64, 2, 3]);
891 assert_eq!(
892 qb.build_sql(Backend::Postgres, None),
893 "SELECT * FROM \"posts\" WHERE \"title\" = $1 AND \"id\" IN ($2, $3, $4)"
894 );
895 }
896
897 #[test]
898 fn postgres_where_in_with_an_empty_list_still_renders_an_always_false_condition() {
899 let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_in("id", Vec::<i64>::new());
900 assert_eq!(
901 qb.build_sql(Backend::Postgres, None),
902 "SELECT * FROM \"posts\" WHERE 1=0"
903 );
904 }
905
906 #[test]
907 fn build_count_sql_renders_numbered_placeholders_for_postgres() {
908 let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_eq("title", "hi");
909 assert_eq!(
910 qb.build_count_sql(Backend::Postgres),
911 "SELECT COUNT(*) FROM \"posts\" WHERE \"title\" = $1"
912 );
913 }
914
915 #[test]
916 fn where_op_renders_the_chosen_comparison() {
917 let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").where_op("views", Op::Gt, 10i64);
918 assert_eq!(
919 qb.build_sql(Backend::Sqlite, None),
920 "SELECT * FROM \"posts\" WHERE \"views\" > ?"
921 );
922 }
923
924 #[test]
925 fn where_null_and_where_not_null_render_with_no_placeholder() {
926 let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
927 .where_null("deleted_at")
928 .where_not_null("published_at");
929 assert_eq!(
930 qb.build_sql(Backend::Sqlite, None),
931 "SELECT * FROM \"posts\" WHERE \"deleted_at\" IS NULL AND \"published_at\" IS NOT NULL"
932 );
933 }
934
935 #[test]
936 fn or_where_variants_join_with_or_instead_of_and() {
937 let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
938 .where_eq("status", "draft")
939 .or_where_eq("status", "published")
940 .or_where_null("archived_at");
941 assert_eq!(
942 qb.build_sql(Backend::Sqlite, None),
943 "SELECT * FROM \"posts\" WHERE \"status\" = ? OR \"status\" = ? OR \"archived_at\" IS NULL"
944 );
945 }
946
947 #[test]
948 fn where_group_parenthesizes_only_its_own_conditions() {
949 let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
950 .where_eq("user_id", 1i64)
951 .where_group(|q| {
952 q.where_eq("status", "draft")
953 .or_where_eq("status", "published")
954 });
955 assert_eq!(
956 qb.build_sql(Backend::Sqlite, None),
957 "SELECT * FROM \"posts\" WHERE \"user_id\" = ? AND (\"status\" = ? OR \"status\" = ?)"
958 );
959 }
960
961 #[test]
962 fn scope_flattens_an_all_and_scope_with_no_parens() {
963 fn published(q: QueryBuilder<Dummy>) -> QueryBuilder<Dummy> {
964 q.where_not_null("published_at")
965 }
966 let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
967 .where_eq("user_id", 1i64)
968 .scope(published);
969 assert_eq!(
970 qb.build_sql(Backend::Sqlite, None),
971 "SELECT * FROM \"posts\" WHERE \"user_id\" = ? AND \"published_at\" IS NOT NULL"
972 );
973 }
974
975 #[test]
976 fn scope_groups_a_scope_that_uses_or_so_it_cannot_leak_precedence() {
977 fn recent_or_pinned(q: QueryBuilder<Dummy>) -> QueryBuilder<Dummy> {
978 q.where_eq("pinned", true).or_where_eq("recent", true)
979 }
980 let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
981 .where_eq("user_id", 1i64)
982 .scope(recent_or_pinned);
983 assert_eq!(
984 qb.build_sql(Backend::Sqlite, None),
985 "SELECT * FROM \"posts\" WHERE \"user_id\" = ? AND (\"pinned\" = ? OR \"recent\" = ?)"
986 );
987 }
988
989 #[test]
990 fn where_in_query_renders_a_subquery_with_its_own_where() {
991 let sub: QueryBuilder<Dummy> = QueryBuilder::new("users").where_eq("country_id", 7i64);
992 let qb: QueryBuilder<Dummy> =
993 QueryBuilder::new("posts").where_in_query("user_id", "id", sub);
994 assert_eq!(
995 qb.build_sql(Backend::Sqlite, None),
996 "SELECT * FROM \"posts\" WHERE \"user_id\" IN (SELECT \"id\" FROM \"users\" WHERE \"country_id\" = ?)"
997 );
998 }
999
1000 #[test]
1001 fn where_in_query_with_no_sub_conditions_omits_the_subquerys_where() {
1002 let sub: QueryBuilder<Dummy> = QueryBuilder::new("users");
1003 let qb: QueryBuilder<Dummy> =
1004 QueryBuilder::new("posts").where_in_query("user_id", "id", sub);
1005 assert_eq!(
1006 qb.build_sql(Backend::Sqlite, None),
1007 "SELECT * FROM \"posts\" WHERE \"user_id\" IN (SELECT \"id\" FROM \"users\")"
1008 );
1009 }
1010
1011 #[test]
1012 fn postgres_numbers_placeholders_in_order_across_a_group_and_a_subquery() {
1013 let sub: QueryBuilder<Dummy> = QueryBuilder::new("users").where_eq("country_id", 7i64);
1014 let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
1015 .where_eq("archived", false)
1016 .where_group(|q| {
1017 q.where_eq("status", "draft")
1018 .or_where_eq("status", "published")
1019 })
1020 .where_in_query("user_id", "id", sub);
1021 assert_eq!(
1022 qb.build_sql(Backend::Postgres, None),
1023 "SELECT * FROM \"posts\" WHERE \"archived\" = $1 AND (\"status\" = $2 OR \"status\" = $3) AND \"user_id\" IN (SELECT \"id\" FROM \"users\" WHERE \"country_id\" = $4)"
1024 );
1025 }
1026
1027 #[test]
1028 fn order_by_chains_multiple_sort_keys_in_call_order() {
1029 let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts")
1030 .order_by("priority", Order::Desc)
1031 .oldest("created_at");
1032 assert_eq!(
1033 qb.build_sql(Backend::Sqlite, None),
1034 "SELECT * FROM \"posts\" ORDER BY \"priority\" DESC, \"created_at\" ASC"
1035 );
1036 }
1037
1038 #[test]
1039 fn limit_sets_the_same_clause_paginate_does() {
1040 let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts").limit(5);
1041 assert_eq!(
1042 qb.build_sql(Backend::Sqlite, None),
1043 "SELECT * FROM \"posts\" LIMIT 5"
1044 );
1045 }
1046
1047 #[test]
1048 fn a_non_soft_delete_model_renders_with_no_filter_at_all() {
1049 let qb: QueryBuilder<Dummy> = QueryBuilder::new("posts");
1050 assert_eq!(
1051 qb.build_sql(Backend::Sqlite, None),
1052 "SELECT * FROM \"posts\""
1053 );
1054 }
1055
1056 #[test]
1057 fn soft_deletable_query_excludes_trashed_rows_by_default() {
1058 let qb: QueryBuilder<SoftDeletedDummy> =
1059 QueryBuilder::new("posts").__with_soft_delete_column("deleted_at");
1060 assert_eq!(
1061 qb.build_sql(Backend::Sqlite, None),
1062 "SELECT * FROM \"posts\" WHERE \"deleted_at\" IS NULL"
1063 );
1064 }
1065
1066 #[test]
1067 fn soft_delete_filter_prepends_plainly_when_no_or_is_present() {
1068 let qb: QueryBuilder<SoftDeletedDummy> = QueryBuilder::new("posts")
1069 .__with_soft_delete_column("deleted_at")
1070 .where_eq("status", "draft");
1071 assert_eq!(
1072 qb.build_sql(Backend::Sqlite, None),
1073 "SELECT * FROM \"posts\" WHERE \"deleted_at\" IS NULL AND \"status\" = ?"
1074 );
1075 }
1076
1077 #[test]
1078 fn soft_delete_filter_wraps_an_or_containing_where_clause_in_parens() {
1079 let qb: QueryBuilder<SoftDeletedDummy> = QueryBuilder::new("posts")
1080 .__with_soft_delete_column("deleted_at")
1081 .where_eq("status", "draft")
1082 .or_where_eq("status", "published");
1083 assert_eq!(
1084 qb.build_sql(Backend::Sqlite, None),
1085 "SELECT * FROM \"posts\" WHERE \"deleted_at\" IS NULL AND (\"status\" = ? OR \"status\" = ?)"
1086 );
1087 }
1088
1089 #[test]
1090 fn with_trashed_removes_the_default_exclusion_filter() {
1091 let qb: QueryBuilder<SoftDeletedDummy> = QueryBuilder::new("posts")
1092 .__with_soft_delete_column("deleted_at")
1093 .with_trashed();
1094 assert_eq!(
1095 qb.build_sql(Backend::Sqlite, None),
1096 "SELECT * FROM \"posts\""
1097 );
1098 }
1099
1100 #[test]
1101 fn only_trashed_filters_to_deleted_rows_only() {
1102 let qb: QueryBuilder<SoftDeletedDummy> = QueryBuilder::new("posts")
1103 .__with_soft_delete_column("deleted_at")
1104 .only_trashed();
1105 assert_eq!(
1106 qb.build_sql(Backend::Sqlite, None),
1107 "SELECT * FROM \"posts\" WHERE \"deleted_at\" IS NOT NULL"
1108 );
1109 }
1110}