prax-query 0.9.7

Type-safe query builder for the Prax ORM
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
#![allow(dead_code)]

//! Transaction support with async closures and savepoints.
//!
//! Set `PRAX_DEBUG=true` to enable transaction debug logging.
//!
//! This module provides a type-safe transaction API that:
//! - Automatically commits on success
//! - Automatically rolls back on error or panic
//! - Supports savepoints for nested transactions
//! - Configurable isolation levels
//!
//! # Isolation Levels
//!
//! ```rust
//! use prax_query::IsolationLevel;
//!
//! // Available isolation levels
//! let level = IsolationLevel::ReadUncommitted;
//! let level = IsolationLevel::ReadCommitted;  // Default
//! let level = IsolationLevel::RepeatableRead;
//! let level = IsolationLevel::Serializable;
//!
//! // Get SQL representation
//! assert_eq!(IsolationLevel::Serializable.as_sql(), "SERIALIZABLE");
//! assert_eq!(IsolationLevel::ReadCommitted.as_sql(), "READ COMMITTED");
//! ```
//!
//! # Transaction Configuration
//!
//! ```rust
//! use prax_query::{TransactionConfig, IsolationLevel};
//!
//! // Default configuration
//! let config = TransactionConfig::new();
//! assert_eq!(config.isolation, IsolationLevel::ReadCommitted);
//!
//! // Custom configuration
//! let config = TransactionConfig::new()
//!     .isolation(IsolationLevel::Serializable);
//!
//! // Access isolation as a public field
//! assert_eq!(config.isolation, IsolationLevel::Serializable);
//! ```
//!
//! # Transaction Usage (requires async runtime)
//!
//! ```rust,ignore
//! // Basic transaction - commits on success, rolls back on error
//! let result = client
//!     .transaction(|tx| async move {
//!         let user = tx.user().create(/* ... */).exec().await?;
//!         tx.post().create(/* ... */).exec().await?;
//!         Ok(user)
//!     })
//!     .await?;
//!
//! // With configuration
//! let result = client
//!     .transaction(|tx| async move {
//!         // ... perform operations
//!         Ok(())
//!     })
//!     .with_config(TransactionConfig::new()
//!         .isolation(IsolationLevel::Serializable)
//!         .timeout(Duration::from_secs(30)))
//!     .await?;
//!
//! // With savepoints for partial rollback
//! let result = client
//!     .transaction(|tx| async move {
//!         tx.user().create(/* ... */).exec().await?;
//!
//!         // This can be rolled back independently
//!         let savepoint_result = tx.savepoint("sp1", |sp| async move {
//!             sp.post().create(/* ... */).exec().await?;
//!             Ok(())
//!         }).await;
//!
//!         // Even if savepoint fails, outer transaction continues
//!         if savepoint_result.is_err() {
//!             // Handle partial failure
//!         }
//!
//!         Ok(())
//!     })
//!     .await?;
//! ```

use std::future::Future;
use std::time::Duration;
use tracing::debug;

use crate::error::QueryResult;

/// Transaction isolation levels.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum IsolationLevel {
    /// Read uncommitted - allows dirty reads.
    ReadUncommitted,
    /// Read committed - prevents dirty reads.
    #[default]
    ReadCommitted,
    /// Repeatable read - prevents non-repeatable reads.
    RepeatableRead,
    /// Serializable - highest isolation level.
    Serializable,
}

impl IsolationLevel {
    /// Get the SQL clause for this isolation level.
    pub fn as_sql(&self) -> &'static str {
        match self {
            Self::ReadUncommitted => "READ UNCOMMITTED",
            Self::ReadCommitted => "READ COMMITTED",
            Self::RepeatableRead => "REPEATABLE READ",
            Self::Serializable => "SERIALIZABLE",
        }
    }
}

/// Access mode for transactions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum AccessMode {
    /// Read-write access (default).
    #[default]
    ReadWrite,
    /// Read-only access.
    ReadOnly,
}

impl AccessMode {
    /// Get the SQL clause for this access mode.
    pub fn as_sql(&self) -> &'static str {
        match self {
            Self::ReadWrite => "READ WRITE",
            Self::ReadOnly => "READ ONLY",
        }
    }
}

