ash_domain/query.rs
1//! Backend-agnostic reads: a [`Query`] is a **bag of parameters**, not a
2//! hand-built filter tree.
3//!
4//! A read names a `resource` and carries a `params` [`Record`] — an opaque bag
5//! whose meaning is owned by the resource's read-action `Preparation`s and,
6//! ultimately, by the [`DataLayer`](crate::datalayer::DataLayer) that receives
7//! it. The core does **not** define a filter algebra: a layer is free to
8//! interpret the bag as a SQL `WHERE`, an index scan, a REST call, or a custom
9//! wire frame. How a well-formed bag becomes a native read is entirely the
10//! layer's business.
11//!
12//! What the core *does* own are a few executor-driven concerns that ride
13//! alongside the bag:
14//!
15//! - [`tenant`](Query::tenant) — a discriminator (not a filter) the domain sets
16//! from the [`Context`](crate::Context); a partitioning layer reads it directly.
17//! - [`limit`](Query::limit) — the **row bound**: a hard ceiling on how many rows
18//! the layer may return. Unlike a param the layer is free to ignore, this one
19//! is part of the layer contract, and the domain checks it on the way back.
20//! The domain also sets it itself, from
21//! [`DomainConfig::max_rows`](crate::DomainConfig::max_rows), when a caller
22//! leaves it unset — so a read is bounded whether or not the caller thought
23//! about it.
24//! - [`sort`](Query::sort) with [`after`](Query::after) or
25//! [`offset`](Query::offset) — the **ordering and paging** contract. A page
26//! needs an order, so a bound without a sort is an arbitrary subset; on top of
27//! an order a caller resumes either by keyset cursor (forward-only, stable
28//! under concurrent writes) or by offset (random access to page *n*, at the
29//! cost of a boundary that moves). Never both — the domain refuses a query
30//! carrying two positions.
31//! - [`load`](Query::load) / [`aggregates`](Query::aggregate_names) /
32//! [`computed`](Query::computed) — relationship loads and derived values the
33//! *domain* resolves after the layer returns, over the abstract data layer.
34//! - A small set of **reserved param keys** (see [`reserved`]) the executor
35//! writes into `params` for its own internal reads — a resolved key-set
36//! ([`reserved::IN`], used by relationship loads) and an unresolved
37//! relationship filter ([`reserved::RELATES`], which the domain rewrites into a
38//! key-set before the layer sees it). A layer must honour [`reserved::IN`] for
39//! relationship loading to work; everything else in `params` is the layer's own
40//! convention.
41//!
42//! There is no in-core query evaluation: a layer that cannot execute a bag reads
43//! what it can and is responsible for keeping any degradation explicit. The
44//! reference [`InMemoryDataLayer`](crate::datalayer::memory::InMemoryDataLayer)
45//! defines its own private interpretation of the bag.
46
47use crate::error::Result;
48use crate::value::{IntoRecord, Record, Value};
49
50/// Reserved param keys the [`Domain`](crate::Domain) writes into
51/// [`Query::params`] for its own internal reads.
52///
53/// These are the one part of the bag the core defines rather than the layer.
54/// Their names are prefixed `__ash_` so they cannot collide with a caller's or a
55/// layer's own params. A layer that wants relationship loading to work **must**
56/// interpret [`IN`](reserved::IN); the rest the domain resolves before the layer
57/// is reached.
58pub mod reserved {
59 /// A resolved key-set: "return the rows of this resource whose `attr` is one
60 /// of `keys`". Encoded as a [`Value::Map`](crate::Value::Map) under this key,
61 /// with a [`Str`](crate::Value::Str) `"attr"` and a
62 /// [`List`](crate::Value::List) `"keys"`.
63 ///
64 /// The executor writes this for every relationship-load hop (and as the
65 /// *result* of resolving a [`RELATES`] filter). A data
66 /// layer must honour it — see [`Query::key_set`](super::Query::key_set) to
67 /// read it back.
68 pub const IN: &str = "__ash_in";
69
70 /// An **unresolved** relationship filter: "rows related through
71 /// `relationship` to a row satisfying `predicate`". Encoded as a
72 /// [`Value::Map`](crate::Value::Map) under this key. The
73 /// [`Domain`](crate::Domain) resolves it into an [`IN`] key-set
74 /// (reading the related keys through the abstract data layer) *before* the
75 /// layer is asked to execute the read, so a layer never has to interpret it —
76 /// though a SQL layer may prefer to and compile a `JOIN`. See
77 /// [`Query::relates`](super::Query::relates) and
78 /// [`Query::relates_filter`](super::Query::relates_filter).
79 pub const RELATES: &str = "__ash_relates";
80
81 /// Map field: the attribute name in an [`IN`] key-set.
82 pub const IN_ATTR: &str = "attr";
83 /// Map field: the list of admitted values in an [`IN`] key-set.
84 pub const IN_KEYS: &str = "keys";
85 /// Map field: the relationship name in a [`RELATES`] filter.
86 pub const RELATES_REL: &str = "relationship";
87 /// Map field: the inner predicate bag in a [`RELATES`]
88 /// filter (a nested param [`Record`](crate::Record), encoded as a `Map`).
89 pub const RELATES_PREDICATE: &str = "predicate";
90}
91
92/// A declarative read over a resource: its resource name plus an opaque bag of
93/// parameters the data layer interprets.
94///
95/// Build one with [`Query::new`] and add params; the fields are public, so refine
96/// with struct-update syntax:
97///
98/// ```
99/// use ash_domain::query::Query;
100///
101/// let q = Query::new("note")
102/// .param("done", false)
103/// .param("limit", 10);
104/// # let _ = q;
105/// ```
106///
107/// What `done` and `limit` *mean* is up to the resource's read
108/// [`Preparation`](crate::action::Preparation)s and the
109/// [`DataLayer`](crate::datalayer::DataLayer); the core attaches no semantics to
110/// them.
111#[derive(Clone, Debug, Default)]
112pub struct Query {
113 /// The resource being read.
114 pub resource: String,
115 /// The opaque parameter bag the data layer interprets. May also carry the
116 /// executor's [`reserved`] keys.
117 pub params: Record,
118 /// Relationships to load alongside each record. Resolved by the
119 /// [`Domain`](crate::Domain) against the abstract data layer after the read;
120 /// a layer may also honour them natively.
121 pub load: Vec<String>,
122 /// The tenant this read is scoped to, if any. The domain sets it from the
123 /// [`Context`](crate::Context) for a tenant-scoped resource; a partitioning
124 /// layer can read it directly. It is a discriminator, not a filter param.
125 pub tenant: Option<Value>,
126 /// A hard upper bound on the number of rows the layer may return, or `None`
127 /// for "the caller set no bound" — in which case the domain sets one from
128 /// [`DomainConfig::max_rows`](crate::DomainConfig::max_rows) before the layer
129 /// ever sees the query.
130 ///
131 /// This is **not** an ordinary param a layer may ignore: it is a contract
132 /// point like [`reserved::IN`]. A layer must return at most this many rows
133 /// (a SQL `LIMIT`, a scan cut short, a page size on an API call); the domain
134 /// verifies the count on the way back and fails the read with
135 /// [`Error::DataLayer`](crate::Error::DataLayer) if the layer overran it,
136 /// rather than truncating and hiding the breach.
137 ///
138 /// `Some(0)` is a legitimate request for an empty result, not "unbounded" —
139 /// that is why this is a plain `u32` and not a `NonZeroU32`.
140 pub limit: Option<u32>,
141 /// Whether this is a sanctioned **cross-tenant** read — the domain dropped the
142 /// tenant predicate because the caller opted in via
143 /// [`Context::allow_cross_tenant`](crate::Context::allow_cross_tenant). A
144 /// partitioning ([`Layer`](crate::TenantStrategy::Layer)) data layer must read
145 /// across partitions when this is set; audit can see the read for what it is.
146 /// Never set on a global (non-tenant) resource — there is nothing to cross.
147 pub across_tenants: bool,
148 /// Names of declared [`Aggregate`](crate::aggregate::Aggregate)s to compute
149 /// alongside each row. Resolved by the domain; an unknown name is an error.
150 pub aggregate_names: Vec<String>,
151 /// Names of declared [`Computed`](crate::aggregate::Computed) fields to
152 /// compute for each row. Resolved by the domain; an unknown name is an error.
153 pub computed: Vec<String>,
154 /// The **sort order**, outermost key first, or empty for "the layer's
155 /// natural order".
156 ///
157 /// Like [`limit`](Query::limit) this is a contract point, not an ordinary
158 /// param: a layer that cannot sort by these keys must say so
159 /// ([`Error::Unsupported`](crate::Error::Unsupported)) rather than return
160 /// rows in some other order, because a bounded read of unordered rows is an
161 /// arbitrary subset rather than a page. The domain validates every key names
162 /// a declared attribute before the layer sees it.
163 pub sort: Vec<SortKey>,
164 /// Resume a previous page: return only rows that fall **after** this cursor
165 /// in the query's [`sort`](Query::sort) order.
166 ///
167 /// Produced by [`Page::cursor`](crate::Page::cursor) from a previous read and passed back
168 /// verbatim. The layer decodes it with [`Cursor::keys`] and turns it into a
169 /// keyset predicate. Meaningless without a `sort`, which is why the domain
170 /// rejects the combination.
171 pub after: Option<Cursor>,
172 /// Skip this many rows of the sorted result set before returning any — the
173 /// **offset** of offset/limit pagination.
174 ///
175 /// Like [`limit`](Query::limit) and [`sort`](Query::sort) this is a contract
176 /// point, not an ordinary param: a layer must skip exactly this many rows of
177 /// the order it was asked for (a SQL `OFFSET`, a scan advanced before
178 /// collecting), or decline with
179 /// [`Error::Unsupported`](crate::Error::Unsupported).
180 ///
181 /// Offset paging is the weaker of the two models the core offers, and
182 /// deliberately so: rows inserted or removed before the offset between two
183 /// pages shift every later row, so a caller walking pages can see a row
184 /// twice or miss it entirely. It is here because it buys what a cursor
185 /// cannot — random access to page *n* — which is what a numbered pager
186 /// needs. Prefer [`after`](Query::after) whenever the caller only ever walks
187 /// forward. The two are mutually exclusive: a query carrying both describes
188 /// two different positions, and the domain rejects it.
189 ///
190 /// Meaningless without a `sort` for the same reason [`limit`](Query::limit)
191 /// is — skipping rows of an arbitrary order yields an arbitrary subset — so
192 /// the domain rejects that combination too.
193 pub offset: Option<u32>,
194}
195
196/// The direction of one [`SortKey`].
197#[derive(Clone, Copy, Debug, PartialEq, Eq)]
198pub enum SortDirection {
199 /// Smallest first.
200 Ascending,
201 /// Largest first.
202 Descending,
203}
204
205/// One key of a [`Query`]'s sort order: an attribute name and a direction.
206#[derive(Clone, Debug, PartialEq, Eq)]
207pub struct SortKey {
208 /// The attribute to sort by. The domain checks it is declared on the
209 /// resource before the layer sees the query.
210 pub attribute: String,
211 /// Which way to sort it.
212 pub direction: SortDirection,
213}
214
215impl SortKey {
216 /// Sort by `attribute`, smallest first.
217 pub fn asc(attribute: impl Into<String>) -> Self {
218 Self {
219 attribute: attribute.into(),
220 direction: SortDirection::Ascending,
221 }
222 }
223
224 /// Sort by `attribute`, largest first.
225 pub fn desc(attribute: impl Into<String>) -> Self {
226 Self {
227 attribute: attribute.into(),
228 direction: SortDirection::Descending,
229 }
230 }
231}
232
233/// An opaque position in a sorted result set — the "resume here" token of
234/// keyset pagination.
235///
236/// A cursor carries the **sort-key values of the last row of a page**, nothing
237/// else: no offset, no snapshot, no server state. A layer resumes by asking for
238/// rows ordered after those values, which is why paging this way neither skips
239/// nor repeats rows when the underlying data changes between pages — the defect
240/// an `OFFSET` has and this does not.
241///
242/// It is deliberately **opaque to callers**: build one only with
243/// [`Page::cursor`](crate::Page::cursor), and read it only from inside a data layer with
244/// [`keys`](Cursor::keys). Callers pass it back verbatim.
245#[derive(Clone, Debug, PartialEq)]
246pub struct Cursor {
247 /// The last row's value for each key of the query's sort order, in the same
248 /// order as [`Query::sort`].
249 keys: Vec<Value>,
250}
251
252impl Cursor {
253 /// The sort-key values this cursor points at, in [`Query::sort`] order —
254 /// what a [`DataLayer`](crate::datalayer::DataLayer) needs to build its
255 /// keyset predicate.
256 pub fn keys(&self) -> &[Value] {
257 &self.keys
258 }
259
260 /// Build a cursor from raw sort-key values. For a data layer that
261 /// round-trips a cursor through its own encoding; ordinary callers use
262 /// [`Page::cursor`](crate::Page::cursor).
263 pub fn from_keys(keys: Vec<Value>) -> Self {
264 Self { keys }
265 }
266}
267
268impl Query {
269 /// Start a query against `resource` with an empty param bag.
270 pub fn new(resource: impl Into<String>) -> Self {
271 Self {
272 resource: resource.into(),
273 ..Default::default()
274 }
275 }
276
277 /// Set a param in the bag, consuming and returning `self` for chaining.
278 pub fn param(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
279 self.params.insert(key, value);
280 self
281 }
282
283 /// Bound the read to at most `limit` rows.
284 ///
285 /// The layer must honour it (see [`Query::limit`]); the domain checks that it
286 /// did. A caller-set bound is taken as deliberate and passed through
287 /// untouched — the domain's own
288 /// [`max_rows`](crate::DomainConfig::max_rows) ceiling only fills in for a
289 /// read that carries no bound of its own.
290 ///
291 /// ```
292 /// use ash_domain::Query;
293 /// let q = Query::new("note").limit(50);
294 /// assert_eq!(q.limit, Some(50));
295 /// ```
296 #[must_use]
297 pub fn limit(mut self, limit: u32) -> Self {
298 self.limit = Some(limit);
299 self
300 }
301
302 /// Sort the read by `attribute`, ascending — appending to any sort keys
303 /// already set, so repeated calls build a compound order.
304 ///
305 /// ```
306 /// use ash_domain::Query;
307 /// let q = Query::new("note").sort_asc("created_at").sort_desc("id");
308 /// assert_eq!(q.sort.len(), 2);
309 /// ```
310 #[must_use]
311 pub fn sort_asc(mut self, attribute: impl Into<String>) -> Self {
312 self.sort.push(SortKey::asc(attribute));
313 self
314 }
315
316 /// Sort the read by `attribute`, descending. See
317 /// [`sort_asc`](Query::sort_asc).
318 #[must_use]
319 pub fn sort_desc(mut self, attribute: impl Into<String>) -> Self {
320 self.sort.push(SortKey::desc(attribute));
321 self
322 }
323
324 /// Resume after `cursor` — the next page of the read that produced it.
325 ///
326 /// The sort order must match the one the cursor came from; the domain
327 /// refuses a cursor on an unsorted read, since there is no order to resume.
328 #[must_use]
329 pub fn after(mut self, cursor: Cursor) -> Self {
330 self.after = Some(cursor);
331 self
332 }
333
334 /// Skip the first `offset` rows of the sorted result set.
335 ///
336 /// The offset-paging counterpart of [`after`](Query::after), and mutually
337 /// exclusive with it: page `n` of a numbered pager is
338 /// `.offset(n * page_size).limit(page_size)`. Requires a
339 /// [`sort`](Query::sort) — the domain rejects an offset without one, since
340 /// skipping rows of an unordered read skips arbitrary rows. See
341 /// [`Query::offset`] for why a cursor is the better default.
342 ///
343 /// ```
344 /// use ash_domain::Query;
345 /// let q = Query::new("note").sort_asc("id").offset(50).limit(25);
346 /// assert_eq!(q.offset, Some(50));
347 /// ```
348 #[must_use]
349 pub fn offset(mut self, offset: u32) -> Self {
350 self.offset = Some(offset);
351 self
352 }
353
354 /// Request `relationships` be loaded alongside each row.
355 pub fn load<I, S>(mut self, relationships: I) -> Self
356 where
357 I: IntoIterator<Item = S>,
358 S: Into<String>,
359 {
360 self.load.extend(relationships.into_iter().map(Into::into));
361 self
362 }
363
364 /// Request declared aggregates be computed for each row.
365 pub fn aggregates<I, S>(mut self, names: I) -> Self
366 where
367 I: IntoIterator<Item = S>,
368 S: Into<String>,
369 {
370 self.aggregate_names
371 .extend(names.into_iter().map(Into::into));
372 self
373 }
374
375 /// Request declared computed fields be computed for each row.
376 pub fn computed<I, S>(mut self, names: I) -> Self
377 where
378 I: IntoIterator<Item = S>,
379 S: Into<String>,
380 {
381 self.computed.extend(names.into_iter().map(Into::into));
382 self
383 }
384
385 // ── reserved-param helpers ────────────────────────────────────────────────
386
387 /// Build the reserved [`IN`](reserved::IN) key-set query: rows of `resource`
388 /// whose `attr` is one of `keys`. The executor uses this for relationship
389 /// loads; a layer reads it back with [`key_set`](Query::key_set).
390 pub fn key_set(resource: impl Into<String>, attr: impl Into<String>, keys: Vec<Value>) -> Self {
391 Query::new(resource).param(reserved::IN, in_param(attr.into(), keys))
392 }
393
394 /// Read this query's [`IN`](reserved::IN) key-set, if it carries one:
395 /// `(attr, keys)`. A data layer calls this to honour an executor-issued
396 /// relationship load.
397 pub fn as_key_set(&self) -> Option<(&str, &[Value])> {
398 let map = self.params.get(reserved::IN)?.as_map()?;
399 let attr = map.get(reserved::IN_ATTR)?.as_str()?;
400 let keys = map.get(reserved::IN_KEYS)?.as_list()?;
401 Some((attr, keys))
402 }
403
404 /// Build an **unresolved** [`RELATES`](reserved::RELATES) filter: rows related
405 /// through `relationship` to a row matching the `predicate` bag. The
406 /// [`Domain`](crate::Domain) resolves this into a key-set before the layer
407 /// runs; see [`relates_filter`](Query::relates_filter).
408 pub fn relates(
409 resource: impl Into<String>,
410 relationship: impl Into<String>,
411 predicate: Record,
412 ) -> Self {
413 let mut map = std::collections::BTreeMap::new();
414 map.insert(
415 reserved::RELATES_REL.to_string(),
416 Value::Str(relationship.into()),
417 );
418 map.insert(
419 reserved::RELATES_PREDICATE.to_string(),
420 Value::Map(predicate.0),
421 );
422 Query::new(resource).param(reserved::RELATES, Value::Map(map))
423 }
424
425 /// Read this query's unresolved [`RELATES`](reserved::RELATES) filter, if it
426 /// carries one: `(relationship, predicate)`. The domain uses this to decide
427 /// whether relationship-filter resolution is needed before a read.
428 pub fn relates_filter(&self) -> Option<(&str, Record)> {
429 let map = self.params.get(reserved::RELATES)?.as_map()?;
430 let relationship = map.get(reserved::RELATES_REL)?.as_str()?;
431 let predicate = map.get(reserved::RELATES_PREDICATE)?.as_map()?;
432 Some((relationship, Record(predicate.clone())))
433 }
434}
435
436/// Encode a [`reserved::IN`] key-set value: rows whose `attr` is one of `keys`.
437/// Shared by [`Query::key_set`] and the executor paths that fold a key-set into
438/// an existing param bag.
439pub(crate) fn in_param(attr: String, keys: Vec<Value>) -> Value {
440 let mut map = std::collections::BTreeMap::new();
441 map.insert(reserved::IN_ATTR.to_string(), Value::Str(attr));
442 map.insert(reserved::IN_KEYS.to_string(), Value::List(keys));
443 Value::Map(map)
444}
445
446/// A caller-side read input: the layer-interpreted param bag — and nothing
447/// else.
448///
449/// This is the input for the erased read path,
450/// [`ActionInput::read`](crate::ActionInput::read). Where a hand-built [`Query`]
451/// can carry a resource name the typed call site contradicts (silently
452/// overwritten) and `load`/`aggregates`/`computed` requests the erased path must
453/// reject, a `Filter` can carry neither: the resource is always named by the
454/// call site's type parameter, and relationship loads / derived values are only
455/// expressible on the path that resolves them, [`Domain::read`](crate::Domain::read).
456///
457/// ```
458/// use ash_domain::{ActionInput, Filter};
459///
460/// let input = ActionInput::read(
461/// Filter::new().param("owner", "alice").param("limit", 50),
462/// );
463/// # let _ = input;
464/// ```
465#[derive(Clone, Debug, Default)]
466pub struct Filter {
467 params: Record,
468}
469
470impl Filter {
471 /// An empty filter: an unconstrained read of the resource.
472 pub fn new() -> Self {
473 Self::default()
474 }
475
476 /// Set a param in the bag. What it means is the data layer's convention,
477 /// exactly as [`Query::param`] — the core attaches no semantics.
478 pub fn param(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
479 self.params.insert(key, value);
480 self
481 }
482
483 /// Merge a whole **typed param bag** into the filter — the compile-checked
484 /// sibling of [`param`](Filter::param). `params` is anything [`IntoRecord`]
485 /// (typically a `#[derive(IntoRecord)]` struct you define), so your layer's
486 /// param convention gets field names and types the compiler checks instead
487 /// of strings. The core still attaches no semantics to any key — the struct
488 /// is a contract between you and your data layer, exactly as with
489 /// [`param`](Filter::param). A key set both ways keeps the later value.
490 ///
491 /// Fallible because [`IntoRecord`] is: an out-of-`i64`-range integer field
492 /// has no lossless neutral form and fails loudly here.
493 ///
494 /// ```
495 /// # fn main() -> ash_domain::Result<()> {
496 /// use ash_domain::{ActionInput, Filter, IntoRecord};
497 ///
498 /// #[derive(IntoRecord)]
499 /// struct OpenTodos {
500 /// done: bool,
501 /// limit: i64,
502 /// }
503 ///
504 /// let input = ActionInput::read(
505 /// Filter::new().params(OpenTodos { done: false, limit: 50 })?,
506 /// );
507 /// # let _ = input;
508 /// # Ok(())
509 /// # }
510 /// ```
511 pub fn params(mut self, params: impl IntoRecord) -> Result<Self> {
512 self.params.0.extend(params.into_record()?.0);
513 Ok(self)
514 }
515}
516
517/// A [`Filter`] is a [`Query`] with no resource name; the executor stamps the
518/// resource of the action it runs against (it does so for every read).
519impl From<Filter> for Query {
520 fn from(filter: Filter) -> Self {
521 Query {
522 params: filter.params,
523 ..Query::default()
524 }
525 }
526}