ruprizzle 1.6.0

A schema-first ORM for Rust: typed queries, relations, and automatic migrations
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
//! Transaction handle.

use std::borrow::Cow;
use std::fmt;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Mutex, PoisonError};

use tokio::sync::Mutex as AsyncMutex;

use ruprizzle_core::ir::Provider;
use ruprizzle_dialect::{DbDialect, dialect_for};
use sqlx::{Any, MySql, Postgres, Sqlite};

use crate::BoxFuture;
use crate::Error;
use crate::executor::RowBatch;
use crate::model::RowDecode;
use crate::pool::Pool;
use crate::value::Value;

/// The isolation level for a transaction.
///
/// Postgres honours all three. SQLite has a single writer and is effectively
/// serializable already, so the level is accepted and ignored there rather than
/// failing — the same application code has to run on both backends.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IsolationLevel {
    /// Each statement sees rows committed before it began.
    ReadCommitted,
    /// All statements see the snapshot taken at the first read.
    RepeatableRead,
    /// Full serializability; may abort with a serialization failure.
    Serializable,
}

impl IsolationLevel {
    /// The SQL fragment used in `SET TRANSACTION ISOLATION LEVEL ...`.
    #[must_use]
    pub const fn as_sql(self) -> &'static str {
        match self {
            Self::ReadCommitted => "READ COMMITTED",
            Self::RepeatableRead => "REPEATABLE READ",
            Self::Serializable => "SERIALIZABLE",
        }
    }
}

