tablo_core/column/relation/
count.rs1use 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
23type Scope<T> = fn(&Cx) -> Result<Option<Query<List<T>>>>;
26
27#[derive_where(Clone, Debug)]
75pub struct CountColumn<M> {
76 pub(super) relation: Declared<M>,
77 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 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 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 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
148fn 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
156fn composite<T: toasty::schema::Model>() -> bool {
158 pk::pk_is_composite::<T>()
159}
160
161fn 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
168fn 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#[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#[topcoat::context::memoize]
226fn counts(cx: &Cx, _tenant: Option<crate::TenantId>) -> Arc<Counts> {
227 let _ = cx;
228 Arc::default()
229}