resolute 0.5.0

Compile-time-checked PostgreSQL queries with a pure-Rust wire protocol driver.
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
//! The `Executor` trait: a unified interface for query execution.
//!
//! Unlike sqlx's `Executor` which consumes `self` (preventing multi-query reuse),
//! this trait uses `&self` methods. Write generic functions once, call them with
//! any executor type:
//!
//! ```no_run
//! # use resolute::{Client, Executor, FromRow, TypedError};
//! # #[derive(FromRow)] struct User { id: i32 }
//! async fn get_user(db: &impl Executor, id: i32) -> Result<User, TypedError> {
//!     let rows = db.query("SELECT * FROM users WHERE id = $1", &[&id]).await?;
//!     User::from_row(&rows[0])
//! }
//!
//! # async fn _demo() -> Result<(), TypedError> {
//! # let client: Client = unimplemented!();
//! # let txn: resolute::Transaction = unimplemented!();
//! # let pooled: resolute::PooledClient = unimplemented!();
//! // Works with Client, Transaction, or PooledClient:
//! get_user(&client, 1).await?;
//! get_user(&txn, 1).await?;
//! get_user(&pooled, 1).await?;
//! # Ok(()) }
//! ```

use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};

use crate::encode::SqlParam;
use crate::error::TypedError;
use crate::row::Row;

