Skip to main content

coven_database/
read.rs

1//! Borrowed reads and their connection-scoped SQL capability.
2
3use crate::sqlite::StoreSql;
4use crate::{database, DbError, Mode, StoreDatabase, Writer};
5use coven_foundation::task::CarriesBug;
6use sqlive::rusqlite::{Params, Row};
7use std::{
8    any::Any,
9    future::Future,
10    pin::Pin,
11    task::{Context, Poll},
12};
13
14/// SQL access to one read-only snapshot. The connection and internal tables
15/// remain private; even SQL with RETURNING cannot write through this context.
16pub struct SqlReadContext<'connection> {
17    database: &'connection StoreSql,
18}
19
20impl<'connection> SqlReadContext<'connection> {
21    pub(crate) fn new(database: &'connection StoreSql) -> Self {
22        Self { database }
23    }
24
25    /// Map the first result row of an ordinary SQL read.
26    pub fn query_row<T, P, F>(&self, sql: &str, params: P, map: F) -> sqlive::rusqlite::Result<T>
27    where
28        P: Params,
29        F: FnOnce(&Row<'_>) -> sqlive::rusqlite::Result<T>,
30    {
31        self.database.app_query_row(sqlive::Recorded::Yes, sql, params, map)
32    }
33
34    /// Map all result rows of an ordinary SQL read.
35    pub fn query<T, P, F>(&self, sql: &str, params: P, map: F) -> sqlive::rusqlite::Result<Vec<T>>
36    where
37        P: Params,
38        F: FnMut(&Row<'_>) -> sqlive::rusqlite::Result<T>,
39    {
40        self.database.app_query(sqlive::Recorded::Yes, sql, params, map)
41    }
42}
43
44/// A read that starts when polled and retains its store borrow until it
45/// ends, on the store's writer or a read-only handle.
46#[must_use = "reads run when awaited"]
47pub struct Read<'a, F, M: Mode = Writer> {
48    database: &'a StoreDatabase<M>,
49    state: ReadState<F>,
50}
51
52// The public type names the closure, rather than its result. Only poll creates
53// the running slot, as RunningRead<R, E> for that closure.
54enum ReadState<F> {
55    Pending(F),
56    Running(Box<dyn Any + Send>),
57    Finished,
58}
59
60impl<'a, F, R, E, M: Mode> Read<'a, F, M>
61where
62    F: FnOnce(SqlReadContext<'_>) -> Result<R, E> + Send + 'static,
63    R: Send + 'static,
64    E: From<DbError> + CarriesBug + Send + 'static,
65{
66    pub(crate) fn new(database: &'a StoreDatabase<M>, read: F) -> Self {
67        Self { database, state: ReadState::Pending(read) }
68    }
69
70    /// Process the value on another worker after releasing the read
71    /// connection. It fails with the read's own error type.
72    pub async fn process<P, T>(self, process: P) -> Result<T, E>
73    where
74        P: FnOnce(R) -> Result<T, E> + Send + 'static,
75        T: Send + 'static,
76    {
77        let bugs = self.database.bugs().clone();
78        let result = self.await?;
79        database::process(&bugs, move || process(result)).await
80    }
81}
82
83// No field relies on a pinned address. The task itself is a movable handle.
84impl<F, M: Mode> Unpin for Read<'_, F, M> {}
85
86impl<F, R, E, M: Mode> Future for Read<'_, F, M>
87where
88    F: FnOnce(SqlReadContext<'_>) -> Result<R, E> + Send + 'static,
89    R: Send + 'static,
90    E: From<DbError> + CarriesBug + Send + 'static,
91{
92    type Output = Result<R, E>;
93
94    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
95        let this = self.get_mut();
96        let mut task: Box<dyn Any + Send> =
97            match std::mem::replace(&mut this.state, ReadState::Finished) {
98                ReadState::Pending(read) => Box::new(this.database.start_read(read)),
99                ReadState::Running(task) => task,
100                ReadState::Finished => panic!("read polled after completion"),
101            };
102        let running =
103            task.downcast_mut::<RunningRead<R, E>>().expect("read task matches its closure result");
104        match Pin::new(running).poll(cx) {
105            Poll::Pending => {
106                this.state = ReadState::Running(task);
107                Poll::Pending
108            }
109            Poll::Ready(result) => Poll::Ready(result),
110        }
111    }
112}
113
114/// One read's call on the blocking pool, which its database started for the
115/// `Read` that awaits it.
116pub(crate) struct RunningRead<R, E> {
117    call: coven_foundation::task::CompletingTask<Result<R, E>>,
118}
119
120impl<R, E> RunningRead<R, E> {
121    pub(crate) fn new(call: coven_foundation::task::CompletingTask<Result<R, E>>) -> Self {
122        Self { call }
123    }
124}
125
126impl<R, E: From<DbError>> Future for RunningRead<R, E> {
127    type Output = Result<R, E>;
128
129    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
130        Pin::new(&mut self.get_mut().call).poll(cx).map(database::finish_blocking)
131    }
132}
133
134#[cfg(test)]
135#[path = "read_tests.rs"]
136pub(crate) mod tests;