Skip to main content

id_effect_sql/
stream.rs

1//! Streaming query results: [`SqlClient::query_stream`](crate::SqlClient::query_stream) and the
2//! environment-reading [`query_stream`] / [`query_stream_as`] return a pull-based
3//! [`Stream`] of rows instead of collecting them.
4//!
5//! - Nothing runs until the stream is pulled, and rows arrive one chunk per pull, so a consumer
6//!   that is slower than the database applies backpressure instead of buffering the result.
7//! - Dropping the stream (a `take`, a failed consumer) or interrupting the fiber pulling it stops
8//!   the query: `PgSqlClient` cancels it on the server and returns its connection to the pool.
9//! - `TestSqlClient` serves its scripted rows lazily and counts the streams still open
10//!   ([`TestSqlClient::open_streams`](crate::TestSqlClient::open_streams)).
11//!
12//! ```rust
13//! use id_effect::{Exit, Stream};
14//! use id_effect_sql::{
15//!   SqlClient, SqlClientEnv, SqlError, SqlRow, TestSqlClient, query_stream, sql_client_env,
16//! };
17//!
18//! let db = TestSqlClient::new();
19//! let _ = db.connect().block_on();
20//! db.script_query(
21//!   "SELECT id FROM ledger",
22//!   (1..=1000i64).map(|id| SqlRow::from_pairs([("id", id)])).collect(),
23//! );
24//! let rows: Stream<SqlRow, SqlError, SqlClientEnv> = query_stream("SELECT id FROM ledger", vec![]);
25//! let first = rows.take(3).run_collect().provide_all(sql_client_env(db.clone()));
26//! let Exit::Success(first) = first.block_on() else { panic!() };
27//! assert_eq!(first.len(), 3);
28//! assert_eq!(db.open_streams(), 0, "the rest was dropped, not read");
29//! ```
30
31use std::collections::VecDeque;
32use std::sync::{Arc, Mutex, PoisonError};
33
34use id_effect::{Effect, HList, Selector, Stream, fail, need, succeed};
35
36use crate::client::{SqlClientService, TestState, lock};
37use crate::error::SqlError;
38use crate::from_row::FromRow;
39use crate::raw::Sql;
40use crate::row::SqlRow;
41use crate::value::SqlValue;
42
43/// [`SqlClient::query_stream`](crate::SqlClient::query_stream) on the [`SqlClientService`] in
44/// `R`: the client is read on the first pull.
45pub fn query_stream<R, I>(sql: impl Into<Sql>, params: Vec<SqlValue>) -> Stream<SqlRow, SqlError, R>
46where
47  R: Selector<SqlClientService, I> + HList + Send + Sync + 'static,
48{
49  type Rest = Arc<Mutex<Option<Stream<SqlRow, SqlError>>>>;
50  let mut start = Some((sql.into(), params));
51  let rest: Rest = Arc::default();
52  Stream::from_pull(move |n| {
53    let slot = Arc::clone(&rest);
54    let current: Effect<Stream<SqlRow, SqlError>, SqlError, R> = match start.take() {
55      Some((sql, params)) => {
56        need::<SqlClientService>().map(move |c| c.query_stream(sql.as_str(), &params))
57      }
58      // `from_pull` stops pulling once the inner stream ends, so the rest is always there.
59      None => succeed(
60        slot
61          .lock()
62          .unwrap_or_else(PoisonError::into_inner)
63          .take()
64          .unwrap_or_else(Stream::empty),
65      ),
66    };
67    current.flat_map(move |stream| {
68      stream.next_chunk_with_size(n).narrow().map(move |step| {
69        step.map(|(chunk, more)| {
70          *slot.lock().unwrap_or_else(PoisonError::into_inner) = Some(more);
71          chunk.into_vec()
72        })
73      })
74    })
75  })
76}
77
78/// [`query_stream`] decoding every row as `T` ([`FromRow`]); a row that does not decode fails
79/// the stream with its error.
80pub fn query_stream_as<T, R, I>(
81  sql: impl Into<Sql>,
82  params: Vec<SqlValue>,
83) -> Stream<T, SqlError, R>
84where
85  T: FromRow + Send + 'static,
86  R: Selector<SqlClientService, I> + HList + Send + Sync + 'static,
87{
88  query_stream::<R, I>(sql, params).map_effect(|row| match T::from_row(&row) {
89    Ok(t) => succeed(t),
90    Err(e) => fail(e),
91  })
92}
93
94/// Decrements [`TestSqlClient::open_streams`](crate::TestSqlClient::open_streams) when the
95/// stream ends or is dropped.
96struct OpenStream(TestState);
97
98impl Drop for OpenStream {
99  fn drop(&mut self) {
100    let mut state = lock(&self.0);
101    state.open_streams = state.open_streams.saturating_sub(1);
102  }
103}
104
105/// The rows left to serve and the open-stream count they hold.
106struct Feed {
107  rows: VecDeque<SqlRow>,
108  _open: OpenStream,
109}
110
111/// `TestSqlClient::query_stream`: on the first pull the query runs against the scripted state
112/// (failing like [`SqlClient::query`](crate::SqlClient::query)) and is recorded; the rows are
113/// then served at most `n` per pull.
114pub(crate) fn test_query_stream(
115  state: TestState,
116  sql: String,
117  params: Vec<SqlValue>,
118) -> Stream<SqlRow, SqlError> {
119  let mut start = Some((sql, params));
120  let mut feed: Option<Feed> = None;
121  Stream::from_pull(move |n| {
122    if let Some((sql, params)) = start.take() {
123      let mut s = lock(&state);
124      match s.run_query(&sql) {
125        Err(e) => return fail(e),
126        Ok(rows) => {
127          s.queries.push((sql, params));
128          s.open_streams += 1;
129          feed = Some(Feed {
130            rows: rows.into(),
131            _open: OpenStream(Arc::clone(&state)),
132          });
133        }
134      }
135    }
136    let Some(f) = feed.as_mut().filter(|f| !f.rows.is_empty()) else {
137      feed = None;
138      return succeed(None);
139    };
140    let batch: Vec<SqlRow> = f.rows.drain(..n.min(f.rows.len())).collect();
141    if f.rows.is_empty() {
142      feed = None;
143    }
144    succeed(Some(batch))
145  })
146}