Skip to main content

tablo_core/column/relation/
count.rs

1//! [`CountColumn`]: how many related records each row on a page holds, read by one count query per
2//! row rather than by loading the records.
3
4use std::{
5    collections::HashMap,
6    sync::{Arc, Mutex, PoisonError},
7};
8
9use derive_where::derive_where;
10use toasty::{
11    Deferred,
12    stmt::{IntoExpr, List, Path, Query},
13};
14use topcoat::{Result, context::Cx};
15
16use super::{ColumnWidth, Declared, RelationLens, restrict::Restrict};
17use crate::{
18    DeclarationErrorKind,
19    schema::{OptionSource, ensure_option_access},
20    toasty_compat::{join::linked_to, pk},
21};
22
23/// The query a count narrows to one row's related records, or `None` when the request may count
24/// none.
25type Scope<T> = fn(&Cx) -> Result<Option<Query<List<T>>>>;
26
27/// A column counting the records of a `Deferred` `has_many` field that a source `S` shows, a
28/// many-to-many `#[has_many(via = ..)]` one included.
29///
30/// ```rust
31/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
32/// # struct Post {
33/// #     #[key] #[auto] id: uuid::Uuid,
34/// #     #[has_many]
35/// #     comments: toasty::Deferred<Vec<Comment>>,
36/// # }
37/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
38/// # struct Comment {
39/// #     #[key] #[auto] id: uuid::Uuid,
40/// #     #[index]
41/// #     post_id: uuid::Uuid,
42/// #     #[belongs_to(key = post_id, references = id)]
43/// #     post: toasty::Deferred<Post>,
44/// # }
45/// # struct CommentResource;
46/// # impl tablo_core::extend::OptionSource for CommentResource {
47/// #     type Model = Comment;
48/// #     fn scoped_query(_cx: &topcoat::context::Cx)
49/// #         -> topcoat::Result<toasty::stmt::Query<toasty::stmt::List<Comment>>>
50/// #     {
51/// #         Ok(toasty::stmt::Query::all())
52/// #     }
53/// #     fn label(_cx: &topcoat::context::Cx, comment: &Comment) -> String {
54/// #         comment.id.to_string()
55/// #     }
56/// # }
57/// use tablo_core::{CountColumn, relation};
58///
59/// CountColumn::of::<CommentResource>(relation!(Post.comments));
60/// ```
61///
62/// The header and the column's name are the field's name, capitalized, until
63/// [`label`](Self::label) replaces both.
64///
65/// The column loads no related record. Once a page's rows load, it counts each row's records in
66/// the database, one count query per row: what `S`'s
67/// [`scoped_query`](OptionSource::scoped_query) returns of them when it
68/// [`lists`](OptionSource::lists) for the user, as a relationship choice over `S` offers them. A
69/// request `S` does not list for, and a row loaded around the table's or the
70/// [`Detail`](crate::Detail)'s loader, which runs the counts, renders empty.
71/// [`unscoped`](Self::unscoped) counts every related record.
72///
73/// A panel refuses a count over a related model whose primary key spans several columns.
74#[derive_where(Clone, Debug)]
75pub struct CountColumn<M> {
76    pub(super) relation: Declared<M>,
77    /// Names the column's counts among the request's.
78    key: Arc<str>,
79    #[derive_where(skip(Debug))]
80    row_key: fn(&M) -> String,
81}
82
83impl<M> CountColumn<M>
84where
85    M: toasty::schema::Model + IntoExpr<M> + Send + Sync + 'static,
86{
87    /// Declare a column counting the records of `relation` that `S` shows.
88    pub fn of<S>(relation: RelationLens<M, Deferred<Vec<S::Model>>>) -> Self
89    where
90        S: OptionSource,
91    {
92        let scope: Scope<S::Model> = |cx| {
93            if ensure_option_access::<S>(cx).is_err() {
94                return Ok(None);
95            }
96            S::scoped_query(cx).map(Some)
97        };
98        let key = counts_key::<M, _>(&relation, std::any::type_name::<S>());
99        let restrict = counter(key.clone(), via(&relation), scope);
100        Self::declare(
101            Declared::of(&relation, ColumnWidth::Auto).scoped::<S>(restrict),
102            key,
103            composite::<S::Model>(),
104        )
105    }
106
107    /// Declare a column counting every record of `relation`, under no resource's query or
108    /// policy: for a related model no resource administers. A count shows no field of the
109    /// records.
110    pub fn unscoped<T>(relation: RelationLens<M, Deferred<Vec<T>>>) -> Self
111    where
112        T: toasty::schema::Model + Send + Sync + 'static,
113    {
114        let scope: Scope<T> = |_| Ok(Some(Query::all()));
115        let key = counts_key::<M, _>(&relation, "");
116        let restrict = counter(key.clone(), via(&relation), scope);
117        Self::declare(
118            Declared::of(&relation, ColumnWidth::Auto).restricted(restrict),
119            key,
120            composite::<T>(),
121        )
122    }
123
124    fn declare(relation: Declared<M>, key: Arc<str>, composite: bool) -> Self {
125        let mut relation = relation.without_include().fieldless();
126        if composite && relation.misdeclared.is_none() {
127            relation.misdeclared = Some(DeclarationErrorKind::CompositeKeyCount {
128                column: relation.name.clone(),
129            });
130        }
131        Self {
132            relation,
133            key,
134            row_key: pk::pk_text::<M>,
135        }
136    }
137}
138
139impl<M> CountColumn<M> {
140    /// The row's count, or `None` when no count ran for it.
141    pub(super) fn loaded_text(&self, cx: &Cx, row: &M) -> Option<String> {
142        counts(cx, crate::tenancy::tenant_id(cx))
143            .get(&self.key, &(self.row_key)(row))
144            .map(|count| count.to_string())
145    }
146}
147
148/// The path from `M` to the records `relation` holds, or `None` when it names no single field.
149fn via<M, T>(relation: &RelationLens<M, Deferred<Vec<T>>>) -> Option<Path<M, List<T>>>
150where
151    M: toasty::schema::Model,
152{
153    relation.index.map(M::path_field::<List<T>>)
154}
155
156/// Whether `T`'s primary key spans several columns, which [`linked_to`] matches none of.
157fn composite<T: toasty::schema::Model>() -> bool {
158    pk::pk_is_composite::<T>()
159}
160
161/// What names a column's counts among the request's: the model, the relation and the source,
162/// since two columns over one relation counted under different sources count apart.
163fn counts_key<M, R>(relation: &RelationLens<M, R>, source: &str) -> Arc<str> {
164    let field = relation.field().unwrap_or_default();
165    Arc::from(format!("{}.{field}:{source}", std::any::type_name::<M>()))
166}
167
168/// Counts each row's records `via` holds that `scope` returns, and records the counts for the
169/// request under `key`.
170fn counter<M, T>(key: Arc<str>, via: Option<Path<M, List<T>>>, scope: Scope<T>) -> Restrict<M>
171where
172    M: toasty::schema::Model + IntoExpr<M> + Send + Sync + 'static,
173    T: toasty::schema::Model + Send + Sync + 'static,
174{
175    Arc::new(move |cx, rows, ex| {
176        let (key, via) = (key.clone(), via.clone());
177        Box::pin(async move {
178            let Some(via) = via else {
179                return Ok(());
180            };
181            let store = counts(cx, crate::tenancy::tenant_id(cx));
182            for row in rows {
183                let id = pk::pk_text(row);
184                if store.get(&key, &id).is_some() {
185                    continue;
186                }
187                let Some(query) = scope(cx)? else {
188                    return Ok(());
189                };
190                let count = crate::toasty_compat::count(
191                    query.filter(linked_to(row, via.clone())),
192                    &mut *ex,
193                )
194                .await
195                .map_err(crate::error::unavailable)?;
196                store.insert(&key, id, count);
197            }
198            Ok(())
199        })
200    })
201}
202
203/// The counts the request's count columns ran, by column and row.
204#[derive(Default)]
205struct Counts(Mutex<HashMap<(Arc<str>, String), u64>>);
206
207impl Counts {
208    fn get(&self, key: &Arc<str>, row: &str) -> Option<u64> {
209        self.0
210            .lock()
211            .unwrap_or_else(PoisonError::into_inner)
212            .get(&(key.clone(), row.to_string()))
213            .copied()
214    }
215
216    fn insert(&self, key: &Arc<str>, row: String, count: u64) {
217        self.0
218            .lock()
219            .unwrap_or_else(PoisonError::into_inner)
220            .insert((key.clone(), row), count);
221    }
222}
223
224/// The request's [`Counts`] in `tenant`.
225#[topcoat::context::memoize]
226fn counts(cx: &Cx, _tenant: Option<crate::TenantId>) -> Arc<Counts> {
227    let _ = cx;
228    Arc::default()
229}