#[derive(Debug)]
enum TxInner {
    Any(sqlx::Transaction<'static, Any>),
    Postgres(sqlx::Transaction<'static, Postgres>),
    Sqlite(sqlx::Transaction<'static, Sqlite>),
    Mysql(sqlx::Transaction<'static, MySql>),
    #[cfg(feature = "sqlite-rusqlite")]
    SqliteNative(crate::rusqlite::RusqliteTransaction),
    #[cfg(feature = "postgres-tokio-postgres")]
    PostgresNative(crate::tokio_postgres::TokioPostgresTransaction),
}

/// A transaction in progress.
pub struct Tx {
    inner: AsyncMutex<Option<TxInner>>,
    provider: Provider,
    dialect: &'static dyn DbDialect,
    full_table_include_limit: u64,
    savepoint_counter: AtomicUsize,
    /// Savepoints whose [`Savepoint`] handle was dropped without an explicit
    /// `release` or `rollback`. They are rolled back before the next operation
    /// on this transaction, matching the synchronous rollback that sqlx and the
    /// native drivers do for abandoned transactions.
    pending_rollback: Mutex<Vec<String>>,
}

impl fmt::Debug for Tx {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Tx")
            .field("provider", &self.provider)
            .field("dialect", &self.dialect.name())
            .field("full_table_include_limit", &self.full_table_include_limit)
            .field(
                "savepoint_counter",
                &self.savepoint_counter.load(Ordering::Relaxed),
            )
            .finish_non_exhaustive()
    }
}

impl Tx {
    /// Begins a new transaction on `pool`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Sqlx`] if the database cannot begin a transaction.
    pub async fn begin(pool: &Pool) -> Result<Self, Error> {
        let tx = match pool {
            Pool::Any(p) => TxInner::Any(p.begin().await.map_err(Error::Sqlx)?),
            Pool::Postgres(p) => TxInner::Postgres(p.begin().await.map_err(Error::Sqlx)?),
            Pool::Sqlite(p) => TxInner::Sqlite(p.begin().await.map_err(Error::Sqlx)?),
            Pool::Mysql(p) => TxInner::Mysql(p.begin().await.map_err(Error::Sqlx)?),
            #[cfg(feature = "sqlite-rusqlite")]
            Pool::SqliteNative(p) => TxInner::SqliteNative(p.begin_transaction().await?),
            #[cfg(feature = "postgres-tokio-postgres")]
            Pool::PostgresNative(p) => TxInner::PostgresNative(p.begin().await?),
        };
        let provider = pool.provider();
        Ok(Self {
            inner: AsyncMutex::new(Some(tx)),
            provider,
            dialect: dialect_for(provider),
            full_table_include_limit: crate::executor::Executor::full_table_include_limit(pool),
            savepoint_counter: AtomicUsize::new(0),
            pending_rollback: Mutex::new(Vec::new()),
        })
    }

    /// Begins a new transaction with an explicit isolation level.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Sqlx`] if the transaction cannot be started or the
    /// level cannot be set.
    pub async fn begin_with_isolation(pool: &Pool, level: IsolationLevel) -> Result<Self, Error> {
        let this = Self::begin(pool).await?;
        if this.provider == Provider::Postgres {
            this.execute(
                &format!("SET TRANSACTION ISOLATION LEVEL {}", level.as_sql()),
                &[],
            )
            .await?;
        }
        Ok(this)
    }

    /// The dialect for the backend this transaction runs on.
    #[must_use]
    pub fn dialect(&self) -> &dyn DbDialect {
        self.dialect
    }

    /// Create a new savepoint inside this transaction.
    ///
    /// The savepoint name is generated by a monotonic counter on this
    /// transaction. User-supplied names are never accepted, because they would
    /// be a SQL identifier injection vector.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Message`] if the transaction has already finished, or
    /// a driver error if the `SAVEPOINT` command fails.
    pub async fn savepoint(&self) -> Result<Savepoint<'_>, Error> {
        let n = self.savepoint_counter.fetch_add(1, Ordering::Relaxed);
        let name = format!("__ruprizzle_sp_{n}");
        self.execute(&format!("SAVEPOINT {name}"), &[]).await?;
        Ok(Savepoint::new(self, name))
    }

    /// Run a closure inside a nested (savepoint) transaction.
    ///
    /// On `Ok`, the savepoint is released. On `Err`, it is rolled back to.
    /// This mirrors the nested-transaction API in ORMs such as Drizzle.
    ///
    /// The closure receives a [`Savepoint`] handle that can be used to create
    /// further nested savepoints or to execute queries (it implements
    /// [`crate::Executor`]).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Message`] if the transaction has already finished, or
    /// any error produced by the closure or the release/rollback.
    pub async fn transaction<'tx, F, T, E>(&'tx self, f: F) -> Result<T, E>
    where
        F: for<'a> FnOnce(&'a Savepoint<'a>) -> BoxFuture<'a, Result<T, E>>,
        E: From<Error>,
    {
        let sp = self.savepoint().await?;
        match f(&sp).await {
            Ok(v) => {
                sp.release().await?;
                Ok(v)
            }
            Err(e) => {
                sp.rollback().await?;
                Err(e)
            }
        }
    }

    /// Commits the transaction.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Sqlx`] if the commit fails.
    pub async fn commit(self) -> Result<(), Error> {
        self.flush_pending_rollback().await?;

        let tx = self.inner.lock().await.take();
        if let Some(tx) = tx {
            match tx {
                TxInner::Any(tx) => tx.commit().await.map_err(Error::Sqlx)?,
                TxInner::Postgres(tx) => tx.commit().await.map_err(Error::Sqlx)?,
                TxInner::Sqlite(tx) => tx.commit().await.map_err(Error::Sqlx)?,
                TxInner::Mysql(tx) => tx.commit().await.map_err(Error::Sqlx)?,
                #[cfg(feature = "sqlite-rusqlite")]
                TxInner::SqliteNative(tx) => {
                    tx.commit()?;
                }
                #[cfg(feature = "postgres-tokio-postgres")]
                TxInner::PostgresNative(tx) => {
                    tx.commit().await?;
                }
            };
            tracing::debug!(target: "ruprizzle::query", "transaction committed");
        }
        Ok(())
    }

    /// Rolls back the transaction.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Sqlx`] if the rollback fails.
    pub async fn rollback(self) -> Result<(), Error> {
        self.flush_pending_rollback().await?;

        let tx = self.inner.lock().await.take();
        if let Some(tx) = tx {
            match tx {
                TxInner::Any(tx) => tx.rollback().await.map_err(Error::Sqlx)?,
                TxInner::Postgres(tx) => tx.rollback().await.map_err(Error::Sqlx)?,
                TxInner::Sqlite(tx) => tx.rollback().await.map_err(Error::Sqlx)?,
                TxInner::Mysql(tx) => tx.rollback().await.map_err(Error::Sqlx)?,
                #[cfg(feature = "sqlite-rusqlite")]
                TxInner::SqliteNative(tx) => {
                    tx.rollback()?;
                }
                #[cfg(feature = "postgres-tokio-postgres")]
                TxInner::PostgresNative(tx) => {
                    tx.rollback().await?;
                }
            };
            tracing::debug!(target: "ruprizzle::query", "transaction rolled back");
        }
        Ok(())
    }

    /// Executes a raw statement inside the transaction, returning rows affected.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Sqlx`] for database errors or [`Error::Message`] if the
    /// transaction has already been finished.
    pub async fn execute(&self, sql: &str, binds: &[Value]) -> Result<u64, Error> {
        self.flush_pending_rollback().await?;
        self.execute_unchecked(sql, binds).await
    }

    /// Fetches all rows from a raw statement inside the transaction.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Sqlx`] for database errors or [`Error::Message`] if the
    /// transaction has already been finished.
    pub async fn fetch_all<T>(&self, sql: &str, binds: &[Value]) -> Result<Vec<T>, Error>
    where
        T: Send + Unpin + RowDecode,
    {
        self.flush_pending_rollback().await?;
        self.fetch_all_unchecked(sql, binds).await
    }

    /// Fetches one row from a raw statement inside the transaction.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Sqlx`] for database errors or [`Error::Message`] if the
    /// transaction has already been finished.
    pub async fn fetch_one<T>(&self, sql: &str, binds: &[Value]) -> Result<T, Error>
    where
        T: Send + Unpin + RowDecode,
    {
        self.flush_pending_rollback().await?;
        let rows = self.fetch_all_unchecked::<T>(sql, binds).await?;
        rows.into_iter()
            .next()
            .ok_or_else(|| Error::Message("no row found".into()))
    }

    /// Fetches one row from a raw statement inside the transaction.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Sqlx`] for database errors or [`Error::Message`] if the
    /// transaction has already been finished.
    pub async fn fetch_optional<T>(&self, sql: &str, binds: &[Value]) -> Result<Option<T>, Error>
    where
        T: Send + Unpin + RowDecode,
    {
        self.flush_pending_rollback().await?;
        let rows = self.fetch_all_unchecked::<T>(sql, binds).await?;
        Ok(rows.into_iter().next())
    }

    /// Fetches raw rows inside the transaction.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Sqlx`] for database errors or [`Error::Message`] if the
    /// transaction has already been finished.
    pub(crate) async fn fetch_all_rows(
        &self,
        sql: &str,
        binds: &[Value],
    ) -> Result<RowBatch, Error> {
        self.flush_pending_rollback().await?;
        self.fetch_all_rows_unchecked(sql, binds).await
    }

    /// Roll back any savepoints whose handles were dropped without an explicit
    /// finish, then issue `sql`.
    ///
    /// This is the core execution path used by every public operation so that
    /// abandoned savepoints do not accidentally get committed with the outer
    /// transaction.
    async fn flush_pending_rollback(&self) -> Result<(), Error> {
        let pending = {
            let mut guard = self
                .pending_rollback
                .lock()
                .unwrap_or_else(PoisonError::into_inner);
            if guard.is_empty() {
                return Ok(());
            }
            std::mem::take(&mut *guard)
        };

        // Roll back from innermost to outermost. Each savepoint is created
        // with a higher counter than the previous one, so the highest index
        // is the deepest.
        for name in pending.into_iter().rev() {
            self.execute_unchecked(&format!("ROLLBACK TO SAVEPOINT {name}"), &[])
                .await?;
        }

        Ok(())
    }

    async fn execute_unchecked(&self, sql: &str, binds: &[Value]) -> Result<u64, Error> {
        let mut guard = self.inner.lock().await;
        let tx = guard
            .as_mut()
            .ok_or_else(|| Error::Message("transaction already finished".into()))?;

        // MySQL rejects savepoint commands over the prepared-statement protocol
        // ("1295: This command is not supported in the prepared statement
        // protocol yet"), so send them as plain text. They never carry binds.
        let text_protocol =
            self.provider == Provider::Mysql && binds.is_empty() && is_savepoint_command(sql);

        match tx {
            // A bare `&str` carries no arguments, which sqlx sends as a text
            // query rather than a prepared statement.
            TxInner::Any(tx) if text_protocol => sqlx::Executor::execute(&mut **tx, sql)
                .await
                .map(|r| r.rows_affected())
                .map_err(Error::Sqlx),
            TxInner::Mysql(tx) if text_protocol => sqlx::Executor::execute(&mut **tx, sql)
                .await
                .map(|r| r.rows_affected())
                .map_err(Error::Sqlx),
            TxInner::Any(tx) => {
                let mut q = sqlx::query::<Any>(sql);
                for b in binds {
                    q = q.bind(b);
                }
                q.execute(&mut **tx)
                    .await
                    .map(|r| r.rows_affected())
                    .map_err(Error::Sqlx)
            }
            TxInner::Postgres(tx) => {
                let mut q = sqlx::query::<Postgres>(sql);
                for b in binds {
                    q = q.bind(b);
                }
                q.execute(&mut **tx)
                    .await
                    .map(|r| r.rows_affected())
                    .map_err(Error::Sqlx)
            }
            TxInner::Sqlite(tx) => {
                let mut q = sqlx::query::<Sqlite>(sql);
                for b in binds {
                    q = q.bind(b);
                }
                q.execute(&mut **tx)
                    .await
                    .map(|r| r.rows_affected())
                    .map_err(Error::Sqlx)
            }
            TxInner::Mysql(tx) => {
                let mut q = sqlx::query::<MySql>(sql);
                for b in binds {
                    q = q.bind(b);
                }
                q.execute(&mut **tx)
                    .await
                    .map(|r| r.rows_affected())
                    .map_err(Error::Sqlx)
            }
            #[cfg(feature = "sqlite-rusqlite")]
            TxInner::SqliteNative(tx) => tx.execute_sync(sql, binds),
            #[cfg(feature = "postgres-tokio-postgres")]
            TxInner::PostgresNative(tx) => tx.execute(sql, binds).await,
        }
    }

    async fn fetch_all_unchecked<T>(&self, sql: &str, binds: &[Value]) -> Result<Vec<T>, Error>
    where
        T: Send + Unpin + RowDecode,
    {
        let mut guard = self.inner.lock().await;
        let tx = guard
            .as_mut()
            .ok_or_else(|| Error::Message("transaction already finished".into()))?;

        match tx {
            TxInner::Any(tx) => {
                let mut q = sqlx::query_as::<Any, T>(sql);
                for b in binds {
                    q = q.bind(b);
                }
                q.fetch_all(&mut **tx).await.map_err(Error::Sqlx)
            }
            TxInner::Postgres(tx) => {
                let mut q = sqlx::query_as::<Postgres, T>(sql);
                for b in binds {
                    q = q.bind(b);
                }
                q.fetch_all(&mut **tx).await.map_err(Error::Sqlx)
            }
            TxInner::Sqlite(tx) => {
                let mut q = sqlx::query_as::<Sqlite, T>(sql);
                for b in binds {
                    q = q.bind(b);
                }
                q.fetch_all(&mut **tx).await.map_err(Error::Sqlx)
            }
            TxInner::Mysql(tx) => {
                let mut q = sqlx::query_as::<MySql, T>(sql);
                for b in binds {
                    q = q.bind(b);
                }
                q.fetch_all(&mut **tx).await.map_err(Error::Sqlx)
            }
            #[cfg(feature = "sqlite-rusqlite")]
            TxInner::SqliteNative(tx) => {
                let batch = tx.fetch_all_sync(sql, binds)?;
                crate::executor::decode_rows::<T>(batch)
            }
            #[cfg(feature = "postgres-tokio-postgres")]
            TxInner::PostgresNative(tx) => {
                let batch = tx.fetch_all(sql, binds).await?;
                crate::executor::decode_rows::<T>(batch)
            }
        }
    }

    async fn fetch_all_rows_unchecked(
        &self,
        sql: &str,
        binds: &[Value],
    ) -> Result<RowBatch, Error> {
        let mut guard = self.inner.lock().await;
        let tx = guard
            .as_mut()
            .ok_or_else(|| Error::Message("transaction already finished".into()))?;

        match tx {
            TxInner::Any(tx) => {
                let mut q = sqlx::query::<Any>(sql);
                for b in binds {
                    q = q.bind(b);
                }
                q.fetch_all(&mut **tx)
                    .await
                    .map(RowBatch::Any)
                    .map_err(Error::Sqlx)
            }
            TxInner::Postgres(tx) => {
                let mut q = sqlx::query::<Postgres>(sql);
                for b in binds {
                    q = q.bind(b);
                }
                q.fetch_all(&mut **tx)
                    .await
                    .map(RowBatch::Postgres)
                    .map_err(Error::Sqlx)
            }
            TxInner::Sqlite(tx) => {
                let mut q = sqlx::query::<Sqlite>(sql);
                for b in binds {
                    q = q.bind(b);
                }
                q.fetch_all(&mut **tx)
                    .await
                    .map(RowBatch::Sqlite)
                    .map_err(Error::Sqlx)
            }
            TxInner::Mysql(tx) => {
                let mut q = sqlx::query::<MySql>(sql);
                for b in binds {
                    q = q.bind(b);
                }
                q.fetch_all(&mut **tx)
                    .await
                    .map(RowBatch::Mysql)
                    .map_err(Error::Sqlx)
            }
            #[cfg(feature = "sqlite-rusqlite")]
            TxInner::SqliteNative(tx) => tx.fetch_all_sync(sql, binds),
            #[cfg(feature = "postgres-tokio-postgres")]
            TxInner::PostgresNative(tx) => tx.fetch_all(sql, binds).await,
        }
    }
}

/// A savepoint inside an open [`Tx`].
///
/// Savepoints can be nested to arbitrary depth. Dropping a `Savepoint` without
/// calling [`release`](Self::release) or [`rollback`](Self::rollback) is an
/// explicit rollback, matching the drop semantics of [`Tx`].
pub struct Savepoint<'tx> {
    tx: &'tx Tx,
    name: String,
    finished: AtomicBool,
}

