| | | 1 | | // SPDX-FileCopyrightText: 2026 Alper Çelik <[email protected]> |
| | | 2 | | // |
| | | 3 | | // SPDX-License-Identifier: AGPL-3.0-or-later |
| | | 4 | | |
| | | 5 | | using Microsoft.EntityFrameworkCore.Storage; |
| | | 6 | | |
| | | 7 | | namespace Api.Database.Utils; |
| | | 8 | | |
| | | 9 | | public interface IEFTransactionDIAccessorService : IAsyncDisposable, IDisposable |
| | | 10 | | { |
| | | 11 | | public IDbContextTransaction BeginOrGetTransaction(); |
| | | 12 | | public Task<IDbContextTransaction> BeginOrGetTransactionAsync( |
| | | 13 | | CancellationToken? ct = null |
| | | 14 | | ); |
| | | 15 | | public ValueTask FinishTransaction(); |
| | | 16 | | public ValueTask SaveAndCommitTX(CancellationToken ct = default); |
| | | 17 | | public ValueTask CommitTX(CancellationToken ct = default); |
| | | 18 | | } |
| | | 19 | | |
| | 1 | 20 | | public class EFTransactionDIAccessorService(PGContext db) |
| | | 21 | | : IEFTransactionDIAccessorService |
| | | 22 | | { |
| | | 23 | | private IDbContextTransaction? _tx; |
| | | 24 | | |
| | | 25 | | public IDbContextTransaction BeginOrGetTransaction() |
| | 0 | 26 | | { |
| | 0 | 27 | | _tx ??= db.Database.BeginTransaction(); |
| | 0 | 28 | | return _tx; |
| | 0 | 29 | | } |
| | | 30 | | |
| | | 31 | | public async Task<IDbContextTransaction> BeginOrGetTransactionAsync( |
| | | 32 | | CancellationToken? ct = null |
| | | 33 | | ) |
| | 1 | 34 | | { |
| | 1 | 35 | | _tx ??= await db.Database.BeginTransactionAsync( |
| | 1 | 36 | | cancellationToken: ct ?? CancellationToken.None |
| | 1 | 37 | | ); |
| | 1 | 38 | | return _tx; |
| | 1 | 39 | | } |
| | | 40 | | |
| | | 41 | | public async ValueTask FinishTransaction() |
| | 0 | 42 | | { |
| | 0 | 43 | | if (_tx is not null) |
| | 0 | 44 | | await _tx.DisposeAsync(); |
| | | 45 | | |
| | 0 | 46 | | _tx = null; |
| | 0 | 47 | | } |
| | | 48 | | |
| | | 49 | | void IDisposable.Dispose() |
| | 0 | 50 | | { |
| | 0 | 51 | | GC.SuppressFinalize(this); |
| | 0 | 52 | | _tx?.Dispose(); |
| | 0 | 53 | | } |
| | | 54 | | |
| | | 55 | | public async ValueTask DisposeAsync() |
| | 1 | 56 | | { |
| | 1 | 57 | | GC.SuppressFinalize(this); |
| | 1 | 58 | | if (_tx is not null) |
| | 1 | 59 | | await _tx.DisposeAsync(); |
| | 1 | 60 | | } |
| | | 61 | | |
| | | 62 | | public async ValueTask CommitTX(CancellationToken ct = default) |
| | 1 | 63 | | { |
| | 1 | 64 | | if (_tx is not null) |
| | 0 | 65 | | { |
| | 0 | 66 | | await _tx.CommitAsync(ct); |
| | 0 | 67 | | await _tx.DisposeAsync(); |
| | 0 | 68 | | _tx = null; |
| | 0 | 69 | | } |
| | 1 | 70 | | } |
| | | 71 | | |
| | | 72 | | public async ValueTask SaveAndCommitTX(CancellationToken ct = default) |
| | 0 | 73 | | { |
| | 0 | 74 | | await db.SaveChangesAsync(ct); |
| | 0 | 75 | | await CommitTX(ct); |
| | 0 | 76 | | } |
| | | 77 | | } |