static SAVEPOINT_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Trait for types that can execute PostgreSQL queries.
///
/// All methods take `&self` — no consuming, no lifetime gymnastics.
/// Only `query` and `execute` need to be implemented; the rest are
/// provided as default methods.
///
/// # Examples
///
/// Write generic functions that work with any executor:
///
/// ```no_run
/// # use resolute::{Client, Executor, TypedError};
/// async fn count_users(db: &impl Executor) -> Result<i64, TypedError> {
///     let row = db.query_one("SELECT count(*) FROM users", &[]).await?;
///     row.get::<i64>(0)
/// }
///
/// # async fn _demo() -> Result<(), TypedError> {
/// # let client: Client = unimplemented!();
/// # let txn: resolute::Transaction = unimplemented!();
/// # let pooled: resolute::PooledClient = unimplemented!();
/// // Call with a Client, Transaction, or PooledClient:
/// let _n = count_users(&client).await?;
/// let _n = count_users(&txn).await?;
/// let _n = count_users(&pooled).await?;
/// # Ok(()) }
/// ```
pub trait Executor: Send + Sync {
    /// Execute a query and return all result rows.
    fn query<'a>(
        &'a self,
        sql: &'a str,
        params: &'a [&'a dyn SqlParam],
    ) -> impl Future<Output = Result<Vec<Row>, TypedError>> + Send + 'a;

    /// Execute a statement (INSERT/UPDATE/DELETE) and return affected row count.
    fn execute<'a>(
        &'a self,
        sql: &'a str,
        params: &'a [&'a dyn SqlParam],
    ) -> impl Future<Output = Result<u64, TypedError>> + Send + 'a;

    /// Execute a query and return exactly one row.
    fn query_one<'a>(
        &'a self,
        sql: &'a str,
        params: &'a [&'a dyn SqlParam],
    ) -> impl Future<Output = Result<Row, TypedError>> + Send + 'a {
        async move {
            let rows = self.query(sql, params).await?;
            if rows.len() != 1 {
                return Err(TypedError::NotExactlyOne(rows.len()));
            }
            Ok(rows.into_iter().next().unwrap())
        }
    }

    /// Execute a query and return an optional single row.
    fn query_opt<'a>(
        &'a self,
        sql: &'a str,
        params: &'a [&'a dyn SqlParam],
    ) -> impl Future<Output = Result<Option<Row>, TypedError>> + Send + 'a {
        async move {
            let rows = self.query(sql, params).await?;
            match rows.len() {
                0 => Ok(None),
                1 => Ok(Some(rows.into_iter().next().unwrap())),
                n => Err(TypedError::NotExactlyOne(n)),
            }
        }
    }

    /// Execute a query with named parameters (`:name` syntax).
    fn query_named<'a>(
        &'a self,
        sql: &'a str,
        params: &'a [(&'a str, &'a dyn SqlParam)],
    ) -> impl Future<Output = Result<Vec<Row>, TypedError>> + Send + 'a {
        async move {
            let (rewritten, names) = crate::named_params::rewrite(sql);
            let ordered = resolve_named(&names, params)?;
            self.query(&rewritten, &ordered).await
        }
    }

    /// Execute a named-param statement. Returns affected row count.
    fn execute_named<'a>(
        &'a self,
        sql: &'a str,
        params: &'a [(&'a str, &'a dyn SqlParam)],
    ) -> impl Future<Output = Result<u64, TypedError>> + Send + 'a {
        async move {
            let (rewritten, names) = crate::named_params::rewrite(sql);
            let ordered = resolve_named(&names, params)?;
            self.execute(&rewritten, &ordered).await
        }
    }

    /// Run a closure with guaranteed atomicity.
    ///
    /// - **Client / PooledClient**: wraps in `BEGIN` / `COMMIT` (or `ROLLBACK` on error).
    /// - **Transaction**: uses a `SAVEPOINT` (nested transaction), so calling `atomic`
    ///   inside an existing transaction is safe and composes correctly.
    ///
    /// This lets you write functions that always run atomically, regardless of
    /// whether the caller already has a transaction open:
    ///
    /// ```no_run
    /// # use resolute::{Client, Executor, TypedError};
    /// # struct Item;
    /// # struct Order { id: i32 }
    /// # async fn insert_order(_db: &(impl Executor + ?Sized)) -> Result<Order, TypedError> { unimplemented!() }
    /// # async fn insert_line_item(_db: &(impl Executor + ?Sized), _id: i32, _item: &Item) -> Result<(), TypedError> { unimplemented!() }
    /// # async fn do_other_stuff(_db: &(impl Executor + ?Sized)) -> Result<(), TypedError> { unimplemented!() }
    /// async fn create_order(db: &impl Executor, items: &[Item]) -> Result<Order, TypedError> {
    ///     db.atomic(|db| Box::pin(async move {
    ///         let order = insert_order(db).await?;
    ///         for item in items {
    ///             insert_line_item(db, order.id, item).await?;
    ///         }
    ///         Ok(order)
    ///     })).await
    /// }
    ///
    /// # async fn _demo() -> Result<(), TypedError> {
    /// # let client: Client = unimplemented!();
    /// # let items: Vec<Item> = vec![];
    /// // Without a transaction, atomic() creates one:
    /// create_order(&client, &items).await?;
    ///
    /// // Inside an existing transaction, atomic() uses a savepoint:
    /// let txn = client.begin().await?;
    /// create_order(&txn, &items).await?;  // savepoint, not a nested BEGIN
    /// do_other_stuff(&txn).await?;
    /// txn.commit().await?;
    /// # Ok(()) }
    /// ```
    fn atomic<'a, T: Send + 'a>(
        &'a self,
        f: impl FnOnce(&'a Self) -> Pin<Box<dyn Future<Output = Result<T, TypedError>> + Send + 'a>>
            + Send
            + 'a,
    ) -> impl Future<Output = Result<T, TypedError>> + Send + 'a;

    /// Ping the database to verify the connection is healthy.
    fn ping<'a>(&'a self) -> impl Future<Output = Result<(), TypedError>> + Send + 'a {
        async move {
            self.query("SELECT 1", &[]).await?;
            Ok(())
        }
    }

    /// Bulk-load data via COPY FROM STDIN. Returns the number of rows copied.
    fn copy_in<'a>(
        &'a self,
        copy_sql: &'a str,
        data: &'a [u8],
    ) -> impl Future<Output = Result<u64, TypedError>> + Send + 'a;

    /// Export data via COPY TO STDOUT. Returns all the data.
    fn copy_out<'a>(
        &'a self,
        copy_sql: &'a str,
    ) -> impl Future<Output = Result<Vec<u8>, TypedError>> + Send + 'a;
}