impl<'tx> fmt::Debug for Savepoint<'tx> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Savepoint")
            .field("name", &self.name)
            .field("finished", &self.finished.load(Ordering::Relaxed))
            .finish()
    }
}

impl<'tx> Savepoint<'tx> {
    fn new(tx: &'tx Tx, name: String) -> Self {
        Self {
            tx,
            name,
            finished: AtomicBool::new(false),
        }
    }

    /// The dialect for the backend this savepoint runs on.
    #[must_use]
    pub fn dialect(&self) -> &dyn DbDialect {
        self.tx.dialect()
    }

    /// Create a nested savepoint inside this one.
    ///
    /// # Errors
    ///
    /// Returns the same errors as [`Tx::savepoint`].
    pub async fn savepoint(&self) -> Result<Savepoint<'_>, Error> {
        self.tx.savepoint().await
    }

    /// Release this savepoint, making its changes part of the outer transaction.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Message`] if the savepoint has already finished, or a
    /// driver error if `RELEASE SAVEPOINT` fails.
    pub async fn release(self) -> Result<(), Error> {
        self.finished.store(true, Ordering::Release);
        self.tx
            .execute(&format!("RELEASE SAVEPOINT {}", self.name), &[])
            .await?;
        Ok(())
    }

    /// Roll back to this savepoint, undoing all changes made since it was
    /// created (including changes in any nested savepoints).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Message`] if the savepoint has already finished, or a
    /// driver error if `ROLLBACK TO SAVEPOINT` fails.
    pub async fn rollback(self) -> Result<(), Error> {
        self.finished.store(true, Ordering::Release);
        self.tx
            .execute(&format!("ROLLBACK TO SAVEPOINT {}", self.name), &[])
            .await?;
        Ok(())
    }
}

