nautilus-orm-connector 0.1.7

Database executors and connection management for Nautilus 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
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
//! Transaction executor for Nautilus.
//!
//! This module provides [`TransactionExecutor`], a single type that wraps a
//! live database transaction for any of the three supported backends
//! (PostgreSQL, MySQL, SQLite).  It replaces the previous per-backend trio
//! `TxPgExecutor` / `TxMysqlExecutor` / `TxSqliteExecutor`, which had
//! identical structure in three copies.
//!
//! ## Architecture note
//!
//! sqlx's `Transaction<'static, Db>` is parameterised by `Db`, making a true
//! Rust generic impossible without fighting GAT lifetime constraints (SQLite's
//! `SqliteArguments<'q>` carries a `'q` lifetime that PG/MySQL arguments do
//! not).  The type instead uses a private `TransactionInner` enum to hold
//! whichever backend's transaction is live, while presenting a uniform public
//! API to all callers.

use std::sync::Arc;
use std::time::Duration;

use tokio::sync::Mutex;

use nautilus_dialect::Sql;

use crate::error::{ConnectorError as Error, Result};
use crate::row_stream::RowStream;
use crate::{Executor, Row};

/// Options for starting a transaction.
#[derive(Debug, Clone)]
pub struct TransactionOptions {
    /// Maximum duration before the transaction is automatically rolled back.
    pub timeout: Duration,
    /// Optional isolation level override.
    pub isolation_level: Option<IsolationLevel>,
}

impl Default for TransactionOptions {
    fn default() -> Self {
        Self {
            timeout: Duration::from_secs(5),
            isolation_level: None,
        }
    }
}

/// Transaction isolation level.
///
/// Re-exported from `nautilus-protocol` for convenience; the connector uses
/// the same enum so callers don't need to depend on the protocol crate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IsolationLevel {
    /// Read uncommitted — allows dirty reads.
    ReadUncommitted,
    /// Read committed — default for most databases.
    ReadCommitted,
    /// Repeatable read — prevents non-repeatable reads.
    RepeatableRead,
    /// Serializable — strictest isolation level.
    Serializable,
}

impl IsolationLevel {
    /// Returns the SQL representation (e.g., `"READ COMMITTED"`).
    pub fn as_sql(&self) -> &'static str {
        match self {
            IsolationLevel::ReadUncommitted => "READ UNCOMMITTED",
            IsolationLevel::ReadCommitted => "READ COMMITTED",
            IsolationLevel::RepeatableRead => "REPEATABLE READ",
            IsolationLevel::Serializable => "SERIALIZABLE",
        }
    }
}

