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