qbrs-sqlx 0.1.0

sqlx-based execution integration for qbrs (Postgres).
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
//! Execution integration between qbrs's query builder and a real Postgres
//! via `sqlx`. This crate owns only the value-binding and row-decoding glue;
//! query building, SQL rendering, and every compile-time guarantee live in
//! `qbrs-core`, which stays independent of any async runtime or driver.

use qbrs_core::delete::Delete;
use qbrs_core::dialect::Postgres;
use qbrs_core::expr::Value;
use qbrs_core::insert::Insert;
use qbrs_core::row::{Row, RowCons, RowNil};
use qbrs_core::select::{DynSelect, Prepared, PreparedParams, Select, Selection, SetOp, Total};
use qbrs_core::statement::{Returning, Statement, WrittenTable};
use qbrs_core::update::Update;
use sqlx::Row as _;
use sqlx::postgres::PgRow;

/// Errors from executing a qbrs query against Postgres via `sqlx`. An enum
/// rather than a bare `sqlx::Error` so a qbrs-level misuse is distinguishable
/// from a driver/database error without string-matching a message.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// A real error from Postgres or the `sqlx` driver: a failed
    /// connection, constraint violation, decode failure, etc.
    #[error(transparent)]
    Sqlx(#[from] sqlx::Error),

    /// A `prepare!{}` placeholder reached execution unresolved: either
    /// `Prepared::resolve()` found no matching field in `Params`, or the
    /// query was executed directly instead of through `.prepare()`.
    #[error(transparent)]
    UnresolvedPlaceholder(#[from] qbrs_core::select::UnresolvedPlaceholder),

    /// An `*Update` describing no assignment, or an insert of no rows —
    /// caught where the request-shaped data is read (`Assignments::from_row`,
    /// `.values_all`), never at a statement. Here so a handler returning
    /// this crate's `Result` can `?` on that as readily as on a query.
    #[error(transparent)]
    NothingToSet(#[from] qbrs_core::update::NothingToSet),

    #[error(transparent)]
    NothingToInsert(#[from] qbrs_core::insert::NothingToInsert),

    /// A column type is enabled on `qbrs` but not on `qbrs-sqlx`, so the
    /// value renders and has nothing to bind it. The two crates carry the
    /// same feature names for exactly this reason — turn it on in both.
    #[error("`{0}` values need the matching feature on `qbrs-sqlx` too")]
    FeatureNotEnabled(&'static str),
}

/// This crate's `Result`: the same shape as `sqlx::Result`, with
/// `qbrs_sqlx::Error` as the fixed error type.
pub type Result<T> = std::result::Result<T, Error>;

/// Every extension trait that puts a terminal method on a builder, plus the
/// error type a caller's own signatures have to name and the `DecodeRow`
/// bound a generic helper over `RowQuery` has to spell. `Result` is
/// deliberately absent: a glob-imported alias of that name shadows
/// `std::result::Result` in every module that follows, and a service layer
/// has its own error type in most of them — write `qbrs_sqlx::Result<T>`
/// where the alias is wanted. Which trait applies
/// depends on the builder, so importing them one at a time is bookkeeping
/// with no decision in it — and `count` in particular resolves against
/// `Iterator::count` with a confusing message until `CountExt` is in scope.
pub mod prelude {
    pub use crate::Error;
    pub use crate::{
        CountExt, CountQuery, DecodeRow, ExecuteExt, LoadExt, PreparedCountExt, PreparedExt,
        PreparedQuery, PreparedTotal, RowQuery, WriteStatement,
    };
}

/// Binds a `Value` to a Postgres query parameter. `Value`'s typed `NullX`
/// variants carry the parameter type a NULL bind still has to declare.
///
/// Fallible only for `Value::Placeholder`: an unresolved named placeholder
/// is a misuse no compile-time check here can catch, so it surfaces as
/// `Error::UnresolvedPlaceholder` rather than a wrong bind or a panic.
fn bind_value<'q>(
    query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
    v: Value,
) -> Result<sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>> {
    Ok(match v {
        Value::I32(x) => query.bind(x),
        Value::I64(x) => query.bind(x),
        Value::F64(x) => query.bind(x),
        Value::Text(x) => query.bind(x),
        Value::Bool(x) => query.bind(x),
        Value::Bytes(x) => query.bind(x),
        Value::NullI32 => query.bind(None::<i32>),
        Value::NullI64 => query.bind(None::<i64>),
        Value::NullF64 => query.bind(None::<f64>),
        Value::NullText => query.bind(None::<String>),
        Value::NullBool => query.bind(None::<bool>),
        Value::NullBytes => query.bind(None::<Vec<u8>>),
        #[cfg(feature = "chrono")]
        Value::Timestamptz(x) => query.bind(x),
        #[cfg(feature = "chrono")]
        Value::NullTimestamptz => query.bind(None::<chrono::DateTime<chrono::Utc>>),
        #[cfg(feature = "chrono")]
        Value::Date(x) => query.bind(x),
        #[cfg(feature = "chrono")]
        Value::NullDate => query.bind(None::<chrono::NaiveDate>),
        #[cfg(feature = "uuid")]
        Value::Uuid(x) => query.bind(x),
        #[cfg(feature = "uuid")]
        Value::NullUuid => query.bind(None::<uuid::Uuid>),
        #[cfg(feature = "decimal")]
        Value::Numeric(x) => query.bind(x),
        #[cfg(feature = "decimal")]
        Value::NullNumeric => query.bind(None::<rust_decimal::Decimal>),
        Value::Placeholder(name) => {
            return Err(qbrs_core::select::UnresolvedPlaceholder(name).into());
        }
        // Reachable only when a column type is on in `qbrs-core` and off
        // here: the variant exists, the arm that binds it doesn't.
        #[allow(unreachable_patterns)]
        other => return Err(Error::FeatureNotEnabled(other.type_name())),
    })
}

fn bind_all<'q>(
    mut query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
    params: Vec<Value>,
) -> Result<sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>> {
    for p in params {
        query = bind_value(query, p)?;
    }
    Ok(query)
}

/// Generic over `E: sqlx::PgExecutor` so every `.load()`/`.execute()` works
/// against a `&PgPool` or a transaction alike. sqlx implements `Executor` for
/// `&mut PgConnection`, not `Transaction`, so callers pass `&mut *tx`.
async fn fetch_all<'e, T: DecodeRow, E: sqlx::PgExecutor<'e>>(
    executor: E,
    sql: &str,
    params: Vec<Value>,
) -> Result<Vec<T>> {
    let rows = bind_all(sqlx::query(sqlx::AssertSqlSafe(sql)), params)?
        .fetch_all(executor)
        .await?;
    rows.iter()
        .map(|row| T::decode_at(row, &mut 0).map_err(Error::from))
        .collect()
}

async fn fetch_optional<'e, T: DecodeRow, E: sqlx::PgExecutor<'e>>(
    executor: E,
    sql: &str,
    params: Vec<Value>,
) -> Result<Option<T>> {
    let row = bind_all(sqlx::query(sqlx::AssertSqlSafe(sql)), params)?
        .fetch_optional(executor)
        .await?;
    row.as_ref()
        .map(|r| T::decode_at(r, &mut 0).map_err(Error::from))
        .transpose()
}

async fn execute_only<'e, E: sqlx::PgExecutor<'e>>(
    executor: E,
    sql: &str,
    params: Vec<Value>,
) -> Result<u64> {
    let result = bind_all(sqlx::query(sqlx::AssertSqlSafe(sql)), params)?
        .execute(executor)
        .await?;
    Ok(result.rows_affected())
}

/// What a row-producing query renders to, and what its rows decode to: a
/// `SELECT`, a `RETURNING` clause, an erased `DynSelect`, a `UNION` chain.
/// `LoadExt` is the pair of methods over it, and the split is load-bearing
/// — with the validity bound on the impl instead, an invalid selection
/// makes `.load(..)` not exist, and the scope error the builder wanted to
/// report is replaced by a method-resolution failure that never mentions
/// the table.
///
/// `Idx` is threaded through the trait's parameter list for the reason
/// `scope::Superset` explains. Callers never see it; it's inferred.
#[diagnostic::on_unimplemented(
    message = "`{Self}` isn't a query this crate can run",
    label = "a `Select`, a `RETURNING`, a `DynSelect` or a set operation, in the `Postgres` dialect, whose values are all types `DecodeRow` covers"
)]
pub trait RowQuery<Idx> {
    type Output: DecodeRow;

