1use super::{Decoder, Entity, Error, Memory, Query, QueryPage, SingleResult, fetch_rows};
4use std::marker::PhantomData;
5
6pub 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
38pub trait SelectColumns: Entity {
40 type Columns;
42 #[doc(hidden)]
43 const COLUMNS: Self::Columns;
44}
45
46mod sealed {
47 pub trait Sealed {}
48}
49
50pub trait Selection<E>: sealed::Sealed {
52 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
76macro_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
104pub 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 #[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 pub fn fetch(self) -> Result<QueryPage<S::Output>, Error> {
130 observe!(query, { selected_page(self.query, &self.selection) })
131 }
132
133 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 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}