rust_query/rows.rs
1use std::{marker::PhantomData, rc::Rc};
2
3use crate::{
4 Expr, IntoExpr, Table, TableRow,
5 joinable::IntoJoinable,
6 lower,
7 private::Joinable,
8 value::{DbTyp, EqTyp},
9};
10
11/// [Rows] keeps track of all rows in the current query.
12///
13/// This is the base type for other query types like [crate::args::Aggregate] and [crate::args::Query].
14/// It contains basic query functionality like joining tables and filters.
15///
16/// [Rows] mutability is only about which rows are included.
17/// Adding new columns does not require mutating [Rows].
18pub struct Rows<'inner, S> {
19 // we might store 'inner
20 pub(crate) phantom: PhantomData<fn(&'inner ()) -> &'inner ()>,
21 pub(crate) _p: PhantomData<S>,
22 pub(crate) ast: Rc<lower::Rows>,
23}
24
25impl<'inner, S> Rows<'inner, S> {
26 /// Join a table, this is like a super simple [Iterator::flat_map] but for queries.
27 ///
28 /// After this operation [Rows] has rows for the combinations of each original row with each row of the table.
29 /// (Also called the "Carthesian product")
30 /// The expression that is returned refers to the joined table.
31 ///
32 /// The parameter must be a table name from the schema like `v0::User`.
33 /// This table can be filtered by `#[index]`: `rows.join(v0::User.score(100))`.
34 ///
35 /// See also [Self::filter_some] if you want to join a table that is filtered by `#[unique]`.
36 pub fn join<T: DbTyp>(
37 &mut self,
38 j: impl IntoJoinable<'inner, S, Typ = T>,
39 ) -> Expr<'inner, S, T> {
40 let joinable = j.into_joinable();
41
42 let join = Rc::make_mut(&mut self.ast).join(joinable.table.clone());
43 for (name, val) in joinable.conds {
44 // it is fine to directly use the alias here because the filter is in the same scope as the join
45 let expr = Rc::new(lower::Expr::RowIndex(
46 lower::RowLike::Join(join.clone()),
47 name,
48 ));
49 self.filter(Expr::adhoc(lower::Expr::Infix(expr, "=", val)));
50 }
51
52 Expr::new_inner(
53 Rc::new(lower::Expr::RowIndex(
54 lower::RowLike::Join(join),
55 joinable.table.main_column,
56 )),
57 true, // join can never be null
58 )
59 }
60
61 #[doc(hidden)]
62 pub fn join_private<T: Table<Schema = S>>(&mut self) -> Expr<'inner, S, TableRow<T>> {
63 self.join(Joinable::table())
64 }
65
66 /// Filter rows based on an expression.
67 pub fn filter(&mut self, prop: impl IntoExpr<'inner, S, Typ = bool>) {
68 Rc::make_mut(&mut self.ast).filter(prop.into_expr().inner);
69 }
70
71 /// Filter out rows where this expression is [None].
72 ///
73 /// Returns a new expression with the unwrapped type.
74 ///
75 /// ```
76 /// # use rust_query::IntoExpr;
77 /// # rust_query::private::doctest::get_txn(|txn| {
78 /// txn.query(|rows| {
79 /// let a = rows.filter_some(Some(100));
80 /// let b = rows.filter_some(Some(false));
81 /// assert_eq!(vec![(100, false)], rows.into_vec((&a, &b)));
82 /// let c = rows.filter_some(None::<i64>);
83 /// assert_eq!(Vec::<(i64, bool)>::new(), rows.into_vec((&a, &b)));
84 /// })
85 /// # });
86 /// ```
87 pub fn filter_some<Typ: EqTyp>(
88 &mut self,
89 val: impl IntoExpr<'inner, S, Typ = Option<Typ>>,
90 ) -> Expr<'inner, S, Typ> {
91 let val = val.into_expr();
92 let not_null = val.is_some();
93 Rc::make_mut(&mut self.ast).filter(not_null.inner.clone());
94
95 // expr may still be null because of error nulls.
96 Expr::new(val.inner)
97 }
98}