    #[doc(hidden)]
    fn rendered(&self) -> (String, Vec<Value>);
}

/// `load` for the rows, `load_one` for the first of them, and
/// `ExecuteExt::execute` where there are none to decode. One trait for
/// every row-producing builder keeps the terminal vocabulary tied to what a
/// statement yields rather than to which builder happens to be in hand.
///
/// Implemented for every builder, satisfiable by the ones that produce
/// rows: what a builder can't do is then reported by `RowQuery`, which says
/// so, rather than by the method not existing — which rustc answers with a
/// list of unsatisfied bounds or, worse, by suggesting `Iterator`. Not a
/// blanket impl, since `load`/`count`/`execute` are names other traits in a
/// caller's scope have too. A builder added here needs its three empty
/// impls, or its terminal goes back to reporting nothing.
pub trait LoadExt {
    fn load<'e, Idx, E: sqlx::PgExecutor<'e>>(
        &self,
        executor: E,
    ) -> impl std::future::Future<Output = Result<Vec<<Self as RowQuery<Idx>>::Output>>>
    where
        Self: RowQuery<Idx>,
    {
        let (sql, params) = self.rendered();
        async move { fetch_all::<<Self as RowQuery<Idx>>::Output, E>(executor, &sql, params).await }
    }

    fn load_one<'e, Idx, E: sqlx::PgExecutor<'e>>(
        &self,
        executor: E,
    ) -> impl std::future::Future<Output = Result<Option<<Self as RowQuery<Idx>>::Output>>>
    where
        Self: RowQuery<Idx>,
    {
        let (sql, params) = self.rendered();
        async move { fetch_optional::<<Self as RowQuery<Idx>>::Output, E>(executor, &sql, params).await }
    }
}