/// Configuration for a transaction.
#[derive(Debug, Clone, Default)]
pub struct TransactionConfig {
    /// Isolation level.
    pub isolation: IsolationLevel,
    /// Access mode.
    pub access_mode: AccessMode,
    /// Timeout for the transaction.
    pub timeout: Option<Duration>,
    /// Whether to defer constraint checking.
    pub deferrable: bool,
}

impl TransactionConfig {
    /// Create a new transaction config with defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the isolation level.
    pub fn isolation(mut self, level: IsolationLevel) -> Self {
        self.isolation = level;
        self
    }

    /// Set the access mode.
    pub fn access_mode(mut self, mode: AccessMode) -> Self {
        self.access_mode = mode;
        self
    }

    /// Set the timeout.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Make the transaction read-only.
    pub fn read_only(self) -> Self {
        self.access_mode(AccessMode::ReadOnly)
    }

    /// Make the transaction deferrable.
    pub fn deferrable(mut self) -> Self {
        self.deferrable = true;
        self
    }

    /// Generate the BEGIN TRANSACTION SQL.
    pub fn to_begin_sql(&self) -> String {
        let mut parts = vec!["BEGIN"];

        // Isolation level
        parts.push("ISOLATION LEVEL");
        parts.push(self.isolation.as_sql());

        // Access mode
        parts.push(self.access_mode.as_sql());

        // Deferrable (PostgreSQL specific, only valid for SERIALIZABLE READ ONLY)
        if self.deferrable
            && self.isolation == IsolationLevel::Serializable
            && self.access_mode == AccessMode::ReadOnly
        {
            parts.push("DEFERRABLE");
        }

        let sql = parts.join(" ");
        debug!(isolation = %self.isolation.as_sql(), access_mode = %self.access_mode.as_sql(), "Transaction BEGIN");
        sql
    }
}

/// A transaction handle that provides query operations.
///
/// The transaction will be committed when dropped if no error occurred,
/// or rolled back if an error occurred or panic happened.
pub struct Transaction<E> {
    engine: E,
    config: TransactionConfig,
    committed: bool,
    savepoint_count: u32,
}

impl<E> Transaction<E> {
    /// Create a new transaction handle.
    pub fn new(engine: E, config: TransactionConfig) -> Self {
        Self {
            engine,
            config,
            committed: false,
            savepoint_count: 0,
        }
    }

    /// Get the transaction configuration.
    pub fn config(&self) -> &TransactionConfig {
        &self.config
    }

    /// Get the underlying engine.
    pub fn engine(&self) -> &E {
        &self.engine
    }

    /// Create a savepoint.
    pub fn savepoint_name(&mut self) -> String {
        self.savepoint_count += 1;
        format!("sp_{}", self.savepoint_count)
    }

    /// Mark the transaction as committed.
    pub fn mark_committed(&mut self) {
        self.committed = true;
    }

    /// Check if the transaction has been committed.
    pub fn is_committed(&self) -> bool {
        self.committed
    }
}

/// Builder for executing a transaction with a closure.
pub struct TransactionBuilder<E, F, Fut, T>
where
    F: FnOnce(Transaction<E>) -> Fut,
    Fut: Future<Output = QueryResult<T>>,
{
    engine: E,
    callback: F,
    config: TransactionConfig,
}

impl<E, F, Fut, T> TransactionBuilder<E, F, Fut, T>
where
    F: FnOnce(Transaction<E>) -> Fut,
    Fut: Future<Output = QueryResult<T>>,
{
    /// Create a new transaction builder.
    pub fn new(engine: E, callback: F) -> Self {
        Self {
            engine,
            callback,
            config: TransactionConfig::default(),
        }
    }

    /// Set the isolation level.
    pub fn isolation(mut self, level: IsolationLevel) -> Self {
        self.config.isolation = level;
        self
    }

    /// Set read-only mode.
    pub fn read_only(mut self) -> Self {
        self.config.access_mode = AccessMode::ReadOnly;
        self
    }

    /// Set the timeout.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.config.timeout = Some(timeout);
        self
    }

    /// Set deferrable mode.
    pub fn deferrable(mut self) -> Self {
        self.config.deferrable = true;
        self
    }
}

/// Interactive transaction for step-by-step operations.
pub struct InteractiveTransaction<E> {
    inner: Transaction<E>,
    started: bool,
}

impl<E> InteractiveTransaction<E> {
    /// Create a new interactive transaction.
    pub fn new(engine: E) -> Self {
        Self {
            inner: Transaction::new(engine, TransactionConfig::default()),
            started: false,
        }
    }

