Skip to main content

rust_query/
rows.rs

1use std::{marker::PhantomData, rc::Rc};
2
3use crate::{
4    CustomJoin, 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.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    pub(crate) fn join_custom<T: CustomJoin<Schema = S>>(
67        &mut self,
68        t: T,
69    ) -> Expr<'inner, S, TableRow<T>> {
70        self.join(Joinable::new(t.name(), t.main_column()))
71    }
72
73    pub(crate) fn join_tmp<T: Table<Schema = S>>(
74        &mut self,
75        tmp: lower::TmpTable,
76    ) -> Expr<'inner, S, TableRow<T>> {
77        self.join(Joinable::new(lower::JoinableTable::Tmp(tmp), T::ID))
78    }
79
80    /// Filter rows based on an expression.
81    pub fn filter(&mut self, prop: impl IntoExpr<'inner, S, Typ = bool>) {
82        Rc::make_mut(&mut self.ast).filter(prop.into_expr().inner);
83    }
84
85    /// Filter out rows where this expression is [None].
86    ///
87    /// Returns a new expression with the unwrapped type.
88    ///
89    /// ```
90    /// # use rust_query::IntoExpr;
91    /// # rust_query::private::doctest::get_txn(|txn| {
92    /// txn.query(|rows| {
93    ///     let a = rows.filter_some(Some(100));
94    ///     let b = rows.filter_some(Some(false));
95    ///     assert_eq!(vec![(100, false)], rows.into_vec((&a, &b)));
96    ///     let c = rows.filter_some(None::<i64>);
97    ///     assert_eq!(Vec::<(i64, bool)>::new(), rows.into_vec((&a, &b)));
98    /// })
99    /// # });
100    /// ```
101    pub fn filter_some<Typ: EqTyp>(
102        &mut self,
103        val: impl IntoExpr<'inner, S, Typ = Option<Typ>>,
104    ) -> Expr<'inner, S, Typ> {
105        let val = val.into_expr();
106        let not_null = val.is_some();
107        Rc::make_mut(&mut self.ast).filter(not_null.inner.clone());
108
109        // expr may still be null because of error nulls.
110        Expr::new(val.inner)
111    }
112}