impl<D, Scope, Sel, Outer> LoadExt for Select<D, Scope, Sel, Outer> {}
impl<S, Sel> LoadExt for Returning<S, Sel> {}
impl<D, Output> LoadExt for DynSelect<D, Output> {}
impl<D, Output> LoadExt for SetOp<D, Output> {}
impl<D, R: qbrs_core::insert::InsertRow> LoadExt for Insert<D, R> {}
impl<D, T: qbrs_core::scope::Table> LoadExt for Update<D, T> {}
impl<D, T: qbrs_core::scope::Table> LoadExt for Delete<D, T> {}

impl<Scope, Sel, Idx> RowQuery<Idx> for Select<Postgres, Scope, Sel>
where
    Sel: Selection<Scope, Idx>,
    Sel::Output: DecodeRow,
{
    type Output = Sel::Output;

    fn rendered(&self) -> (String, Vec<Value>) {
        self.to_sql::<Idx>(Postgres)
    }
}

/// `SELECT count(*)` over a query's `FROM`/`JOIN`/`WHERE`/`GROUP BY`, with
/// its `ORDER BY`/`LIMIT`/`OFFSET` dropped — a total counts the rows that
/// match, not the page being shown. Returns a number rather than an
/// `Option`, since a count query always produces exactly one row.
#[diagnostic::on_unimplemented(
    message = "`{Self}` isn't a query this crate can count",
    label = "a `Select`, a `DynSelect` or a set operation in the `Postgres` dialect is; a writing statement reports rows affected through `.execute(..)` instead"
)]
pub trait CountQuery<Idx> {
    #[doc(hidden)]
    fn count_rendered(&self) -> (String, Vec<Value>);
}

/// The bound is on the method, and the impls are per-builder, for the two
/// reasons `LoadExt` explains.
pub trait CountExt {
    fn count<'e, Idx, E: sqlx::PgExecutor<'e>>(
        &self,
        executor: E,
    ) -> impl std::future::Future<Output = Result<i64>>
    where
        Self: CountQuery<Idx>,
    {
        count_rows(executor, self.count_rendered())
    }
}