/// Resolve named params to positional order.
fn resolve_named<'a>(
    names: &[String],
    params: &[(&str, &'a dyn SqlParam)],
) -> Result<Vec<&'a dyn SqlParam>, TypedError> {
    names
        .iter()
        .map(|name| {
            params
                .iter()
                .find(|(n, _)| *n == name.as_str())
                .map(|(_, p)| *p)
                .ok_or_else(|| TypedError::MissingParam(name.to_string()))
        })
        .collect()
}

// ---------------------------------------------------------------------------
// Implementations
// ---------------------------------------------------------------------------

#[allow(clippy::manual_async_fn)]
impl Executor for crate::query::Client {
    fn query<'a>(
        &'a self,
        sql: &'a str,
        params: &'a [&'a dyn SqlParam],
    ) -> impl Future<Output = Result<Vec<Row>, TypedError>> + Send + 'a {
        crate::query::Client::query(self, sql, params)
    }

    fn execute<'a>(
        &'a self,
        sql: &'a str,
        params: &'a [&'a dyn SqlParam],
    ) -> impl Future<Output = Result<u64, TypedError>> + Send + 'a {
        crate::query::Client::execute(self, sql, params)
    }

    fn copy_in<'a>(
        &'a self,
        copy_sql: &'a str,
        data: &'a [u8],
    ) -> impl Future<Output = Result<u64, TypedError>> + Send + 'a {
        crate::query::Client::copy_in(self, copy_sql, data)
    }

    fn copy_out<'a>(
        &'a self,
        copy_sql: &'a str,
    ) -> impl Future<Output = Result<Vec<u8>, TypedError>> + Send + 'a {
        crate::query::Client::copy_out(self, copy_sql)
    }

    fn atomic<'a, T: Send + 'a>(
        &'a self,
        f: impl FnOnce(&'a Self) -> Pin<Box<dyn Future<Output = Result<T, TypedError>> + Send + 'a>>
            + Send
            + 'a,
    ) -> impl Future<Output = Result<T, TypedError>> + Send + 'a {
        async move {
            self.simple_query("BEGIN").await?;
            match f(self).await {
                Ok(val) => {
                    self.simple_query("COMMIT").await?;
                    Ok(val)
                }
                Err(e) => {
                    if let Err(rb_err) = self.simple_query("ROLLBACK").await {
                        tracing::error!(error = %rb_err, "transaction rollback failed");
                    }
                    Err(e)
                }
            }
        }
    }
}

#[allow(clippy::manual_async_fn)]
impl Executor for crate::query::Transaction<'_> {
    fn query<'a>(
        &'a self,
        sql: &'a str,
        params: &'a [&'a dyn SqlParam],
    ) -> impl Future<Output = Result<Vec<Row>, TypedError>> + Send + 'a {
        self.client.query(sql, params)
    }

    fn execute<'a>(
        &'a self,
        sql: &'a str,
        params: &'a [&'a dyn SqlParam],
    ) -> impl Future<Output = Result<u64, TypedError>> + Send + 'a {
        self.client.execute(sql, params)
    }

    fn copy_in<'a>(
        &'a self,
        copy_sql: &'a str,
        data: &'a [u8],
    ) -> impl Future<Output = Result<u64, TypedError>> + Send + 'a {
        self.client.copy_in(copy_sql, data)
    }

    fn copy_out<'a>(
        &'a self,
        copy_sql: &'a str,
    ) -> impl Future<Output = Result<Vec<u8>, TypedError>> + Send + 'a {
        self.client.copy_out(copy_sql)
    }

    fn atomic<'a, T: Send + 'a>(
        &'a self,
        f: impl FnOnce(&'a Self) -> Pin<Box<dyn Future<Output = Result<T, TypedError>> + Send + 'a>>
            + Send
            + 'a,
    ) -> impl Future<Output = Result<T, TypedError>> + Send + 'a {
        async move {
            let id = SAVEPOINT_COUNTER.fetch_add(1, Ordering::Relaxed);
            let sp = format!("resolute_sp_{id}");
            self.client.simple_query(&format!("SAVEPOINT {sp}")).await?;
            match f(self).await {
                Ok(val) => {
                    self.client
                        .simple_query(&format!("RELEASE SAVEPOINT {sp}"))
                        .await?;
                    Ok(val)
                }
                Err(e) => {
                    if let Err(rb_err) = self
                        .client
                        .simple_query(&format!("ROLLBACK TO SAVEPOINT {sp}"))
                        .await
                    {
                        tracing::error!(error = %rb_err, savepoint = %sp, "savepoint rollback failed");
                    }
                    Err(e)
                }
            }
        }
    }
}

