Skip to main content

ruststream_sqlx/inbox/
database.rs

1//! The databases the inbox runs on.
2
3use std::future::Future;
4
5use futures::TryStreamExt;
6use sqlx::Row as _;
7use sqlx::any::AnyQueryResult;
8use sqlx::{
9    Arguments, ColumnIndex, Database, Decode, Encode, Error, Executor, IntoArguments, SqlStr, Type,
10};
11
12use super::engine::{Claimed, Events, IdAt, undecodable};
13use super::form::advisory::events::Candidates;
14use super::queue::Queue;
15
16#[cfg(feature = "any")]
17mod any;
18pub(crate) mod built_in;
19mod insert;
20pub(crate) mod notify;
21
22#[cfg(feature = "any")]
23pub use any::AnyDialect;
24pub use built_in::{BuiltIn, BuiltInDialect};
25pub use insert::{InsertSql, OnConnection, no_insert};
26pub use notify::Notifies;
27
28/// A sqlx database the inbox runs on: one that binds and reads the values the queue's own
29/// statements use, runs statements on a connection, and reports the rows a statement changed.
30///
31/// Every database whose sqlx driver does so implements it; Postgres, MySQL, SQLite and `Any` do.
32/// The rows a statement changed come through sqlx's [`AnyQueryResult`], which every driver in sqlx
33/// converts its result into; a driver outside sqlx provides that conversion for its own result
34/// type.
35///
36/// # Examples
37///
38/// ```
39/// # #[cfg(feature = "postgres")]
40/// # mod demo {
41/// use ruststream_sqlx::prelude::*;
42/// use serde::Deserialize;
43/// use sqlx::{PgPool, Postgres};
44///
45/// #[derive(Inbox, sqlx::FromRow)]
46/// #[inbox(table = "email_jobs")]
47/// pub struct SendEmail {
48///     #[field(id, generated)]
49///     job_id: i64,
50///     #[field(group)]
51///     name: String,
52///     #[field(payload)]
53///     payload: Vec<u8>,
54/// }
55///
56/// #[derive(Deserialize)]
57/// struct Email {
58///     to: String,
59/// }
60///
61/// #[subscriber(InboxQueue::<SendEmail>::new("emails"))]
62/// async fn send(email: &Email) -> HandlerOutcome {
63///     tracing::info!(to = %email.to, "sending");
64///     HandlerOutcome::ack()
65/// }
66///
67/// // `Postgres` is a `QueueDatabase`: the broker over a `PgPool` is a `SqlxBroker<Postgres>`.
68/// pub fn broker(pool: PgPool) -> SqlxBroker<Postgres> {
69///     SqlxBroker::new(pool)
70/// }
71///
72/// pub fn app(pool: PgPool) -> RustStream {
73///     RustStream::new(AppInfo::new("mailer", "0.1.0")).with_broker(broker(pool), |b| {
74///         b.include(send);
75///     })
76/// }
77/// # }
78/// # fn main() {}
79/// ```
80pub trait QueueDatabase: Database {
81    /// Binds a text value. Machinery; the crate's statements call it.
82    #[doc(hidden)]
83    fn bind_str(arguments: &mut Self::Arguments, value: &str) -> Result<(), Error>;
84
85    /// Binds an integer. Machinery; the crate's statements call it.
86    #[doc(hidden)]
87    fn bind_i64(arguments: &mut Self::Arguments, value: i64) -> Result<(), Error>;
88
89    /// Runs a statement and returns the rows it changed. Machinery.
90    #[doc(hidden)]
91    fn execute<'c>(
92        conn: &'c mut Self::Connection,
93        sql: &'static str,
94        arguments: Self::Arguments,
95    ) -> impl Future<Output = Result<u64, Error>> + Send + 'c;
96
97    /// Runs a statement that binds nothing as text, unprepared: a savepoint, which MySQL does not
98    /// prepare. Machinery.
99    #[doc(hidden)]
100    fn execute_text<'c>(
101        conn: &'c mut Self::Connection,
102        sql: &'static str,
103    ) -> impl Future<Output = Result<(), Error>> + Send + 'c;
104
105    /// Runs a claim or a fetch of whole rows of `queue` into `out`: a row its struct does not
106    /// decode is [`Claimed::Undecodable`], its id read alone where the queue's select carries it
107    /// and its attempt as the struct reads it. Machinery.
108    #[doc(hidden)]
109    fn fetch_rows<'c, Row>(
110        conn: &'c mut Self::Connection,
111        sql: &'static str,
112        arguments: Self::Arguments,
113        queue: &'static Queue,
114        out: &'c mut Vec<Claimed<Row>>,
115    ) -> impl Future<Output = Result<(), Error>> + Send + 'c
116    where
117        Row: Events<Self>,
118        Row::Id: for<'r> Decode<'r, Self> + Type<Self>;
119
120    /// Reads the column `name` of `row` as a `T`. Machinery.
121    #[doc(hidden)]
122    fn column<T>(row: &Self::Row, name: &str) -> Result<T, Error>
123    where
124        T: for<'r> Decode<'r, Self> + Type<Self>;
125
126    /// Runs a claim of ids into `out`. Machinery.
127    #[doc(hidden)]
128    fn fetch_ids<'c, Id>(
129        conn: &'c mut Self::Connection,
130        sql: &'static str,
131        arguments: Self::Arguments,
132        out: &'c mut Vec<Id>,
133    ) -> impl Future<Output = Result<(), Error>> + Send + 'c
134    where
135        Id: for<'r> Decode<'r, Self> + Type<Self> + Send + Unpin + 'c;
136
137    /// Prepares a statement on the server: the startup check. Machinery.
138    #[doc(hidden)]
139    fn prepare<'c>(
140        conn: &'c mut Self::Connection,
141        sql: &'static str,
142    ) -> impl Future<Output = Result<(), Error>> + Send + 'c;
143
144    /// Runs a query of one text value, such as the server's version, and returns the value.
145    /// Machinery.
146    #[doc(hidden)]
147    fn fetch_text<'c>(
148        conn: &'c mut Self::Connection,
149        sql: &'static str,
150    ) -> impl Future<Output = Result<String, Error>> + Send + 'c;
151
152    /// Runs a statement whose one row starts with a 64-bit integer, such as the guard a FIFO
153    /// claim takes its group with, or the lock and the unlock of the advisory lock form, and
154    /// returns whether the integer is nonzero. Machinery.
155    #[doc(hidden)]
156    fn fetch_flag<'c>(
157        conn: &'c mut Self::Connection,
158        sql: &'static str,
159        arguments: Self::Arguments,
160    ) -> impl Future<Output = Result<bool, Error>> + Send + 'c;
161
162    /// Runs the advisory claim of candidates into `out`: the id in the first column, the lock key
163    /// as text in the second, copied into the buffers `out` keeps. Machinery.
164    #[doc(hidden)]
165    fn fetch_candidates<'c, Id>(
166        conn: &'c mut Self::Connection,
167        sql: &'static str,
168        arguments: Self::Arguments,
169        out: &'c mut Candidates<Id>,
170    ) -> impl Future<Output = Result<(), Error>> + Send + 'c
171    where
172        Id: for<'r> Decode<'r, Self> + Type<Self> + Send + 'c;
173
174    /// Runs a statement and says whether it returned a row, such as the take of a candidate the
175    /// service's own fetch reads. Machinery.
176    #[doc(hidden)]
177    fn fetch_found<'c>(
178        conn: &'c mut Self::Connection,
179        sql: &'static str,
180        arguments: Self::Arguments,
181    ) -> impl Future<Output = Result<bool, Error>> + Send + 'c;
182}
183
184impl<DB> QueueDatabase for DB
185where
186    DB: Database,
187    for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>,
188    DB::Arguments: IntoArguments<DB>,
189    for<'q> &'q str: Encode<'q, DB> + Type<DB>,
190    for<'r> &'r str: Decode<'r, DB> + ColumnIndex<DB::Row>,
191    for<'a> i64: Encode<'a, DB> + Decode<'a, DB> + Type<DB>,
192    for<'r> String: Decode<'r, DB> + Type<DB>,
193    usize: ColumnIndex<DB::Row>,
194    DB::QueryResult: Into<AnyQueryResult>,
195{
196    fn bind_str(arguments: &mut Self::Arguments, value: &str) -> Result<(), Error> {
197        arguments.add(value).map_err(Error::Encode)
198    }
199
200    fn bind_i64(arguments: &mut Self::Arguments, value: i64) -> Result<(), Error> {
201        arguments.add(value).map_err(Error::Encode)
202    }
203
204    async fn execute(
205        conn: &mut Self::Connection,
206        sql: &'static str,
207        arguments: Self::Arguments,
208    ) -> Result<u64, Error> {
209        let result: AnyQueryResult = sqlx::query_with(sql, arguments).execute(conn).await?.into();
210        Ok(result.rows_affected())
211    }
212
213    async fn execute_text(conn: &mut Self::Connection, sql: &'static str) -> Result<(), Error> {
214        // A bare text binds nothing, so sqlx sends it as is, without preparing it.
215        conn.execute(sql).await?;
216        Ok(())
217    }
218
219    async fn fetch_rows<'c, Row>(
220        conn: &'c mut Self::Connection,
221        sql: &'static str,
222        arguments: Self::Arguments,
223        queue: &'static Queue,
224        out: &'c mut Vec<Claimed<Row>>,
225    ) -> Result<(), Error>
226    where
227        Row: Events<Self>,
228        Row::Id: for<'r> Decode<'r, Self> + Type<Self>,
229    {
230        // The decode `query_as` runs, one row at a time, so a row that fails it fails alone.
231        let mut rows = sqlx::query_with::<Self, _>(sql, arguments).fetch(conn);
232        while let Some(raw) = rows.try_next().await? {
233            match Row::from_row(&raw) {
234                Ok(row) => out.push(Claimed::Row(row)),
235                Err(error) => {
236                    // Why the id alone: a row only its id can name is still a row the policy
237                    // settles, and nothing settles a row whose id does not decode either. Its
238                    // attempt comes along, so the cap spends such a row as any other.
239                    let id = match queue.id_at {
240                        IdAt::First => raw.try_get::<Row::Id, _>(0_usize),
241                        IdAt::Named(name) => raw.try_get::<Row::Id, _>(name),
242                    };
243                    match id {
244                        Ok(id) => out.push(Claimed::Undecodable {
245                            id,
246                            attempt: Row::read_attempt(&raw, queue),
247                            error: Box::new(undecodable(error)),
248                        }),
249                        Err(_) => return Err(error),
250                    }
251                }
252            }
253        }
254        Ok(())
255    }
256
257    fn column<T>(row: &Self::Row, name: &str) -> Result<T, Error>
258    where
259        T: for<'r> Decode<'r, Self> + Type<Self>,
260    {
261        row.try_get::<T, _>(name)
262    }
263
264    async fn fetch_ids<'c, Id>(
265        conn: &'c mut Self::Connection,
266        sql: &'static str,
267        arguments: Self::Arguments,
268        out: &'c mut Vec<Id>,
269    ) -> Result<(), Error>
270    where
271        Id: for<'r> Decode<'r, Self> + Type<Self> + Send + Unpin + 'c,
272    {
273        // Into the subscription's buffer, as the claim's rows go, and through the plain query's
274        // stream: `query_scalar`'s `fetch_all` boxes a stream per layer and collects a vector of
275        // its own on every claim.
276        let mut rows = sqlx::query_with::<Self, _>(sql, arguments).fetch(conn);
277        while let Some(row) = rows.try_next().await? {
278            out.push(row.try_get::<Id, _>(0_usize)?);
279        }
280        Ok(())
281    }
282
283    async fn prepare(conn: &mut Self::Connection, sql: &'static str) -> Result<(), Error> {
284        conn.prepare(SqlStr::from_static(sql)).await?;
285        Ok(())
286    }
287
288    fn fetch_text<'c>(
289        conn: &'c mut Self::Connection,
290        sql: &'static str,
291    ) -> impl Future<Output = Result<String, Error>> + Send + 'c {
292        sqlx::query_scalar::<Self, String>(sql).fetch_one(conn)
293    }
294
295    async fn fetch_flag(
296        conn: &mut Self::Connection,
297        sql: &'static str,
298        arguments: Self::Arguments,
299    ) -> Result<bool, Error> {
300        let flag: i64 = sqlx::query_scalar_with::<Self, i64, _>(sql, arguments)
301            .fetch_one(conn)
302            .await?;
303        Ok(flag != 0)
304    }
305
306    async fn fetch_candidates<'c, Id>(
307        conn: &'c mut Self::Connection,
308        sql: &'static str,
309        arguments: Self::Arguments,
310        out: &'c mut Candidates<Id>,
311    ) -> Result<(), Error>
312    where
313        Id: for<'r> Decode<'r, Self> + Type<Self> + Send + 'c,
314    {
315        let mut rows = sqlx::query_with::<Self, _>(sql, arguments).fetch(conn);
316        while let Some(row) = rows.try_next().await? {
317            // The key is read where the row holds it, and copied once, into a kept buffer.
318            let key = row.try_get::<&str, _>(1_usize)?;
319            out.push(row.try_get::<Id, _>(0_usize)?, key);
320        }
321        Ok(())
322    }
323
324    async fn fetch_found(
325        conn: &mut Self::Connection,
326        sql: &'static str,
327        arguments: Self::Arguments,
328    ) -> Result<bool, Error> {
329        // Every row is read, so the statement has run to its end when the answer comes.
330        let mut rows = sqlx::query_with::<Self, _>(sql, arguments).fetch(conn);
331        let mut found = false;
332        while rows.try_next().await?.is_some() {
333            found = true;
334        }
335        Ok(found)
336    }
337}