impl<D, Scope, Sel, Outer> CountExt for Select<D, Scope, Sel, Outer> {}
impl<S, Sel> CountExt for Returning<S, Sel> {}
impl<D, Output> CountExt for DynSelect<D, Output> {}
impl<D, Output> CountExt for SetOp<D, Output> {}
impl<D, R: qbrs_core::insert::InsertRow> CountExt for Insert<D, R> {}
impl<D, T: qbrs_core::scope::Table> CountExt for Update<D, T> {}
impl<D, T: qbrs_core::scope::Table> CountExt for Delete<D, T> {}

impl<Scope, Sel: Selection<Scope, Idx>, Idx> CountQuery<Idx> for Select<Postgres, Scope, Sel> {
    fn count_rendered(&self) -> (String, Vec<Value>) {
        self.count_sql::<Idx>(Postgres)
    }
}

/// Erasure is for a query whose joins depend on a condition, and such a
/// query is paged like any other, so it counts like any other. The same
/// goes for a set-operation chain.
impl<Output> CountQuery<()> for DynSelect<Postgres, Output> {
    fn count_rendered(&self) -> (String, Vec<Value>) {
        self.count_sql(Postgres)
    }
}

impl<Output> CountQuery<()> for SetOp<Postgres, Output> {
    fn count_rendered(&self) -> (String, Vec<Value>) {
        self.count_sql(Postgres)
    }
}

async fn count_rows<'e, E: sqlx::PgExecutor<'e>>(
    executor: E,
    (sql, params): (String, Vec<Value>),
) -> Result<i64> {
    let row = bind_all(sqlx::query(sqlx::AssertSqlSafe(sql.as_str())), params)?
        .fetch_one(executor)
        .await?;
    Ok(row.try_get::<i64, _>(0)?)
}

/// Every writing statement, rendered: what `execute` returns is rows
/// affected, whichever of the three it was.
#[diagnostic::on_unimplemented(
    message = "`{Self}` isn't a statement this crate can execute",
    label = "an `INSERT`, `UPDATE` or `DELETE` in the `Postgres` dialect is; a `SELECT` or a `RETURNING` yields rows, so it goes through `.load(..)` — and a prepared query through `.load(.., params)`"
)]
pub trait WriteStatement {
    #[doc(hidden)]
    fn write_rendered(&self) -> (String, Vec<Value>);
}

#[diagnostic::do_not_recommend]
impl<S: Statement<Dialect = Postgres>> WriteStatement for S {
    fn write_rendered(&self) -> (String, Vec<Value>) {
        self.to_sql(Postgres)
    }
}

/// The bound is on the method, and the impls are per-builder, for the two
/// reasons `LoadExt` explains.
pub trait ExecuteExt {
    fn execute<'e, E: sqlx::PgExecutor<'e>>(
        &self,
        executor: E,
    ) -> impl std::future::Future<Output = Result<u64>>
    where
        Self: WriteStatement,
    {
        let (sql, params) = self.write_rendered();
        async move { execute_only(executor, &sql, params).await }
    }
}

impl<D, Scope, Sel, Outer> ExecuteExt for Select<D, Scope, Sel, Outer> {}
impl<S, Sel> ExecuteExt for Returning<S, Sel> {}
impl<D, Output> ExecuteExt for DynSelect<D, Output> {}
impl<D, Output> ExecuteExt for SetOp<D, Output> {}
impl<D, R: qbrs_core::insert::InsertRow> ExecuteExt for Insert<D, R> {}
impl<D, T: qbrs_core::scope::Table> ExecuteExt for Update<D, T> {}
impl<D, T: qbrs_core::scope::Table> ExecuteExt for Delete<D, T> {}

/// One impl for every `RETURNING`: what a statement returns is decided by
/// its selection, not by which statement it was.
impl<S: Statement<Dialect = Postgres>, Sel, Idx> RowQuery<Idx> for Returning<S, Sel>
where
    Sel: Selection<WrittenTable<S::Table>, Idx>,
    Sel::Output: DecodeRow,
{
    type Output = Sel::Output;
    fn rendered(&self) -> (String, Vec<Value>) {
        self.to_sql(Postgres)
    }
}

