rqb 0.1.2

sqlx-first typed Postgres query builder.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use async_stream::try_stream;
use futures_core::stream::BoxStream;
use futures_util::{StreamExt, TryStreamExt};
use sqlx::postgres::PgRow;
use sqlx::{AssertSqlSafe, Decode, FromRow, PgExecutor, PgPool, Postgres, Type};

use crate::Result;
use crate::{
    BuiltQuery, Delete, Insert, Merge, RawStmt, Select, SetQuery, Stmt, Update, count_all, select,
    subquery,
};

/// Rust value that can be decoded from a single Postgres result column.
///
/// This is the read-side pair to [`crate::BindValue`]: it keeps sqlx scalar
/// decode bounds out of user-facing method signatures.
pub trait ScalarValue: for<'r> Decode<'r, Postgres> + Type<Postgres> + Send + Unpin {}

impl<T> ScalarValue for T where T: for<'r> Decode<'r, Postgres> + Type<Postgres> + Send + Unpin {}

fn safe_sql(sql: &str) -> AssertSqlSafe<&str> {
    // rqb reaches execution only after validation and rendering have produced
    // parameterized Postgres SQL; raw fragments are server-owned with bind
    // counts validated, and user values are carried separately as binds.
    AssertSqlSafe(sql)
}

impl BuiltQuery {
    /// Executes the query and returns affected row count.
    pub async fn execute<'e>(&self, executor: impl PgExecutor<'e>) -> Result<u64> {
        let result = sqlx::query_with(safe_sql(&self.sql), self.arguments()?)
            .persistent(self.cacheable)
            .execute(executor)
            .await?;
        Ok(result.rows_affected())
    }

    /// Fetches all rows as raw sqlx `PgRow` values.
    pub async fn fetch_all<'e>(&self, executor: impl PgExecutor<'e>) -> Result<Vec<PgRow>> {
        sqlx::query_with(safe_sql(&self.sql), self.arguments()?)
            .persistent(self.cacheable)
            .fetch_all(executor)
            .await
            .map_err(Into::into)
    }

    /// Streams raw sqlx `PgRow` values.
    ///
    /// The returned stream borrows this [`BuiltQuery`], so keep the built query
    /// value alive until the stream is fully consumed.
    pub fn fetch_stream<'q, 'e>(
        &'q self,
        executor: impl PgExecutor<'e> + 'q,
    ) -> Result<BoxStream<'q, Result<PgRow>>>
    where
        'e: 'q,
    {
        Ok(sqlx::query_with(safe_sql(&self.sql), self.arguments()?)
            .persistent(self.cacheable)
            .fetch(executor)
            .map_err(Into::into)
            .boxed())
    }

    /// Streams raw sqlx `PgRow` values from an owned pool-backed query.
    ///
    /// The returned stream owns this built query and a cloneable [`PgPool`]
    /// handle, so it can outlive the call frame that created it.
    pub fn fetch_stream_pool(self, pool: PgPool) -> Result<BoxStream<'static, Result<PgRow>>> {
        let Self {
            sql,
            params,
            cacheable,
        } = self;
        let arguments = params.arguments()?;

        Ok(try_stream! {
            let mut rows = sqlx::query_with(safe_sql(&sql), arguments)
                .persistent(cacheable)
                .fetch(&pool);
            while let Some(row) = rows.try_next().await.map_err(crate::Error::from)? {
                yield row;
            }
        }
        .boxed())
    }

    /// Fetches exactly one raw sqlx `PgRow`.
    pub async fn fetch_one<'e>(&self, executor: impl PgExecutor<'e>) -> Result<PgRow> {
        sqlx::query_with(safe_sql(&self.sql), self.arguments()?)
            .persistent(self.cacheable)
            .fetch_one(executor)
            .await
            .map_err(Into::into)
    }

    /// Fetches zero or one raw sqlx `PgRow`.
    pub async fn fetch_optional<'e>(&self, executor: impl PgExecutor<'e>) -> Result<Option<PgRow>> {
        sqlx::query_with(safe_sql(&self.sql), self.arguments()?)
            .persistent(self.cacheable)
            .fetch_optional(executor)
            .await
            .map_err(Into::into)
    }

    /// Fetches all rows into a `sqlx::FromRow` type.
    pub async fn fetch_all_as<'e, T>(&self, executor: impl PgExecutor<'e>) -> Result<Vec<T>>
    where
        T: for<'r> FromRow<'r, PgRow> + Send + Unpin,
    {
        sqlx::query_as_with::<_, T, _>(safe_sql(&self.sql), self.arguments()?)
            .persistent(self.cacheable)
            .fetch_all(executor)
            .await
            .map_err(Into::into)
    }

    /// Streams rows into a `sqlx::FromRow` type.
    ///
    /// Streaming avoids materializing large exports in memory. Keep the
    /// [`BuiltQuery`] value alive while consuming the stream.
    pub fn fetch_stream_as<'q, 'e, T>(
        &'q self,
        executor: impl PgExecutor<'e> + 'q,
    ) -> Result<BoxStream<'q, Result<T>>>
    where
        'e: 'q,
        T: for<'r> FromRow<'r, PgRow> + Send + Unpin + 'q,
    {
        Ok(
            sqlx::query_as_with::<_, T, _>(safe_sql(&self.sql), self.arguments()?)
                .persistent(self.cacheable)
                .fetch(executor)
                .map_err(Into::into)
                .boxed(),
        )
    }

    /// Streams rows into a `sqlx::FromRow` type from an owned pool-backed query.
    ///
    /// The returned stream owns this built query and a cloneable [`PgPool`]
    /// handle, so it can outlive the call frame that created it.
    pub fn fetch_stream_pool_as<T>(self, pool: PgPool) -> Result<BoxStream<'static, Result<T>>>
    where
        T: for<'r> FromRow<'r, PgRow> + Send + Unpin + 'static,
    {
        let Self {
            sql,
            params,
            cacheable,
        } = self;
        let arguments = params.arguments()?;

        Ok(try_stream! {
            let mut rows = sqlx::query_as_with::<_, T, _>(safe_sql(&sql), arguments)
                .persistent(cacheable)
                .fetch(&pool);
            while let Some(row) = rows.try_next().await.map_err(crate::Error::from)? {
                yield row;
            }
        }
        .boxed())
    }

    /// Fetches exactly one row into a `sqlx::FromRow` type.
    pub async fn fetch_one_as<'e, T>(&self, executor: impl PgExecutor<'e>) -> Result<T>
    where
        T: for<'r> FromRow<'r, PgRow> + Send + Unpin,
    {
        sqlx::query_as_with::<_, T, _>(safe_sql(&self.sql), self.arguments()?)
            .persistent(self.cacheable)
            .fetch_one(executor)
            .await
            .map_err(Into::into)
    }

    /// Fetches zero or one row into a `sqlx::FromRow` type.
    pub async fn fetch_optional_as<'e, T>(&self, executor: impl PgExecutor<'e>) -> Result<Option<T>>
    where
        T: for<'r> FromRow<'r, PgRow> + Send + Unpin,
    {
        sqlx::query_as_with::<_, T, _>(safe_sql(&self.sql), self.arguments()?)
            .persistent(self.cacheable)
            .fetch_optional(executor)
            .await
            .map_err(Into::into)
    }

    /// Fetches all rows as a single decoded scalar column.
    pub async fn fetch_scalar<'e, T>(&self, executor: impl PgExecutor<'e>) -> Result<Vec<T>>
    where
        T: ScalarValue,
    {
        sqlx::query_scalar_with::<_, T, _>(safe_sql(&self.sql), self.arguments()?)
            .persistent(self.cacheable)
            .fetch_all(executor)
            .await
            .map_err(Into::into)
    }

    /// Streams rows as a single decoded scalar column.
    ///
    /// Keep the [`BuiltQuery`] value alive while consuming the stream.
    pub fn fetch_stream_scalar<'q, 'e, T>(
        &'q self,
        executor: impl PgExecutor<'e> + 'q,
    ) -> Result<BoxStream<'q, Result<T>>>
    where
        'e: 'q,
        T: ScalarValue + 'q,
    {
        Ok(
            sqlx::query_scalar_with::<_, T, _>(safe_sql(&self.sql), self.arguments()?)
                .persistent(self.cacheable)
                .fetch(executor)
                .map_err(Into::into)
                .boxed(),
        )
    }

    /// Streams rows as a single decoded scalar column from an owned pool-backed query.
    ///
    /// The returned stream owns this built query and a cloneable [`PgPool`]
    /// handle, so it can outlive the call frame that created it.
    pub fn fetch_stream_pool_scalar<T>(self, pool: PgPool) -> Result<BoxStream<'static, Result<T>>>
    where
        T: ScalarValue + 'static,
    {
        let Self {
            sql,
            params,
            cacheable,
        } = self;
        let arguments = params.arguments()?;

        Ok(try_stream! {
            let mut rows = sqlx::query_scalar_with::<_, T, _>(safe_sql(&sql), arguments)
                .persistent(cacheable)
                .fetch(&pool);
            while let Some(row) = rows.try_next().await.map_err(crate::Error::from)? {
                yield row;
            }
        }
        .boxed())
    }

    /// Fetches exactly one decoded scalar value.
    pub async fn fetch_one_scalar<'e, T>(&self, executor: impl PgExecutor<'e>) -> Result<T>
    where
        T: ScalarValue,
    {
        sqlx::query_scalar_with::<_, T, _>(safe_sql(&self.sql), self.arguments()?)
            .persistent(self.cacheable)
            .fetch_one(executor)
            .await
            .map_err(Into::into)
    }

    /// Fetches zero or one decoded scalar value.
    pub async fn fetch_optional_scalar<'e, T>(
        &self,
        executor: impl PgExecutor<'e>,
    ) -> Result<Option<T>>
    where
        T: ScalarValue,
    {
        sqlx::query_scalar_with::<_, T, _>(safe_sql(&self.sql), self.arguments()?)
            .persistent(self.cacheable)
            .fetch_optional(executor)
            .await
            .map_err(Into::into)
    }
}