#[allow(clippy::manual_async_fn)]
impl Executor for crate::pooled::PooledClient {
    fn query<'a>(
        &'a self,
        sql: &'a str,
        params: &'a [&'a dyn SqlParam],
    ) -> impl Future<Output = Result<Vec<Row>, TypedError>> + Send + 'a {
        crate::pooled::PooledClient::query(self, sql, params)
    }

    fn execute<'a>(
        &'a self,
        sql: &'a str,
        params: &'a [&'a dyn SqlParam],
    ) -> impl Future<Output = Result<u64, TypedError>> + Send + 'a {
        crate::pooled::PooledClient::execute(self, sql, params)
    }

    fn copy_in<'a>(
        &'a self,
        copy_sql: &'a str,
        data: &'a [u8],
    ) -> impl Future<Output = Result<u64, TypedError>> + Send + 'a {
        crate::pooled::PooledClient::copy_in(self, copy_sql, data)
    }

    fn copy_out<'a>(
        &'a self,
        copy_sql: &'a str,
    ) -> impl Future<Output = Result<Vec<u8>, TypedError>> + Send + 'a {
        crate::pooled::PooledClient::copy_out(self, copy_sql)
    }

    fn atomic<'a, T: Send + 'a>(
        &'a self,
        f: impl FnOnce(&'a Self) -> Pin<Box<dyn Future<Output = Result<T, TypedError>> + Send + 'a>>
            + Send
            + 'a,
    ) -> impl Future<Output = Result<T, TypedError>> + Send + 'a {
        async move {
            self.simple_query("BEGIN").await?;
            match f(self).await {
                Ok(val) => {
                    self.simple_query("COMMIT").await?;
                    Ok(val)
                }
                Err(e) => {
                    if let Err(rb_err) = self.simple_query("ROLLBACK").await {
                        tracing::error!(error = %rb_err, "transaction rollback failed");
                    }
                    Err(e)
                }
            }
        }
    }
}

#[allow(clippy::manual_async_fn)]
impl Executor for crate::reconnect::ReconnectingClient {
    fn query<'a>(
        &'a self,
        sql: &'a str,
        params: &'a [&'a dyn SqlParam],
    ) -> impl Future<Output = Result<Vec<Row>, TypedError>> + Send + 'a {
        crate::reconnect::ReconnectingClient::query(self, sql, params)
    }

    fn execute<'a>(
        &'a self,
        sql: &'a str,
        params: &'a [&'a dyn SqlParam],
    ) -> impl Future<Output = Result<u64, TypedError>> + Send + 'a {
        crate::reconnect::ReconnectingClient::execute(self, sql, params)
    }

    fn copy_in<'a>(
        &'a self,
        copy_sql: &'a str,
        data: &'a [u8],
    ) -> impl Future<Output = Result<u64, TypedError>> + Send + 'a {
        async move { self.client().copy_in(copy_sql, data).await }
    }

    fn copy_out<'a>(
        &'a self,
        copy_sql: &'a str,
    ) -> impl Future<Output = Result<Vec<u8>, TypedError>> + Send + 'a {
        async move { self.client().copy_out(copy_sql).await }
    }

    fn atomic<'a, T: Send + 'a>(
        &'a self,
        f: impl FnOnce(&'a Self) -> Pin<Box<dyn Future<Output = Result<T, TypedError>> + Send + 'a>>
            + Send
            + 'a,
    ) -> impl Future<Output = Result<T, TypedError>> + Send + 'a {
        async move {
            let client = self.client();
            client.simple_query("BEGIN").await?;
            match f(self).await {
                Ok(val) => {
                    client.simple_query("COMMIT").await?;
                    Ok(val)
                }
                Err(e) => {
                    if let Err(rb_err) = client.simple_query("ROLLBACK").await {
                        tracing::error!(error = %rb_err, "transaction rollback failed");
                    }
                    Err(e)
                }
            }
        }
    }
}