impl<'tx> Drop for Savepoint<'tx> {
    fn drop(&mut self) {
        if self.finished.swap(true, Ordering::Acquire) {
            return;
        }

        tracing::warn!(
            target: "ruprizzle::query",
            savepoint = %self.name,
            "savepoint dropped without commit or rollback; rolling back"
        );

        let mut guard = self
            .tx
            .pending_rollback
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        guard.push(self.name.clone());
    }
}

impl crate::executor::Executor for Tx {
    fn dialect(&self) -> &dyn DbDialect {
        Self::dialect(self)
    }

    fn full_table_include_limit(&self) -> u64 {
        self.full_table_include_limit
    }

    #[cfg(feature = "sqlite-rusqlite")]
    fn as_rusqlite(&self) -> Option<&crate::rusqlite::RusqlitePool> {
        None
    }

    fn fetch_all_raw(
        &self,
        sql: Cow<'static, str>,
        binds: Vec<Value>,
    ) -> BoxFuture<'_, Result<RowBatch, Error>> {
        let bind_count = binds.len();
        Box::pin(crate::executor::trace_and_record_query(
            sql.clone(),
            bind_count,
            async move { self.fetch_all_rows(sql.as_ref(), &binds).await },
        ))
    }

    fn execute_raw(
        &self,
        sql: Cow<'static, str>,
        binds: Vec<Value>,
    ) -> BoxFuture<'_, Result<u64, Error>> {
        let bind_count = binds.len();
        Box::pin(crate::executor::trace_and_record_execute(
            sql.clone(),
            bind_count,
            async move { self.execute(sql.as_ref(), &binds).await },
        ))
    }

    /// Buffers rather than streaming incrementally.
    ///
    /// A transaction owns a single connection behind a mutex. Holding a cursor
    /// open across awaits would keep that mutex locked and deadlock every other
    /// statement issued on the same transaction, so the rows are fetched up
    /// front. Streaming a very large result set is therefore something to do on
    /// the pool, not inside a transaction.
    fn stream_raw(
        &self,
        sql: Cow<'static, str>,
        binds: Vec<Value>,
    ) -> crate::executor::BoxRowStream<'_> {
        Box::pin(crate::executor::DeferredRowStream::new(Box::pin(
            async move { crate::executor::Executor::fetch_all_raw(self, sql, binds).await },
        )))
    }
}

