Skip to main content

tablo_core/resource/
query.rs

1//! [`ResourceDef::query`]: a resource's own row scoping within its panel.
2
3use std::sync::Arc;
4
5use toasty::stmt::Expr;
6use topcoat::context::Cx;
7
8use super::{Resource, ResourceDef};
9
10/// One [`ResourceDef::query`] narrowing: the predicate its rows match in a request, or `None`
11/// when it narrows nothing there.
12pub(crate) type QueryFn = Arc<dyn Fn(&Cx) -> Option<Expr<bool>> + Send + Sync>;
13
14impl<R: Resource> ResourceDef<R> {
15    /// Narrows the rows the resource serves within the panel to the ones `predicate` matches: its
16    /// own row scoping, such as row visibility. Every loader reads through it: the list and its
17    /// counts, the export, the detail, edit and record pages, every write, relationship options
18    /// and relation tables, the global search, widgets and the sidebar badge. A row it leaves out
19    /// does not exist for the request: its pages answer 404.
20    ///
21    /// ```rust
22    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
23    /// # struct Post { #[key] #[auto] id: uuid::Uuid, published: bool }
24    /// # struct PostResource;
25    /// # impl tablo_core::Resource for PostResource {
26    /// #     type Model = Post;
27    /// #     type Form = tablo_core::NoForm<Post>;
28    /// # }
29    /// use tablo_core::Panel;
30    ///
31    /// // The portal lists and opens published posts only.
32    /// Panel::new("portal")
33    ///     .resource_with::<PostResource>(|def| def.query(Post::fields().published().eq(true)));
34    /// ```
35    ///
36    /// [`query_fn`](Self::query_fn) narrows by the request, such as to the signed-in user's rows.
37    ///
38    /// Each call ANDs its predicate onto the ones before it, so a panel's
39    /// [`resource_with`](crate::Panel::resource_with) narrows what the resource's own
40    /// [`declare`](Resource::declare) narrows, and none widens another.
41    ///
42    /// **Tenancy and soft deletes are not this method's job.** The framework ANDs the
43    /// [`tenancy`](Self::tenancy) filter and leaves out the [trashed](Self::soft_delete) records
44    /// beside every narrowing. Code outside the framework's loaders starts from
45    /// [`scoped_query`](crate::scoped_query), which reads through the same narrowings.
46    ///
47    /// **Neither are relations, an order or a limit.** A predicate says which rows, and nothing
48    /// else: the list, the export and the detail page load the relations their columns declare
49    /// ([`Column::includes`](crate::extend::Column::includes)),
50    /// [`include_unscoped`](Self::include_unscoped) loads one a closure no column covers reads,
51    /// and [`Table::default_sort`](crate::Table::default_sort) orders a list.
52    ///
53    /// # Unique constraints and the narrowed rows
54    ///
55    /// The app-side unique pre-check reads each narrowing's predicate. One that reads a field of
56    /// the unique index stays in the probe, as it fixes that field: under
57    /// `query_fn(|cx| owner().eq(me(cx)))` a `#[unique(owner, slug)]` slug is taken only among the
58    /// user's own rows. One that reads none of the index's fields is left out of the probe, since
59    /// the index covers the rows it hides: a slug an unpublished post holds is refused inline as
60    /// "has already been taken". A predicate over the index's fields that still hides a
61    /// colliding row, such as `owner().ne(..)`, lets the database refuse the write; probe that
62    /// index in [`create_record`](Resource::create_record) and
63    /// [`update_record`](Resource::update_record) and refuse with
64    /// [`WriteError::Refused`](crate::WriteError::Refused).
65    #[must_use]
66    pub fn query(mut self, predicate: Expr<bool>) -> Self {
67        self.queries
68            .push(Arc::new(move |_cx| Some(predicate.clone())));
69        self
70    }
71
72    /// Narrows the rows as [`query`](Self::query) does, by the request: to the ones the predicate
73    /// it returns matches, or not at all when it returns `None`.
74    ///
75    /// ```rust
76    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
77    /// # struct Post { #[key] #[auto] id: uuid::Uuid, author: String }
78    /// # struct PostResource;
79    /// # impl tablo_core::Resource for PostResource {
80    /// #     type Model = Post;
81    /// #     type Form = tablo_core::NoForm<Post>;
82    /// # }
83    /// # fn current_user(_cx: &topcoat::context::Cx) -> String { String::new() }
84    /// # fn is_editor(_cx: &topcoat::context::Cx) -> bool { false }
85    /// use tablo_core::Panel;
86    ///
87    /// Panel::new("portal").resource_with::<PostResource>(|def| {
88    ///     // Each author lists and opens their own posts only.
89    ///     def.query_fn(|cx| Post::fields().author().eq(current_user(cx)))
90    /// });
91    ///
92    /// Panel::new("desk").resource_with::<PostResource>(|def| {
93    ///     // An editor reads every post.
94    ///     def.query_fn(|cx| (!is_editor(cx)).then(|| Post::fields().author().eq(current_user(cx))))
95    /// });
96    /// ```
97    ///
98    /// The closure runs once per query a request makes, reads the request alone and cannot fail:
99    /// the [`policy`](Self::policy) refuses a request that may read no row. A predicate over
100    /// rows the request must first read, the teams a user sits on say, reads them from a
101    /// [`Load`](crate::Load) value the panel loaded.
102    #[must_use]
103    pub fn query_fn<F, P>(mut self, predicate: F) -> Self
104    where
105        F: Fn(&Cx) -> P + Send + Sync + 'static,
106        P: Into<Option<Expr<bool>>>,
107    {
108        self.queries.push(Arc::new(move |cx| predicate(cx).into()));
109        self
110    }
111
112    /// Loads `relation` with every row the resource reads, for a closure no column covers: one
113    /// the [`policy`](Self::policy) reads, or one a table's `group_by` or row key reads without a
114    /// column including it. Call it once per relation.
115    ///
116    /// The closure reads whatever the include loads, under no resource's query or policy, as an
117    /// [`unscoped`](crate::RelationColumn::unscoped) relation column does. Every loader pays for
118    /// the relation, so one only a column shows belongs to that column.
119    #[must_use]
120    pub fn include_unscoped<T>(
121        mut self,
122        relation: impl Into<toasty::stmt::Include<R::Model, T>>,
123    ) -> Self {
124        self.includes = self.includes.with(relation);
125        self
126    }
127}