Skip to main content

ic_db/store/query/
select.rs

1//! Typed column selection at the boundary of the shared projection executor.
2
3use super::{Decoder, Entity, Error, Memory, Query, QueryPage, fetch_rows};
4use std::marker::PhantomData;
5
6/// A column of entity `E` whose stored value decodes to `T`.
7pub struct Column<E, T> {
8    position: u8,
9    decode: fn(&mut Decoder<'_>) -> Result<T, Error>,
10    entity: PhantomData<fn(E)>,
11}
12
13impl<E, T> Copy for Column<E, T> {}
14impl<E, T> Clone for Column<E, T> {
15    fn clone(&self) -> Self {
16        *self
17    }
18}
19
20impl<E, T> Column<E, T> {
21    #[doc(hidden)]
22    pub const fn new(position: u8, decode: fn(&mut Decoder<'_>) -> Result<T, Error>) -> Self {
23        Self {
24            position,
25            decode,
26            entity: PhantomData,
27        }
28    }
29}
30
31/// Field handles supplied to a selection by an authored entity.
32pub trait SelectColumns: Entity {
33    /// The generated fields, with their exact stored Rust types.
34    type Columns;
35    #[doc(hidden)]
36    const COLUMNS: Self::Columns;
37}
38
39mod sealed {
40    pub trait Sealed {}
41}
42
43/// A single selected column or a tuple of two to four columns from one entity.
44pub trait Selection<E>: sealed::Sealed {
45    /// The value returned for each matching row.
46    type Output;
47    #[doc(hidden)]
48    fn positions(&self) -> impl AsRef<[u8]>;
49    #[doc(hidden)]
50    fn decode(&self, reader: &mut Decoder<'_>, order: &[usize]) -> Result<Self::Output, Error>;
51}
52
53impl<E, T> sealed::Sealed for Column<E, T> {}
54impl<E, T> Selection<E> for Column<E, T> {
55    type Output = T;
56    fn positions(&self) -> impl AsRef<[u8]> {
57        [self.position]
58    }
59    fn decode(&self, reader: &mut Decoder<'_>, _: &[usize]) -> Result<T, Error> {
60        (self.decode)(reader)
61    }
62}
63
64// Projected bytes are in durable field order. Decode each field once in that
65// order, then assemble the tuple in the caller's order.
66macro_rules! tuple_selection {
67    ($( $index:tt $ty:ident $slot:ident ),+) => {
68        impl<E, $($ty),+> sealed::Sealed for ($(Column<E, $ty>,)+) {}
69        impl<E, $($ty),+> Selection<E> for ($(Column<E, $ty>,)+) {
70            type Output = ($($ty,)+);
71            fn positions(&self) -> impl AsRef<[u8]> { [$(self.$index.position),+] }
72            fn decode(&self, reader: &mut Decoder<'_>, order: &[usize]) -> Result<Self::Output, Error> {
73                $(let mut $slot = None;)+
74                for &index in order {
75                    match index {
76                        $($index => $slot = Some((self.$index.decode)(reader)?),)+
77                        _ => return Err(Error::Corrupt),
78                    }
79                }
80                Ok(($($slot.ok_or(Error::Corrupt)?,)+))
81            }
82        }
83    };
84}
85tuple_selection!(0 A a, 1 B b);
86tuple_selection!(0 A a, 1 B b, 2 C c);
87tuple_selection!(0 A a, 1 B b, 2 C c, 3 D d);
88
89/// A bounded query with its result columns selected.
90pub struct SelectedQuery<'a, E, M: Memory, S> {
91    query: Query<'a, E, M>,
92    selection: S,
93}
94
95impl<'a, E: SelectColumns, M: Memory> Query<'a, E, M> {
96    /// Select a field or tuple before fetching, e.g. `.select(|e| (e.id, e.name))`.
97    /// The selector runs once and receives field handles. Apply filters, order and cursor first.
98    #[must_use]
99    pub fn select<S: Selection<E>>(
100        self,
101        fields: impl FnOnce(E::Columns) -> S,
102    ) -> SelectedQuery<'a, E, M, S> {
103        SelectedQuery {
104            query: self,
105            selection: fields(E::COLUMNS),
106        }
107    }
108}
109
110impl<E: Entity, M: Memory, S: Selection<E>> SelectedQuery<'_, E, M, S> {
111    /// Fetch the selected values with ordinary query bounds and continuation.
112    /// # Errors
113    /// Repeated columns refuse. Ordinary query, projection and cursor errors apply.
114    pub fn fetch(self) -> Result<QueryPage<S::Output>, Error> {
115        observe!(query, { selected_page(self.query, &self.selection) })
116    }
117
118    /// Return the first selected value in query order.
119    /// # Errors
120    /// Returns `Limit` if the work budget ends before a match or proven exhaustion.
121    /// Ordinary selection and query errors apply.
122    pub fn first(self) -> Result<Option<S::Output>, Error> {
123        self.query
124            .first_with(|query| selected_page(query, &self.selection))
125    }
126
127    /// Return the sole selected result, or `None` on a proven miss.
128    /// # Errors
129    /// A second match returns `MultipleMatches`; an inconclusive scan returns
130    /// `Limit`. A continuation is refused. Ordinary selection and query errors apply.
131    pub fn try_one(self) -> Result<Option<S::Output>, Error> {
132        self.query
133            .try_one_with(|query| selected_page(query, &self.selection))
134    }
135}
136
137fn selected_page<E: Entity, M: Memory, S: Selection<E>>(
138    query: Query<'_, E, M>,
139    selection: &S,
140) -> Result<QueryPage<S::Output>, Error> {
141    let positions = selection.positions();
142    let positions = positions.as_ref();
143    let raw = fetch_rows(
144        &*query.db.read()?,
145        E::SCHEMA,
146        query.request,
147        Some(super::Projection::Columns(positions)),
148    )?;
149    let mut slots = [0, 1, 2, 3];
150    let order = &mut slots[..positions.len()];
151    order.sort_unstable_by_key(|&index| positions[index]);
152    raw.decode_with(|reader| selection.decode(reader, order))
153}