Skip to main content

tablo_core/resource/action/
keys.rs

1//! [`filter_keys`]: the predicate an action's `run` writes its records through in one statement.
2
3use toasty::stmt::{Expr, IntoExpr};
4
5use crate::toasty_compat::pk::pk_set_filter;
6
7/// The predicate selecting each of `records` by its primary key, so that an action writes the
8/// same change to all of them in one statement rather than one per record:
9///
10/// ```rust
11/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
12/// # struct Post {
13/// #     #[key] #[auto] id: uuid::Uuid,
14/// #     title: String,
15/// #     status: String,
16/// # }
17/// # use tablo_core::{Action, NoForm, Resource, filter_keys};
18/// # use toasty::Executor;
19/// # use topcoat::{Result, context::Cx};
20/// # struct PostResource;
21/// # impl Resource for PostResource {
22/// #     type Model = Post;
23/// #     type Form = NoForm<Post>;
24/// # }
25/// # struct Publish;
26/// # impl Action<PostResource> for Publish {
27/// #     type Input = ();
28/// #     const NAME: &'static str = "publish";
29/// async fn run(
30///     _cx: &Cx,
31///     posts: &[Post],
32///     _: (),
33///     ex: &mut dyn Executor,
34/// ) -> Result<tablo_core::Outcome, tablo_core::WriteError<()>> {
35///     Post::filter(filter_keys(posts))
36///         .update()
37///         .status("published".to_string())
38///         .exec(ex)
39///         .await?;
40///     Ok(tablo_core::Outcome::done())
41/// }
42/// # }
43/// ```
44///
45/// A single key selects through one `IN` list, a composite key through one equality per record,
46/// and no record selects no row. The predicate scopes nothing itself: it selects exactly the
47/// records given, which for an [`Action`](crate::Action) the pipeline loaded through the
48/// tenant-scoped query and checked against the policy, no more than
49/// [`Limits::bulk_records`](crate::Limits::bulk_records) of them.
50///
51/// The statement binds a value per key, which databases bound: SQLite takes 32,766 values, and
52/// nests the equalities of composite keys no more than 1,000 deep. A set the caller loaded itself,
53/// as a [`HeaderAction`](crate::HeaderAction) does, has no such bound: write it in chunks, a few
54/// hundred records each.
55pub fn filter_keys<M>(records: &[M]) -> Expr<bool>
56where
57    M: toasty::schema::Model + IntoExpr<M>,
58{
59    pk_set_filter(&records.iter().collect::<Vec<_>>())
60}