impl Select {
    /// Executes a matching `count(*)` query for this select.
    ///
    /// The count query strips `ORDER BY`, `LIMIT`, `OFFSET`, `FETCH`, and row
    /// locks before wrapping the select as a subquery.
    pub async fn count<'e>(&self, executor: impl PgExecutor<'e>) -> Result<i64> {
        self.build_count()?.fetch_one_scalar(executor).await
    }

    pub(crate) fn build_count(&self) -> Result<BuiltQuery> {
        let mut count = self.clone();
        count.order.clear();
        count.row_limit = None;
        count.offset = None;
        count.lock = None;
        select(subquery(count, "rqb_count", ()))
            .expr(count_all())
            .build()
    }
}

macro_rules! impl_statement_execute {
    ($ty:ty) => {
        impl $ty {
            /// Builds and executes the statement.
            ///
            /// This is a convenience path; call `build()` first when you need
            /// to inspect SQL or reuse the same validated query.
            pub async fn execute<'e>(&self, executor: impl PgExecutor<'e>) -> Result<u64> {
                self.build()?.execute(executor).await
            }

            /// Builds the statement and fetches all raw rows.
            pub async fn fetch_all<'e>(&self, executor: impl PgExecutor<'e>) -> Result<Vec<PgRow>> {
                self.build()?.fetch_all(executor).await
            }

            /// Builds the statement and fetches one raw row.
            pub async fn fetch_one<'e>(&self, executor: impl PgExecutor<'e>) -> Result<PgRow> {
                self.build()?.fetch_one(executor).await
            }

            /// Builds the statement and fetches an optional raw row.
            pub async fn fetch_optional<'e>(
                &self,
                executor: impl PgExecutor<'e>,
            ) -> Result<Option<PgRow>> {
                self.build()?.fetch_optional(executor).await
            }

            /// Builds the statement and streams raw rows from an owned pool-backed query.
            ///
            /// For borrowed executor streams, call `build()` and use
            /// [`BuiltQuery::fetch_stream`].
            pub fn fetch_stream_pool(
                self,
                pool: PgPool,
            ) -> Result<BoxStream<'static, Result<PgRow>>> {
                self.build()?.fetch_stream_pool(pool)
            }

            /// Builds the statement and fetches all rows into a `sqlx::FromRow` type.
            ///
            /// Use scalar helpers when the query returns one column instead of
            /// a row struct/tuple.
            pub async fn fetch_all_as<'e, T>(&self, executor: impl PgExecutor<'e>) -> Result<Vec<T>>
            where
                T: for<'r> FromRow<'r, PgRow> + Send + Unpin,
            {
                self.build()?.fetch_all_as(executor).await
            }

            /// Builds the statement and fetches one row into a `sqlx::FromRow` type.
            pub async fn fetch_one_as<'e, T>(&self, executor: impl PgExecutor<'e>) -> Result<T>
            where
                T: for<'r> FromRow<'r, PgRow> + Send + Unpin,
            {
                self.build()?.fetch_one_as(executor).await
            }

            /// Builds the statement and fetches an optional row into a `sqlx::FromRow` type.
            pub async fn fetch_optional_as<'e, T>(
                &self,
                executor: impl PgExecutor<'e>,
            ) -> Result<Option<T>>
            where
                T: for<'r> FromRow<'r, PgRow> + Send + Unpin,
            {
                self.build()?.fetch_optional_as(executor).await
            }

            /// Builds the statement and streams rows into a `sqlx::FromRow` type from an owned pool-backed query.
            ///
            /// For borrowed executor streams, call `build()` and use
            /// [`BuiltQuery::fetch_stream_as`].
            pub fn fetch_stream_pool_as<T>(
                self,
                pool: PgPool,
            ) -> Result<BoxStream<'static, Result<T>>>
            where
                T: for<'r> FromRow<'r, PgRow> + Send + Unpin + 'static,
            {
                self.build()?.fetch_stream_pool_as(pool)
            }

            /// Builds the statement and fetches all rows as a single scalar column.
            pub async fn fetch_scalar<'e, T>(&self, executor: impl PgExecutor<'e>) -> Result<Vec<T>>
            where
                T: ScalarValue,
            {
                self.build()?.fetch_scalar(executor).await
            }

            /// Builds the statement and fetches one scalar value.
            pub async fn fetch_one_scalar<'e, T>(&self, executor: impl PgExecutor<'e>) -> Result<T>
            where
                T: ScalarValue,
            {
                self.build()?.fetch_one_scalar(executor).await
            }

            /// Builds the statement and fetches an optional scalar value.
            pub async fn fetch_optional_scalar<'e, T>(
                &self,
                executor: impl PgExecutor<'e>,
            ) -> Result<Option<T>>
            where
                T: ScalarValue,
            {
                self.build()?.fetch_optional_scalar(executor).await
            }

            /// Builds the statement and streams scalar values from an owned pool-backed query.
            ///
            /// For borrowed executor streams, call `build()` and use
            /// [`BuiltQuery::fetch_stream_scalar`].
            pub fn fetch_stream_pool_scalar<T>(
                self,
                pool: PgPool,
            ) -> Result<BoxStream<'static, Result<T>>>
            where
                T: ScalarValue + 'static,
            {
                self.build()?.fetch_stream_pool_scalar(pool)
            }
        }
    };
}

impl_statement_execute!(Select);
impl_statement_execute!(SetQuery);
impl_statement_execute!(Insert);
impl_statement_execute!(Update);
impl_statement_execute!(Delete);
impl_statement_execute!(Merge);
impl_statement_execute!(RawStmt);
impl_statement_execute!(Stmt);