#[allow(clippy::manual_async_fn)]
impl Executor for crate::pooled::PooledTransaction<'_> {
    fn query<'a>(
        &'a self,
        sql: &'a str,
        params: &'a [&'a dyn SqlParam],
    ) -> impl Future<Output = Result<Vec<Row>, TypedError>> + Send + 'a {
        crate::pooled::PooledTransaction::query(self, sql, params)
    }

    fn execute<'a>(
        &'a self,
        sql: &'a str,
        params: &'a [&'a dyn SqlParam],
    ) -> impl Future<Output = Result<u64, TypedError>> + Send + 'a {
        crate::pooled::PooledTransaction::execute(self, sql, params)
    }

    fn copy_in<'a>(
        &'a self,
        copy_sql: &'a str,
        data: &'a [u8],
    ) -> impl Future<Output = Result<u64, TypedError>> + Send + 'a {
        async move { self.client().copy_in(copy_sql, data).await }
    }

    fn copy_out<'a>(
        &'a self,
        copy_sql: &'a str,
    ) -> impl Future<Output = Result<Vec<u8>, TypedError>> + Send + 'a {
        async move { self.client().copy_out(copy_sql).await }
    }

    fn atomic<'a, T: Send + 'a>(
        &'a self,
        f: impl FnOnce(&'a Self) -> Pin<Box<dyn Future<Output = Result<T, TypedError>> + Send + 'a>>
            + Send
            + 'a,
    ) -> impl Future<Output = Result<T, TypedError>> + Send + 'a {
        async move {
            let id = SAVEPOINT_COUNTER.fetch_add(1, Ordering::Relaxed);
            let sp = format!("resolute_sp_{id}");
            self.client()
                .simple_query(&format!("SAVEPOINT {sp}"))
                .await?;
            match f(self).await {
                Ok(val) => {
                    self.client()
                        .simple_query(&format!("RELEASE SAVEPOINT {sp}"))
                        .await?;
                    Ok(val)
                }
                Err(e) => {
                    if let Err(rb_err) = self
                        .client()
                        .simple_query(&format!("ROLLBACK TO SAVEPOINT {sp}"))
                        .await
                    {
                        tracing::error!(error = %rb_err, savepoint = %sp, "savepoint rollback failed");
                    }
                    Err(e)
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Closure-based transaction API
// ---------------------------------------------------------------------------

impl crate::query::Client {
    /// Run a closure inside a transaction. Commits on `Ok`, rolls back on `Err`.
    ///
    /// The closure receives the `Client` reference (which is inside a BEGIN..COMMIT
    /// block), so any `&impl Executor` function works inside it.
    ///
    /// ```no_run
    /// # use resolute::{Client, Executor, TypedError};
    /// # async fn create_user(_db: &Client, _name: &str) -> Result<i32, TypedError> { unimplemented!() }
    /// # async fn create_profile(_db: &Client, _id: i32) -> Result<(), TypedError> { unimplemented!() }
    /// # async fn _demo() -> Result<(), TypedError> {
    /// # let client: Client = unimplemented!();
    /// let _user_id = client.with_transaction(|db| Box::pin(async move {
    ///     let id = create_user(db, "Alice").await?;
    ///     create_profile(db, id).await?;
    ///     Ok(id)
    /// })).await?;
    /// # Ok(()) }
    /// ```
    pub async fn with_transaction<'a, T: Send + 'a>(
        &'a self,
        f: impl FnOnce(&'a Self) -> Pin<Box<dyn Future<Output = Result<T, TypedError>> + Send + 'a>>,
    ) -> Result<T, TypedError> {
        self.simple_query("BEGIN").await?;
        match f(self).await {
            Ok(val) => {
                self.simple_query("COMMIT").await?;
                Ok(val)
            }
            Err(e) => {
                if let Err(rollback_err) = self.simple_query("ROLLBACK").await {
                    tracing::warn!(
                        error = %rollback_err,
                        "ROLLBACK failed after transaction error; connection may be unhealthy"
                    );
                }
                Err(e)
            }
        }
    }
}