entity-core 0.3.0

Core traits and types for entity-derive
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
// SPDX-FileCopyrightText: 2025-2026 RAprogramm <andrey.rozanov.vl@gmail.com>
// SPDX-License-Identifier: MIT

//! Transaction support for entity-derive.
//!
//! This module provides type-safe transaction management with automatic
//! commit/rollback semantics. It uses a fluent builder pattern for composing
//! multiple entity operations into a single transaction.
//!
//! # Overview
//!
//! - [`Transaction`] — Entry point for creating transactions
//! - [`TransactionContext`] — Holds active transaction, provides repo access
//! - [`TransactionError`] — Error wrapper for transaction operations
//!
//! # Example
//!
//! ```rust,ignore
//! use entity_derive::prelude::*;
//!
//! async fn transfer(pool: &PgPool, from: Uuid, to: Uuid, amount: i64) -> Result<(), AppError> {
//!     Transaction::new(pool)
//!         .with_accounts()
//!         .with_transfers()
//!         .run(|mut ctx| async move {
//!             let from_acc = ctx.accounts().find_by_id(from).await?.ok_or(AppError::NotFound)?;
//!
//!             ctx.accounts().update(from, UpdateAccount {
//!                 balance: Some(from_acc.balance - amount),
//!                 ..Default::default()
//!             }).await?;
//!
//!             ctx.transfers().create(CreateTransfer { from, to, amount }).await?;
//!             Ok(())
//!         })
//!         .await
//! }
//! ```

#[cfg(feature = "postgres")]
use std::future::Future;
use std::{error::Error as StdError, fmt};

/// Transaction builder for composing multi-entity operations.
///
/// Use [`Transaction::new`] to create a builder, chain `.with_*()` methods
/// to declare which entities you'll use, then call `.run()` to execute.
///
/// # Type Parameters
///
/// - `'p` — Pool lifetime
/// - `DB` — Database pool type (e.g., `PgPool`)
///
/// # Example
///
/// ```rust,ignore
/// Transaction::new(&pool)
///     .with_users()
///     .with_orders()
///     .run(|mut ctx| async move {
///         let user = ctx.users().find_by_id(id).await?;
///         ctx.orders().create(order).await?;
///         Ok(())
///     })
///     .await?;
/// ```
pub struct Transaction<'p, DB> {
    pool: &'p DB
}

impl<'p, DB> Transaction<'p, DB> {
    /// Create a new transaction builder.
    ///
    /// # Arguments
    ///
    /// * `pool` — Database connection pool
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let tx = Transaction::new(&pool);
    /// ```
    pub const fn new(pool: &'p DB) -> Self {
        Self {
            pool
        }
    }

    /// Get reference to the underlying pool.
    pub const fn pool(&self) -> &'p DB {
        self.pool
    }
}

/// Active transaction context with repository access.
///
/// This struct holds the database transaction and provides access to
/// entity repositories via extension traits generated by the macro.
///
/// # Automatic Rollback
///
/// If dropped without explicit commit, the transaction is automatically
/// rolled back via the underlying database transaction's Drop impl.
///
/// # Accessing Repositories
///
/// Each entity with `#[entity(transactions)]` generates an extension trait
/// that adds an accessor method:
///
/// ```rust,ignore
/// // For entity BankAccount, use:
/// ctx.bank_accounts().find_by_id(id).await?;
/// ctx.bank_accounts().create(dto).await?;
/// ctx.bank_accounts().update(id, dto).await?;
/// ```
#[cfg(feature = "postgres")]
pub struct TransactionContext {
    tx: sqlx::Transaction<'static, sqlx::Postgres>
}

#[cfg(feature = "postgres")]
impl TransactionContext {
    /// Create a new transaction context.
    ///
    /// # Arguments
    ///
    /// * `tx` — Active database transaction
    #[doc(hidden)]
    pub fn new(tx: sqlx::Transaction<'static, sqlx::Postgres>) -> Self {
        Self {
            tx
        }
    }

    /// Get mutable reference to the underlying transaction.
    ///
    /// Use this for custom queries within the transaction or
    /// for repository adapters to execute queries.
    pub fn transaction(&mut self) -> &mut sqlx::Transaction<'static, sqlx::Postgres> {
        &mut self.tx
    }

    /// Commit the transaction.
    ///
    /// Consumes self and commits all changes.
    pub async fn commit(self) -> Result<(), sqlx::Error> {
        self.tx.commit().await
    }

    /// Rollback the transaction.
    ///
    /// Consumes self and rolls back all changes.
    pub async fn rollback(self) -> Result<(), sqlx::Error> {
        self.tx.rollback().await
    }
}