/// Decodes a query's `Output` positionally out of a `PgRow`. Keyed on the
/// plain-Rust type a selection produces rather than on the selection
/// itself: erasure leaves only `Output`, with no `Selection` impl left to
/// hang decoding off, so this is implemented directly against the closed set
/// of native types.
#[diagnostic::on_unimplemented(
    message = "`{Self}` isn't a value this crate can decode",
    label = "every selected column has to decode to one of the six built-in natives, or to a type whose feature is on here as well as on `qbrs`",
    note = "`chrono`/`uuid`/`decimal` have to be enabled on `qbrs-sqlx` too — they are separate `cfg`s over one `Value`"
)]
pub trait DecodeRow: Sized {
    #[doc(hidden)]
    fn decode_at(row: &PgRow, idx: &mut usize) -> sqlx::Result<Self>;
}

macro_rules! decode_row_leaf {
    ($ty:ty) => {
        impl DecodeRow for $ty {
            fn decode_at(row: &PgRow, idx: &mut usize) -> sqlx::Result<Self> {
                let v = row.try_get::<$ty, _>(*idx)?;
                *idx += 1;
                Ok(v)
            }
        }
        impl DecodeRow for Option<$ty> {
            fn decode_at(row: &PgRow, idx: &mut usize) -> sqlx::Result<Self> {
                let v = row.try_get::<Option<$ty>, _>(*idx)?;
                *idx += 1;
                Ok(v)
            }
        }
    };
}
decode_row_leaf!(i32);
decode_row_leaf!(i64);
decode_row_leaf!(f64);
decode_row_leaf!(String);
decode_row_leaf!(bool);
decode_row_leaf!(Vec<u8>);
#[cfg(feature = "chrono")]
decode_row_leaf!(chrono::DateTime<chrono::Utc>);
#[cfg(feature = "chrono")]
decode_row_leaf!(chrono::NaiveDate);
#[cfg(feature = "uuid")]
decode_row_leaf!(uuid::Uuid);
#[cfg(feature = "decimal")]
decode_row_leaf!(rust_decimal::Decimal);

impl DecodeRow for RowNil {
    fn decode_at(_row: &PgRow, _idx: &mut usize) -> sqlx::Result<Self> {
        Ok(RowNil)
    }
}

impl<K, V: DecodeRow, Tail: DecodeRow> DecodeRow for RowCons<K, V, Tail> {
    fn decode_at(row: &PgRow, idx: &mut usize) -> sqlx::Result<Self> {
        let value = V::decode_at(row, idx)?;
        Ok(RowCons::new(value, Tail::decode_at(row, idx)?))
    }
}

impl<L: DecodeRow> DecodeRow for Row<L> {
    fn decode_at(row: &PgRow, idx: &mut usize) -> sqlx::Result<Self> {
        Ok(Row::new(L::decode_at(row, idx)?))
    }
}

/// An erased query and a set-op chain were both rendered before their
/// selection type was gone, leaving nothing for `Idx` to index — hence
/// `RowQuery<()>`, the same trait with an empty proof.
impl<Output: DecodeRow> RowQuery<()> for DynSelect<Postgres, Output> {
    type Output = Output;
    fn rendered(&self) -> (String, Vec<Value>) {
        self.to_sql(Postgres)
    }
}

impl<Output: DecodeRow> RowQuery<()> for SetOp<Postgres, Output> {
    type Output = Output;
    fn rendered(&self) -> (String, Vec<Value>) {
        self.to_sql(Postgres)
    }
}

/// Runs a `prepare!{}`-built query, resolving its named placeholders from
/// `params` first. Separate from `LoadExt` only because the values arrive at
/// the call rather than being baked into the query: one `Prepared` is meant
/// to serve many calls, and `.resolve()` clones the template rather than
/// re-rendering it.
#[diagnostic::on_unimplemented(
    message = "`{Self}` isn't a prepared query this crate can run",
    label = "a `.prepare()`-built query is — `Prepared<D, Params, Output>`, params before output — and its `Params` have to be the ones it declared"
)]
pub trait PreparedQuery<Params> {
    type Output: DecodeRow;
    #[doc(hidden)]
    fn resolved(&self, params: Params) -> Result<(String, Vec<Value>)>;
}

