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