/// Error type for transaction operations.
///
/// Wraps database errors and provides context about the transaction state.
#[derive(Debug)]
pub enum TransactionError<E> {
    /// Failed to begin transaction.
    Begin(E),

    /// Failed to commit transaction.
    Commit(E),

    /// Failed to rollback transaction.
    Rollback(E),

    /// Operation within transaction failed.
    Operation(E)
}

impl<E: fmt::Display> fmt::Display for TransactionError<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Begin(e) => write!(f, "failed to begin transaction: {e}"),
            Self::Commit(e) => write!(f, "failed to commit transaction: {e}"),
            Self::Rollback(e) => write!(f, "failed to rollback transaction: {e}"),
            Self::Operation(e) => write!(f, "transaction operation failed: {e}")
        }
    }
}

impl<E: StdError + 'static> StdError for TransactionError<E> {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            Self::Begin(e) | Self::Commit(e) | Self::Rollback(e) | Self::Operation(e) => Some(e)
        }
    }
}

impl<E> TransactionError<E> {
    /// Check if this is a begin error.
    pub const fn is_begin(&self) -> bool {
        matches!(self, Self::Begin(_))
    }

    /// Check if this is a commit error.
    pub const fn is_commit(&self) -> bool {
        matches!(self, Self::Commit(_))
    }

    /// Check if this is a rollback error.
    pub const fn is_rollback(&self) -> bool {
        matches!(self, Self::Rollback(_))
    }

    /// Check if this is an operation error.
    pub const fn is_operation(&self) -> bool {
        matches!(self, Self::Operation(_))
    }

    /// Get the inner error.
    pub fn into_inner(self) -> E {
        match self {
            Self::Begin(e) | Self::Commit(e) | Self::Rollback(e) | Self::Operation(e) => e
        }
    }
}

#[cfg(feature = "postgres")]
impl From<TransactionError<sqlx::Error>> for sqlx::Error {
    fn from(err: TransactionError<sqlx::Error>) -> Self {
        err.into_inner()
    }
}

// PostgreSQL implementation
#[cfg(feature = "postgres")]
impl<'p> Transaction<'p, sqlx::PgPool> {
    /// Execute a closure within a PostgreSQL transaction.
    ///
    /// Automatically commits on `Ok`, rolls back on `Err` or drop.
    ///
    /// # Type Parameters
    ///
    /// - `F` — Closure type
    /// - `Fut` — Future returned by closure
    /// - `T` — Success type
    /// - `E` — Error type (must be convertible from sqlx::Error)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// Transaction::new(&pool)
    ///     .with_users()
    ///     .run(|mut ctx| async move {
    ///         let user = ctx.users().create(dto).await?;
    ///         Ok(user)
    ///     })
    ///     .await?;
    /// ```
    pub async fn run<F, Fut, T, E>(self, f: F) -> Result<T, E>
    where
        F: FnOnce(TransactionContext) -> Fut + Send,
        Fut: Future<Output = Result<T, E>> + Send,
        E: From<sqlx::Error>
    {
        let tx = self.pool.begin().await.map_err(E::from)?;
        let ctx = TransactionContext::new(tx);

        match f(ctx).await {
            Ok(result) => Ok(result),
            Err(e) => Err(e)
        }
    }

    /// Execute a closure within a transaction with explicit commit.
    ///
    /// Unlike `run`, this method requires the closure to explicitly
    /// commit the transaction by calling `ctx.commit()`.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// Transaction::new(&pool)
    ///     .run_with_commit(|mut ctx| async move {
    ///         let user = ctx.users().create(dto).await?;
    ///         ctx.commit().await?;
    ///         Ok(user)
    ///     })
    ///     .await?;
    /// ```
    pub async fn run_with_commit<F, Fut, T, E>(self, f: F) -> Result<T, E>
    where
        F: FnOnce(TransactionContext) -> Fut + Send,
        Fut: Future<Output = Result<T, E>> + Send,
        E: From<sqlx::Error>
    {
        let tx = self.pool.begin().await.map_err(E::from)?;
        let ctx = TransactionContext::new(tx);
        f(ctx).await
    }
}