    /// Create with configuration.
    pub fn with_config(engine: E, config: TransactionConfig) -> Self {
        Self {
            inner: Transaction::new(engine, config),
            started: false,
        }
    }

    /// Get the engine.
    pub fn engine(&self) -> &E {
        &self.inner.engine
    }

    /// Check if the transaction has started.
    pub fn is_started(&self) -> bool {
        self.started
    }

    /// Get the BEGIN SQL.
    pub fn begin_sql(&self) -> String {
        self.inner.config.to_begin_sql()
    }

    /// Get the COMMIT SQL.
    pub fn commit_sql(&self) -> &'static str {
        "COMMIT"
    }

    /// Get the ROLLBACK SQL.
    pub fn rollback_sql(&self) -> &'static str {
        "ROLLBACK"
    }

    /// Get the SAVEPOINT SQL.
    pub fn savepoint_sql(&mut self, name: Option<&str>) -> String {
        let name = name
            .map(|s| s.to_string())
            .unwrap_or_else(|| self.inner.savepoint_name());
        format!("SAVEPOINT {}", name)
    }

    /// Get the ROLLBACK TO SAVEPOINT SQL.
    pub fn rollback_to_sql(&self, name: &str) -> String {
        format!("ROLLBACK TO SAVEPOINT {}", name)
    }

    /// Get the RELEASE SAVEPOINT SQL.
    pub fn release_savepoint_sql(&self, name: &str) -> String {
        format!("RELEASE SAVEPOINT {}", name)
    }

    /// Mark as started.
    pub fn mark_started(&mut self) {
        self.started = true;
    }
}

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

    #[test]
    fn test_isolation_level() {
        assert_eq!(IsolationLevel::ReadCommitted.as_sql(), "READ COMMITTED");
        assert_eq!(IsolationLevel::Serializable.as_sql(), "SERIALIZABLE");
    }

    #[test]
    fn test_access_mode() {
        assert_eq!(AccessMode::ReadWrite.as_sql(), "READ WRITE");
        assert_eq!(AccessMode::ReadOnly.as_sql(), "READ ONLY");
    }

    #[test]
    fn test_transaction_config_default() {
        let config = TransactionConfig::new();
        assert_eq!(config.isolation, IsolationLevel::ReadCommitted);
        assert_eq!(config.access_mode, AccessMode::ReadWrite);
        assert!(config.timeout.is_none());
        assert!(!config.deferrable);
    }

    #[test]
    fn test_transaction_config_builder() {
        let config = TransactionConfig::new()
            .isolation(IsolationLevel::Serializable)
            .read_only()
            .deferrable()
            .timeout(Duration::from_secs(30));

        assert_eq!(config.isolation, IsolationLevel::Serializable);
        assert_eq!(config.access_mode, AccessMode::ReadOnly);
        assert!(config.deferrable);
        assert_eq!(config.timeout, Some(Duration::from_secs(30)));
    }

    #[test]
    fn test_begin_sql() {
        let config = TransactionConfig::new();
        let sql = config.to_begin_sql();
        assert!(sql.contains("BEGIN"));
        assert!(sql.contains("ISOLATION LEVEL READ COMMITTED"));
        assert!(sql.contains("READ WRITE"));
    }

    #[test]
    fn test_begin_sql_serializable_deferrable() {
        let config = TransactionConfig::new()
            .isolation(IsolationLevel::Serializable)
            .read_only()
            .deferrable();
        let sql = config.to_begin_sql();
        assert!(sql.contains("SERIALIZABLE"));
        assert!(sql.contains("READ ONLY"));
        assert!(sql.contains("DEFERRABLE"));
    }

    #[test]
    fn test_interactive_transaction() {
        #[derive(Clone)]
        struct MockEngine;

        let mut tx = InteractiveTransaction::new(MockEngine);
        assert!(!tx.is_started());

        let begin = tx.begin_sql();
        assert!(begin.contains("BEGIN"));

        let sp = tx.savepoint_sql(Some("test_sp"));
        assert_eq!(sp, "SAVEPOINT test_sp");

        let rollback_to = tx.rollback_to_sql("test_sp");
        assert_eq!(rollback_to, "ROLLBACK TO SAVEPOINT test_sp");

        let release = tx.release_savepoint_sql("test_sp");
        assert_eq!(release, "RELEASE SAVEPOINT test_sp");
    }
}