/// Per-backend transaction storage.
///
/// This is a private implementation detail — callers always interact with the
/// outer [`TransactionExecutor`] type.
enum TransactionInner {
    Postgres(Arc<Mutex<Option<sqlx::Transaction<'static, sqlx::Postgres>>>>),
    Mysql(Arc<Mutex<Option<sqlx::Transaction<'static, sqlx::MySql>>>>),
    Sqlite(Arc<Mutex<Option<sqlx::Transaction<'static, sqlx::Sqlite>>>>),
}

/// An executor that runs queries inside a live database transaction.
///
/// This single type works with PostgreSQL, MySQL, and SQLite, replacing the
/// previous per-backend `TxPgExecutor` / `TxMysqlExecutor` / `TxSqliteExecutor`
/// trio.  Internally it holds a [`TransactionInner`] enum; callers see one
/// consistent API regardless of the backend in use.
///
/// The underlying sqlx transaction is stored behind an
/// `Arc<Mutex<Option<…>>>` so the executor can be shared cheaply through
/// [`crate::client::Client`]'s `Arc<E>` wrapping.
///
/// # Example
///
/// ```no_run
/// # use nautilus_connector::{Client, ConnectorResult};
/// # async fn example() -> ConnectorResult<()> {
/// let client = Client::postgres("postgres://localhost/mydb").await?;
/// let result = client.transaction(Default::default(), |tx| Box::pin(async move {
///     // tx is Client<TransactionExecutor>; all queries run inside the transaction.
///     Ok(42i64)
/// })).await?;
/// # Ok(())
/// # }
/// ```
pub struct TransactionExecutor {
    inner: TransactionInner,
}

impl TransactionExecutor {
    /// Wrap an already-begun PostgreSQL transaction.
    pub fn postgres(tx: sqlx::Transaction<'static, sqlx::Postgres>) -> Self {
        Self {
            inner: TransactionInner::Postgres(Arc::new(Mutex::new(Some(tx)))),
        }
    }

    /// Wrap an already-begun MySQL transaction.
    pub fn mysql(tx: sqlx::Transaction<'static, sqlx::MySql>) -> Self {
        Self {
            inner: TransactionInner::Mysql(Arc::new(Mutex::new(Some(tx)))),
        }
    }

    /// Wrap an already-begun SQLite transaction.
    pub fn sqlite(tx: sqlx::Transaction<'static, sqlx::Sqlite>) -> Self {
        Self {
            inner: TransactionInner::Sqlite(Arc::new(Mutex::new(Some(tx)))),
        }
    }

    /// Commit the transaction. After this, further queries will return an error.
    pub async fn commit(&self) -> Result<()> {
        match &self.inner {
            TransactionInner::Postgres(mx) => {
                let tx = mx
                    .lock()
                    .await
                    .take()
                    .ok_or_else(|| Error::database_msg("Transaction already closed"))?;
                tx.commit()
                    .await
                    .map_err(|e| Error::database(e, "Commit failed"))
            }
            TransactionInner::Mysql(mx) => {
                let tx = mx
                    .lock()
                    .await
                    .take()
                    .ok_or_else(|| Error::database_msg("Transaction already closed"))?;
                tx.commit()
                    .await
                    .map_err(|e| Error::database(e, "Commit failed"))
            }
            TransactionInner::Sqlite(mx) => {
                let tx = mx
                    .lock()
                    .await
                    .take()
                    .ok_or_else(|| Error::database_msg("Transaction already closed"))?;
                tx.commit()
                    .await
                    .map_err(|e| Error::database(e, "Commit failed"))
            }
        }
    }

    /// Rollback the transaction. After this, further queries will return an error.
    pub async fn rollback(&self) -> Result<()> {
        match &self.inner {
            TransactionInner::Postgres(mx) => {
                let tx = mx
                    .lock()
                    .await
                    .take()
                    .ok_or_else(|| Error::database_msg("Transaction already closed"))?;
                tx.rollback()
                    .await
                    .map_err(|e| Error::database(e, "Rollback failed"))
            }
            TransactionInner::Mysql(mx) => {
                let tx = mx
                    .lock()
                    .await
                    .take()
                    .ok_or_else(|| Error::database_msg("Transaction already closed"))?;
                tx.rollback()
                    .await
                    .map_err(|e| Error::database(e, "Rollback failed"))
            }
            TransactionInner::Sqlite(mx) => {
                let tx = mx
                    .lock()
                    .await
                    .take()
                    .ok_or_else(|| Error::database_msg("Transaction already closed"))?;
                tx.rollback()
                    .await
                    .map_err(|e| Error::database(e, "Rollback failed"))
            }
        }
    }

    /// Returns `true` if the transaction has not yet been committed or rolled back.
    pub async fn is_open(&self) -> bool {
        match &self.inner {
            TransactionInner::Postgres(mx) => mx.lock().await.is_some(),
            TransactionInner::Mysql(mx) => mx.lock().await.is_some(),
            TransactionInner::Sqlite(mx) => mx.lock().await.is_some(),
        }
    }

    /// Execute a mutation SQL inside this transaction and return the number of
    /// affected rows.
    ///
    /// Used when `return_data = false` so no RETURNING clause is emitted and
    /// the affected-row count comes from the database execution result.
    pub async fn execute_affected(&self, sql: &Sql) -> Result<usize> {
        match &self.inner {
            TransactionInner::Postgres(tx_arc) => {
                let mut guard = tx_arc.lock().await;
                let tx = guard
                    .as_mut()
                    .ok_or_else(|| Error::database_msg("Transaction already closed"))?;
                let mut query = sqlx::query(&sql.text);
                for param in &sql.params {
                    query = crate::postgres::bind_value(query, param)?;
                }
                use sqlx::Executor as _;
                let result = (&mut **tx)
                    .execute(query)
                    .await
                    .map_err(|e| Error::database(e, "Mutation failed"))?;
                Ok(result.rows_affected() as usize)
            }
            TransactionInner::Mysql(tx_arc) => {
                let mut guard = tx_arc.lock().await;
                let tx = guard
                    .as_mut()
                    .ok_or_else(|| Error::database_msg("Transaction already closed"))?;
                let mut query = sqlx::query(&sql.text);
                for param in &sql.params {
                    query = crate::mysql::bind_value(query, param)?;
                }
                use sqlx::Executor as _;
                let result = (&mut **tx)
                    .execute(query)
                    .await
                    .map_err(|e| Error::database(e, "Mutation failed"))?;
                Ok(result.rows_affected() as usize)
            }
            TransactionInner::Sqlite(tx_arc) => {
                let mut guard = tx_arc.lock().await;
                let tx = guard
                    .as_mut()
                    .ok_or_else(|| Error::database_msg("Transaction already closed"))?;
                let mut query = sqlx::query(&sql.text);
                for param in &sql.params {
                    query = crate::sqlite::bind_value(query, param)?;
                }
                use sqlx::Executor as _;
                let result = (&mut **tx)
                    .execute(query)
                    .await
                    .map_err(|e| Error::database(e, "Mutation failed"))?;
                Ok(result.rows_affected() as usize)
            }
        }
    }
}

impl Executor for TransactionExecutor {
    type Row<'conn>
        = Row
    where
        Self: 'conn;
    type RowStream<'conn>
        = RowStream
    where
        Self: 'conn;

    fn execute<'conn>(&'conn self, sql: &'conn Sql) -> Self::RowStream<'conn> {
        let sql_text = sql.text.clone();
        let params = sql.params.clone();

        match &self.inner {
            TransactionInner::Postgres(tx_arc) => {
                let tx_arc = Arc::clone(tx_arc);
                let stream = async_stream::stream! {
                    let mut guard = tx_arc.lock().await;
                    let tx = match guard.as_mut() {
                        Some(tx) => tx,
                        None => { yield Err(Error::database_msg("Transaction already closed")); return; }
                    };
                    let mut query = sqlx::query(&sql_text);
                    for param in &params {
                        query = match crate::postgres::bind_value(query, param) {
                            Ok(q) => q,
                            Err(e) => { yield Err(e); return; }
                        };
                    }
                    use sqlx::Executor as _;
                    let rows = match (&mut **tx).fetch_all(query).await {
                        Ok(rows) => rows,
                        Err(e) => { yield Err(Error::database(e, "Query failed")); return; }
                    };
                    drop(guard);
                    for row in rows {
                        match crate::postgres_stream::decode_row_internal(row) {
                            Ok(r) => yield Ok(r),
                            Err(e) => yield Err(e),
                        }
                    }
                };
                RowStream::new_from_stream(Box::pin(stream))
            }
            TransactionInner::Mysql(tx_arc) => {
                let tx_arc = Arc::clone(tx_arc);
                let stream = async_stream::stream! {
                    let mut guard = tx_arc.lock().await;
                    let tx = match guard.as_mut() {
                        Some(tx) => tx,
                        None => { yield Err(Error::database_msg("Transaction already closed")); return; }
                    };
                    let mut query = sqlx::query(&sql_text);
                    for param in &params {
                        query = match crate::mysql::bind_value(query, param) {
                            Ok(q) => q,
                            Err(e) => { yield Err(e); return; }
                        };
                    }
                    use sqlx::Executor as _;
                    let rows = match (&mut **tx).fetch_all(query).await {
                        Ok(rows) => rows,
                        Err(e) => { yield Err(Error::database(e, "Query failed")); return; }
                    };
                    drop(guard);
                    for row in rows {
                        match crate::mysql_stream::decode_row_internal(row) {
                            Ok(r) => yield Ok(r),
                            Err(e) => yield Err(e),
                        }
                    }
                };
                RowStream::new_from_stream(Box::pin(stream))
            }
            TransactionInner::Sqlite(tx_arc) => {
                let tx_arc = Arc::clone(tx_arc);
                let stream = async_stream::stream! {
                    let mut guard = tx_arc.lock().await;
                    let tx = match guard.as_mut() {
                        Some(tx) => tx,
                        None => { yield Err(Error::database_msg("Transaction already closed")); return; }
                    };
                    let mut query = sqlx::query(&sql_text);
                    for param in &params {
                        query = match crate::sqlite::bind_value(query, param) {
                            Ok(q) => q,
                            Err(e) => { yield Err(e); return; }
                        };
                    }
                    use sqlx::Executor as _;
                    let rows = match (&mut **tx).fetch_all(query).await {
                        Ok(rows) => rows,
                        Err(e) => { yield Err(Error::database(e, "Query failed")); return; }
                    };
                    drop(guard);
                    for row in rows {
                        match crate::sqlite_stream::decode_row_internal(row) {
                            Ok(r) => yield Ok(r),
                            Err(e) => yield Err(e),
                        }
                    }
                };
                RowStream::new_from_stream(Box::pin(stream))
            }
        }
    }

    fn execute_and_fetch<'conn>(
        &'conn self,
        mutation: &'conn Sql,
        fetch: &'conn Sql,
    ) -> Self::RowStream<'conn> {
        let mutation_text = mutation.text.clone();
        let mutation_params = mutation.params.clone();
        let fetch_text = fetch.text.clone();
        let fetch_params = fetch.params.clone();

        match &self.inner {
            TransactionInner::Postgres(tx_arc) => {
                let tx_arc = Arc::clone(tx_arc);
                let stream = async_stream::stream! {
                    let mut guard = tx_arc.lock().await;
                    let tx = match guard.as_mut() {
                        Some(tx) => tx,
                        None => { yield Err(Error::database_msg("Transaction already closed")); return; }
                    };
                    let mut mq = sqlx::query(&mutation_text);
                    for param in &mutation_params {
                        mq = match crate::postgres::bind_value(mq, param) {
                            Ok(q) => q,
                            Err(e) => { yield Err(e); return; }
                        };
                    }
                    use sqlx::Executor as _;
                    if let Err(e) = (&mut **tx).execute(mq).await {
                        yield Err(Error::database(e, "Mutation failed")); return;
                    }
                    let mut fq = sqlx::query(&fetch_text);
                    for param in &fetch_params {
                        fq = match crate::postgres::bind_value(fq, param) {
                            Ok(q) => q,
                            Err(e) => { yield Err(e); return; }
                        };
                    }
                    let rows = match (&mut **tx).fetch_all(fq).await {
                        Ok(rows) => rows,
                        Err(e) => { yield Err(Error::database(e, "Fetch failed")); return; }
                    };
                    drop(guard);
                    for row in rows {
                        match crate::postgres_stream::decode_row_internal(row) {
                            Ok(r) => yield Ok(r),
                            Err(e) => yield Err(e),
                        }
                    }
                };
                RowStream::new_from_stream(Box::pin(stream))
            }
            TransactionInner::Mysql(tx_arc) => {
                let tx_arc = Arc::clone(tx_arc);
                let stream = async_stream::stream! {
                    let mut guard = tx_arc.lock().await;
                    let tx = match guard.as_mut() {
                        Some(tx) => tx,
                        None => { yield Err(Error::database_msg("Transaction already closed")); return; }
                    };
                    let mut mq = sqlx::query(&mutation_text);
                    for param in &mutation_params {
                        mq = match crate::mysql::bind_value(mq, param) {
                            Ok(q) => q,
                            Err(e) => { yield Err(e); return; }
                        };
                    }
                    use sqlx::Executor as _;
                    if let Err(e) = (&mut **tx).execute(mq).await {
                        yield Err(Error::database(e, "Mutation failed")); return;
                    }
                    let mut fq = sqlx::query(&fetch_text);
                    for param in &fetch_params {
                        fq = match crate::mysql::bind_value(fq, param) {
                            Ok(q) => q,
                            Err(e) => { yield Err(e); return; }
                        };
                    }
                    let rows = match (&mut **tx).fetch_all(fq).await {
                        Ok(rows) => rows,
                        Err(e) => { yield Err(Error::database(e, "Fetch failed")); return; }
                    };
                    drop(guard);
                    for row in rows {
                        match crate::mysql_stream::decode_row_internal(row) {
                            Ok(r) => yield Ok(r),
                            Err(e) => yield Err(e),
                        }
                    }
                };
                RowStream::new_from_stream(Box::pin(stream))
            }
            TransactionInner::Sqlite(tx_arc) => {
                let tx_arc = Arc::clone(tx_arc);
                let stream = async_stream::stream! {
                    let mut guard = tx_arc.lock().await;
                    let tx = match guard.as_mut() {
                        Some(tx) => tx,
                        None => { yield Err(Error::database_msg("Transaction already closed")); return; }
                    };
                    let mut mq = sqlx::query(&mutation_text);
                    for param in &mutation_params {
                        mq = match crate::sqlite::bind_value(mq, param) {
                            Ok(q) => q,
                            Err(e) => { yield Err(e); return; }
                        };
                    }
                    use sqlx::Executor as _;
                    if let Err(e) = (&mut **tx).execute(mq).await {
                        yield Err(Error::database(e, "Mutation failed")); return;
                    }
                    let mut fq = sqlx::query(&fetch_text);
                    for param in &fetch_params {
                        fq = match crate::sqlite::bind_value(fq, param) {
                            Ok(q) => q,
                            Err(e) => { yield Err(e); return; }
                        };
                    }
                    let rows = match (&mut **tx).fetch_all(fq).await {
                        Ok(rows) => rows,
                        Err(e) => { yield Err(Error::database(e, "Fetch failed")); return; }
                    };
                    drop(guard);
                    for row in rows {
                        match crate::sqlite_stream::decode_row_internal(row) {
                            Ok(r) => yield Ok(r),
                            Err(e) => yield Err(e),
                        }
                    }
                };
                RowStream::new_from_stream(Box::pin(stream))
            }
        }
    }
}