#[cfg(test)]
mod tests {
    use std::error::Error;

    use super::*;

    #[test]
    fn transaction_error_display_begin() {
        let err: TransactionError<std::io::Error> =
            TransactionError::Begin(std::io::Error::other("test"));
        assert!(err.to_string().contains("begin"));
        assert!(err.to_string().contains("test"));
    }

    #[test]
    fn transaction_error_display_commit() {
        let err: TransactionError<std::io::Error> =
            TransactionError::Commit(std::io::Error::other("test"));
        assert!(err.to_string().contains("commit"));
    }

    #[test]
    fn transaction_error_display_rollback() {
        let err: TransactionError<std::io::Error> =
            TransactionError::Rollback(std::io::Error::other("test"));
        assert!(err.to_string().contains("rollback"));
    }

    #[test]
    fn transaction_error_display_operation() {
        let err: TransactionError<std::io::Error> =
            TransactionError::Operation(std::io::Error::other("test"));
        assert!(err.to_string().contains("operation"));
    }

    #[test]
    fn transaction_error_is_methods() {
        let begin: TransactionError<&str> = TransactionError::Begin("e");
        let commit: TransactionError<&str> = TransactionError::Commit("e");
        let rollback: TransactionError<&str> = TransactionError::Rollback("e");
        let operation: TransactionError<&str> = TransactionError::Operation("e");

        assert!(begin.is_begin());
        assert!(!begin.is_commit());
        assert!(!begin.is_rollback());
        assert!(!begin.is_operation());

        assert!(!commit.is_begin());
        assert!(commit.is_commit());
        assert!(!commit.is_rollback());
        assert!(!commit.is_operation());

        assert!(!rollback.is_begin());
        assert!(!rollback.is_commit());
        assert!(rollback.is_rollback());
        assert!(!rollback.is_operation());

        assert!(!operation.is_begin());
        assert!(!operation.is_commit());
        assert!(!operation.is_rollback());
        assert!(operation.is_operation());
    }

    #[test]
    fn transaction_error_into_inner() {
        let err: TransactionError<&str> = TransactionError::Operation("test");
        assert_eq!(err.into_inner(), "test");
    }

    #[test]
    fn transaction_error_into_inner_begin() {
        let err: TransactionError<&str> = TransactionError::Begin("begin_err");
        assert_eq!(err.into_inner(), "begin_err");
    }

    #[test]
    fn transaction_error_into_inner_commit() {
        let err: TransactionError<&str> = TransactionError::Commit("commit_err");
        assert_eq!(err.into_inner(), "commit_err");
    }

    #[test]
    fn transaction_error_into_inner_rollback() {
        let err: TransactionError<&str> = TransactionError::Rollback("rollback_err");
        assert_eq!(err.into_inner(), "rollback_err");
    }

    #[test]
    fn transaction_error_source_begin() {
        let err: TransactionError<std::io::Error> =
            TransactionError::Begin(std::io::Error::other("src"));
        assert!(err.source().is_some());
    }

    #[test]
    fn transaction_error_source_commit() {
        let err: TransactionError<std::io::Error> =
            TransactionError::Commit(std::io::Error::other("src"));
        assert!(err.source().is_some());
    }

    #[test]
    fn transaction_error_source_rollback() {
        let err: TransactionError<std::io::Error> =
            TransactionError::Rollback(std::io::Error::other("src"));
        assert!(err.source().is_some());
    }

    #[test]
    fn transaction_error_source_operation() {
        let err: TransactionError<std::io::Error> =
            TransactionError::Operation(std::io::Error::other("src"));
        assert!(err.source().is_some());
    }

    #[test]
    fn transaction_builder_new() {
        struct MockPool;
        let pool = MockPool;
        let tx = Transaction::new(&pool);
        let _ = tx.pool();
    }

    #[test]
    fn transaction_builder_pool_accessor() {
        struct MockPool {
            id: u32
        }
        let pool = MockPool {
            id: 42
        };
        let tx = Transaction::new(&pool);
        assert_eq!(tx.pool().id, 42);
    }

    #[test]
    fn transaction_error_debug() {
        let err: TransactionError<&str> = TransactionError::Begin("test");
        let debug_str = format!("{:?}", err);
        assert!(debug_str.contains("Begin"));
        assert!(debug_str.contains("test"));
    }
}