/// The bound is on the method, and the impls are per-builder, for the two
/// reasons `LoadExt` explains.
pub trait PreparedExt {
    fn load<'e, Params, E: sqlx::PgExecutor<'e>>(
        &self,
        executor: E,
        params: Params,
    ) -> impl std::future::Future<Output = Result<Vec<<Self as PreparedQuery<Params>>::Output>>>
    where
        Self: PreparedQuery<Params>,
    {
        let resolved = self.resolved(params);
        async move {
            let (sql, values) = resolved?;
            fetch_all::<<Self as PreparedQuery<Params>>::Output, E>(executor, &sql, values).await
        }
    }

    fn load_one<'e, Params, E: sqlx::PgExecutor<'e>>(
        &self,
        executor: E,
        params: Params,
    ) -> impl std::future::Future<Output = Result<Option<<Self as PreparedQuery<Params>>::Output>>>
    where
        Self: PreparedQuery<Params>,
    {
        let resolved = self.resolved(params);
        async move {
            let (sql, values) = resolved?;
            fetch_optional::<<Self as PreparedQuery<Params>>::Output, E>(executor, &sql, values)
                .await
        }
    }
}

impl<D, Params, Output> PreparedExt for Prepared<D, Params, Output> {}

// A prepared query's `load`/`count` are told apart from the plain ones by
// arity, but `execute` is not — without this, it is the one terminal on the
// one builder that reports nothing.
impl<D, Params, Output> ExecuteExt for Prepared<D, Params, Output> {}

#[diagnostic::do_not_recommend]
impl<Params: PreparedParams, Output: DecodeRow> PreparedQuery<Params>
    for Prepared<Postgres, Params, Output>
{
    type Output = Output;

    fn resolved(&self, params: Params) -> Result<(String, Vec<Value>)> {
        Ok(self.resolve(params)?)
    }
}

/// A prepared total. Separate from `PreparedExt` for the reason `CountExt`
/// is separate from `LoadExt`: a count produces a number, not rows.
#[diagnostic::on_unimplemented(
    message = "`{Self}` isn't a prepared total this crate can run",
    label = "`.prepare_count()` builds one; `.prepare()` builds a query whose rows go through `.load(..)`"
)]
pub trait PreparedTotal<Params> {
    #[doc(hidden)]
    fn resolved_count(&self, params: Params) -> Result<(String, Vec<Value>)>;
}

impl<Params: PreparedParams> PreparedTotal<Params> for Prepared<Postgres, Params, Total> {
    fn resolved_count(&self, params: Params) -> Result<(String, Vec<Value>)> {
        Ok(self.resolve(params)?)
    }
}

/// The bound is on the method, and the impls are per-builder, for the two
/// reasons `LoadExt` explains.
pub trait PreparedCountExt {
    fn count<'e, Params, E: sqlx::PgExecutor<'e>>(
        &self,
        executor: E,
        params: Params,
    ) -> impl std::future::Future<Output = Result<i64>>
    where
        Self: PreparedTotal<Params>,
    {
        let resolved = self.resolved_count(params);
        async move { count_rows(executor, resolved?).await }
    }
}

impl<D, Params, Output> PreparedCountExt for Prepared<D, Params, Output> {}

#[cfg(test)]
mod tests {
    use super::*;

    // No real Postgres needed: binding inspects the `Value` enum before
    // anything reaches the network, so an unresolved placeholder is
    // reachable, and its error checkable, without a live DB.
    #[test]
    fn unresolved_placeholder_is_a_typed_error_not_a_sqlx_configuration_string() {
        let query = sqlx::query(sqlx::AssertSqlSafe("SELECT $1"));
        let err = match bind_all(query, vec![Value::Placeholder("email")]) {
            Err(e) => e,
            Ok(_) => panic!("unresolved placeholder must fail to bind"),
        };

        assert!(matches!(
            err,
            Error::UnresolvedPlaceholder(qbrs_core::select::UnresolvedPlaceholder("email"))
        ));
        // A real `std::error::Error`, so it composes with
        // `anyhow`/`Box<dyn Error>`.
        let _: &dyn std::error::Error = &err;
        assert_eq!(err.to_string(), "no value provided for placeholder `email`");
    }

    #[test]
    fn sqlx_errors_convert_via_from() {
        let err: Error = sqlx::Error::RowNotFound.into();
        assert!(matches!(err, Error::Sqlx(sqlx::Error::RowNotFound)));
    }
}