1use std::{any::TypeId, collections::HashMap, future::Future, pin::Pin, sync::Arc};
4
5use toasty::stmt::{Expr, IntoExpr, List, Path};
6use topcoat::{Result, context::Cx};
7
8use super::{ErasedInput, InputResult, InputSpec, Resource, can, scoped_query};
9use crate::{
10 form::{FieldError, FormScalar},
11 naming::{sentence_case, type_short_name},
12 policy::Ability,
13 schema::{Field, Schema},
14 toasty_compat::{
15 join::{JoinTable, linked_to},
16 model::{self, AppSchema, ModelPath},
17 pk,
18 },
19};
20
21pub struct Relation<P> {
50 pub(crate) child: TypeId,
51 pub(crate) child_name: &'static str,
52 pub(crate) label: Option<String>,
53 pub(crate) kind: RelationKind<P>,
54 bind: BindFn<P>,
55 pub(crate) misdeclared: Option<crate::DeclarationErrorKind>,
57}
58
59pub(crate) enum RelationKind<P> {
61 HasMany { foreign_key: String },
63 ManyToMany(Links<P>),
65}
66
67type BindFn<P> = Arc<dyn Fn(&P) -> (Expr<bool>, String) + Send + Sync>;
69
70type LinkFuture<'a> = Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
72
73pub(crate) struct Links<P> {
76 pub(crate) field: String,
78 pub(crate) input: InputSpec,
80 pub(crate) attach: LinkFn<P, String>,
83 pub(crate) detach: LinkFn<P, Vec<String>>,
86}
87
88type LinkFn<P, K> = Arc<
90 dyn for<'a> Fn(&'a Cx, &'a P, K, &'a mut dyn toasty::Executor) -> LinkFuture<'a> + Send + Sync,
91>;
92
93const ATTACH_KEY: &str = "record";
95
96pub trait ForeignKey<K>:
99 sealed::Sealed<K> + IntoExpr<Self> + FormScalar + Send + Sync + 'static
100{
101}
102
103impl<K> ForeignKey<K> for K where K: IntoExpr<K> + FormScalar + Send + Sync + 'static {}
104
105impl<K> ForeignKey<K> for Option<K> where
106 Option<K>: IntoExpr<Self> + FormScalar + Send + Sync + 'static
107{
108}
109
110mod sealed {
111 pub trait Sealed<K> {}
112
113 impl<K> Sealed<K> for K {}
114
115 impl<K> Sealed<K> for Option<K> {}
116}
117
118impl<P> Relation<P>
119where
120 P: toasty::schema::Model + IntoExpr<P> + 'static,
121{
122 pub fn has_many<C>(foreign_key: Path<C::Model, impl ForeignKey<P::PrimaryKey>>) -> Self
148 where
149 C: Resource,
150 {
151 Self::bound_by::<C, _>(foreign_key)
152 }
153
154 fn bound_by<C, T>(foreign_key: Path<C::Model, T>) -> Self
155 where
156 C: Resource,
157 T: ForeignKey<P::PrimaryKey>,
158 {
159 let (column, misdeclared) = match model::field::<C::Model>(&ModelPath::of(&foreign_key)) {
161 Ok(field) => (field.name, None),
162 Err(error) => (String::new(), Some(error)),
163 };
164 Self {
165 child: TypeId::of::<C>(),
166 child_name: std::any::type_name::<C>(),
167 label: None,
168 kind: RelationKind::HasMany {
169 foreign_key: column,
170 },
171 misdeclared,
172 bind: Arc::new(move |owner| {
173 let scope = foreign_key.clone().eq(pk::pk_expr::<P, T>(owner));
174 (scope, pk::pk_text(owner))
175 }),
176 }
177 }
178
179 pub fn belongs_to_many<C>(via: impl Into<Path<P, List<C::Model>>>) -> Self
214 where
215 C: Resource,
216 P: Send + Sync,
217 {
218 let via: Path<P, List<C::Model>> = via.into();
219 let (field, misdeclared) = match model::field::<P>(&ModelPath::of(&via)) {
220 Ok(field) => (field.name, None),
221 Err(error) => (String::new(), Some(error)),
222 };
223 let attach_via = via.clone();
224 let attach_field = field.clone();
225 let detach_via = via.clone();
226 let detach_field = field.clone();
227 Self {
228 child: TypeId::of::<C>(),
229 child_name: std::any::type_name::<C>(),
230 label: None,
231 kind: RelationKind::ManyToMany(Links {
232 field,
233 input: InputSpec {
234 schema: attach_schema::<C>,
235 takes_input: true,
236 parse: parse_attach,
237 },
238 attach: Arc::new(move |cx, owner, key, ex| {
239 let (via, field) = (attach_via.clone(), attach_field.clone());
240 Box::pin(async move { attach::<P, C>(cx, owner, via, &field, key, ex).await })
241 }),
242 detach: Arc::new(move |cx, owner, keys, ex| {
243 let (via, field) = (detach_via.clone(), detach_field.clone());
244 Box::pin(async move { detach::<P, C>(cx, owner, via, &field, keys, ex).await })
245 }),
246 }),
247 misdeclared,
248 bind: Arc::new(move |owner| (linked_to(owner, via.clone()), pk::pk_text(owner))),
249 }
250 }
251}
252
253fn attach_schema<C: Resource>() -> Schema {
255 Schema::new(
256 Field::choice_input(ATTACH_KEY)
257 .label(sentence_case(type_short_name::<C::Model>()))
258 .relationship::<C>()
259 .searchable(),
260 )
261}
262
263fn parse_attach(_cx: &Cx, values: &HashMap<String, String>) -> InputResult {
266 match values.get(ATTACH_KEY).map(|key| key.trim()) {
267 Some(key) if !key.is_empty() => Ok(Box::new(key.to_string()) as ErasedInput),
268 _ => Err(vec![FieldError::required(ATTACH_KEY)]),
269 }
270}
271
272fn join_table<P: toasty::schema::Model>(cx: &Cx, field: &str) -> Result<JoinTable> {
274 let schema = AppSchema::of(cx).ok_or_else(|| {
275 crate::error::declaration(crate::DeclarationErrorKind::MissingDb.to_string())
276 })?;
277 JoinTable::of::<P>(&schema, field).map_err(|fault| {
278 crate::error::declaration(
279 crate::DeclarationErrorKind::ManyToMany {
280 field: field.to_string(),
281 fault,
282 }
283 .to_string(),
284 )
285 })
286}
287
288async fn attach<P, C>(
290 cx: &Cx,
291 owner: &P,
292 via: Path<P, List<C::Model>>,
293 field: &str,
294 key: String,
295 ex: &mut dyn toasty::Executor,
296) -> Result<()>
297where
298 P: toasty::schema::Model + IntoExpr<P>,
299 C: Resource,
300{
301 let join = join_table::<P>(cx, field)?;
302 let Some(record) = pk::pk_eq_expr::<C::Model>(&key) else {
303 return Err(topcoat::router::error::not_found().into());
304 };
305 let linked = scoped_query::<C>(cx)?
306 .filter(record)
307 .filter(linked_to(owner, via))
308 .first()
309 .exec(&mut *ex)
310 .await
311 .map_err(crate::error::unavailable)?;
312 if linked.is_none() {
313 join.link(owner, &[key], ex)
314 .await
315 .map_err(|error| -> topcoat::Error { error.into() })?;
316 }
317 Ok(())
318}
319
320async fn detach<P, C>(
322 cx: &Cx,
323 owner: &P,
324 via: Path<P, List<C::Model>>,
325 field: &str,
326 keys: Vec<String>,
327 ex: &mut dyn toasty::Executor,
328) -> Result<()>
329where
330 P: toasty::schema::Model + IntoExpr<P>,
331 C: Resource,
332{
333 let join = join_table::<P>(cx, field)?;
334 let ids: Vec<&str> = keys.iter().map(String::as_str).collect();
335 let Some(records) = pk::pk_in_expr::<C::Model>(&ids) else {
336 return Err(topcoat::router::error::not_found().into());
337 };
338 let linked = scoped_query::<C>(cx)?
339 .filter(records)
340 .filter(linked_to(owner, via))
341 .exec(&mut *ex)
342 .await
343 .map_err(crate::error::unavailable)?;
344 if linked.len() != keys.len() {
345 return Err(topcoat::router::error::not_found().into());
346 }
347 if linked
349 .iter()
350 .any(|record| !can::<C>(cx, Ability::View(record)))
351 {
352 return Err(topcoat::router::error::forbidden().into());
353 }
354 join.unlink(owner, &keys, ex)
355 .await
356 .map_err(|error| -> topcoat::Error { error.into() })
357}
358
359impl<P> Relation<P> {
360 #[must_use]
362 pub fn label(mut self, label: impl Into<String>) -> Self {
363 self.label = Some(label.into());
364 self
365 }
366
367 pub(crate) fn bind(&self, owner: &P) -> (Expr<bool>, String) {
369 (self.bind)(owner)
370 }
371}
372
373impl<P> Relation<P> {
374 pub(crate) fn links(&self) -> Option<&Links<P>> {
376 match &self.kind {
377 RelationKind::ManyToMany(links) => Some(links),
378 RelationKind::HasMany { .. } => None,
379 }
380 }
381}
382
383impl<P> std::fmt::Debug for Relation<P> {
384 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
385 let mut debug = f.debug_struct("Relation");
386 debug
387 .field("child", &self.child_name)
388 .field("label", &self.label);
389 match &self.kind {
390 RelationKind::HasMany { foreign_key } => debug.field("foreign_key", foreign_key),
391 RelationKind::ManyToMany(links) => debug.field("via", &links.field),
392 };
393 debug.finish_non_exhaustive()
394 }
395}