impl<'tx> crate::executor::Executor for Savepoint<'tx> {
    fn dialect(&self) -> &dyn DbDialect {
        self.tx.dialect()
    }

    fn full_table_include_limit(&self) -> u64 {
        self.tx.full_table_include_limit()
    }

    #[cfg(feature = "sqlite-rusqlite")]
    fn as_rusqlite(&self) -> Option<&crate::rusqlite::RusqlitePool> {
        None
    }

    fn fetch_all_raw(
        &self,
        sql: Cow<'static, str>,
        binds: Vec<Value>,
    ) -> BoxFuture<'_, Result<RowBatch, Error>> {
        self.tx.fetch_all_raw(sql, binds)
    }

    fn execute_raw(
        &self,
        sql: Cow<'static, str>,
        binds: Vec<Value>,
    ) -> BoxFuture<'_, Result<u64, Error>> {
        self.tx.execute_raw(sql, binds)
    }

    fn stream_raw(
        &self,
        sql: Cow<'static, str>,
        binds: Vec<Value>,
    ) -> crate::executor::BoxRowStream<'_> {
        self.tx.stream_raw(sql, binds)
    }
}

/// Whether an error is a transient serialization/lock failure worth retrying.
///
/// Postgres reports serialization failures as `40001` and deadlocks as `40P01`;
/// SQLite reports contention as `SQLITE_BUSY` / `SQLITE_LOCKED`. Anything else
/// is a real error and must not be retried, because retrying a genuine
/// constraint violation just multiplies the work before failing anyway.
#[must_use]
pub fn is_retryable(err: &Error) -> bool {
    let (code, message) = match err {
        Error::Sqlx(e) => {
            let Some(db) = e.as_database_error() else {
                return false;
            };
            (
                db.code().map(|c| c.to_string()),
                Some(db.message().to_string()),
            )
        }
        #[cfg(feature = "postgres-tokio-postgres")]
        Error::TokioPostgres(e) => {
            let Some(db) = e.as_db_error() else {
                return false;
            };
            (
                Some(db.code().code().to_owned()),
                Some(db.message().to_owned()),
            )
        }
        _ => return false,
    };

    match code.as_deref() {
        Some("40001" | "40P01") => true,
        _ => {
            let m = message.unwrap_or_default().to_ascii_lowercase();
            m.contains("database is locked") || m.contains("database table is locked")
        }
    }
}

/// Whether `sql` is a savepoint control statement (`SAVEPOINT`,
/// `RELEASE SAVEPOINT`, `ROLLBACK TO SAVEPOINT`).
fn is_savepoint_command(sql: &str) -> bool {
    let upper = sql.trim_start().to_ascii_uppercase();
    upper.starts_with("SAVEPOINT ")
        || upper.starts_with("RELEASE SAVEPOINT ")
        || upper.starts_with("ROLLBACK TO SAVEPOINT ")
}

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

    #[test]
    fn savepoint_commands_are_recognised() {
        assert!(is_savepoint_command("SAVEPOINT sp_1"));
        assert!(is_savepoint_command("  release savepoint sp_1"));
        assert!(is_savepoint_command("ROLLBACK TO SAVEPOINT sp_2"));
    }

    #[test]
    fn other_statements_keep_the_prepared_path() {
        assert!(!is_savepoint_command("ROLLBACK"));
        assert!(!is_savepoint_command(
            "INSERT INTO savepoints (id) VALUES (1)"
        ));
        assert!(!is_savepoint_command("SELECT 'SAVEPOINT x'"));
    }
}