forked from Giorgi/DuckDB.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDuckDBTransaction.cs
More file actions
66 lines (53 loc) · 1.84 KB
/
Copy pathDuckDBTransaction.cs
File metadata and controls
66 lines (53 loc) · 1.84 KB
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
namespace DuckDB.NET.Data;
public class DuckDBTransaction : DbTransaction
{
private bool finished = false;
private readonly DuckDBConnection connection;
protected override DbConnection DbConnection => connection;
public override IsolationLevel IsolationLevel { get; }
public DuckDBTransaction(DuckDBConnection connection, IsolationLevel isolationLevel)
{
this.connection = connection;
IsolationLevel = isolationLevel;
if (isolationLevel != IsolationLevel.Snapshot && isolationLevel != IsolationLevel.Unspecified)
{
throw new ArgumentException($"Unsupported isolation level: {isolationLevel}", nameof(isolationLevel));
}
this.connection.ExecuteNonQuery("BEGIN TRANSACTION;");
}
public override void Commit() => FinishTransaction("COMMIT;");
public override void Rollback() => FinishTransaction("ROLLBACK");
private void FinishTransaction(string finalizer)
{
if (finished)
{
throw new InvalidOperationException("Transaction has already been finished.");
}
try
{
connection.ExecuteNonQuery(finalizer);
Cleanup();
}
// If something goes wrong with the transaction, to match the
// transaction's internal duckdb state it should still be considered
// finished and should no longer be used
catch (DuckDBException ex) when (ex.ErrorType == Native.DuckDBErrorType.Transaction)
{
Cleanup();
throw;
}
void Cleanup()
{
connection.Transaction = null;
finished = true;
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing && !finished && connection.IsOpen())
{
Rollback();
}
}
}