Datei: NDODLL/NDOTransactionScope.cs

Last Commit (4b748a1)
1 using NDO.Mapping;
 
2 using System;
3 using System.Collections.Generic;
4 using System.Data;
5 using System.Linq;
6 using System.Text.RegularExpressions;
7
8 namespace NDO
9 {
10 ····/// <summary>
11 ····/// class NDOTransactionScope
12 ····/// </summary>
13 ····public class NDOTransactionScope : INDOTransactionScope
14 ····{
15 ········private PersistenceManager pm;
16
17 ········private Dictionary<string, IDbConnection> usedConnections = new Dictionary<string, IDbConnection>();
18 ········private Dictionary<string, IDbTransaction> usedTransactions = new Dictionary<string, IDbTransaction>();
19
20 ········///<inheritdoc/>
21 ········public IsolationLevel IsolationLevel { get; set; }
22 ········///<inheritdoc/>
23 ········public TransactionMode TransactionMode { get; set; }
24
25 ········bool isInTransaction = false;
26
27 ········/// <summary>
28 ········/// Constructs an NDOTransactionScope object.
29 ········/// </summary>
30 ········public NDOTransactionScope()
31 ········{
32 ············IsolationLevel = IsolationLevel.ReadCommitted;
33 ············TransactionMode = TransactionMode.Optimistic;
34 ········}
35
36 ········///<inheritdoc/>
37 ········public void CheckTransaction()
38 ········{
39 ············if (TransactionMode == TransactionMode.None)
40 ············{
41 ················return;
42 ············}
43
44 ············if (!this.isInTransaction)
45 ············{
46 ················foreach (var connId in this.usedConnections.Keys)
47 ················{
48 ····················OpenConnAndStartTransaction( connId, this.usedConnections[connId] );
49 ················}
50 ············}
51
52 ············this.isInTransaction = true;
53 ········}
54
55 ········private void OpenConnAndStartTransaction( string connId, IDbConnection conn )
56 ········{
57 ············conn.Open();
58 pm. LogIfVerbose( $"Opening connection { conn. DisplayName( ) } " ) ;
 
59 ············var tx = conn.BeginTransaction(IsolationLevel);
60 ············usedTransactions.Add( connId, tx );
61 this. pm. LogIfVerbose( String. Format( "Starting transaction { 0:X} at connection '{ 1} '", tx. GetHashCode( ) , conn. DisplayName( ) ) ) ;
62 ········}
63
64 ········///<inheritdoc/>
65 ········public void Complete()
66 ········{
67 ············CommitTransactions();
68 ············CloseConnections();
69 ············isInTransaction = false;
70 ········}
71
72 ········private void CommitTransactions()
73 ········{
74 ············foreach (var id in usedTransactions.Keys)
75 ············{
76 ················var tx = usedTransactions[id];
77 ················tx.Commit();
78
79 ················IDbConnection conn = null;
80 ················usedConnections.TryGetValue( id, out conn );
81 ················if (conn == null)
82 ····················throw new NDOException( 121, $"Can't commit. No open connection found for NDO Connection {id} ({conn.DisplayName()})" );
83 this. pm. LogIfVerbose( String. Format( "Committing transaction { 0:X} at connection '{ 1} '", tx. GetHashCode( ) , conn. DisplayName( ) ) ) ;
 
84 ············}
85
86 ············usedTransactions.Clear();
87 ········}
88
89 ········///<inheritdoc/>
90 ········public IDbConnection GetConnection( string id, Func<IDbConnection> factory )
91 ········{
92 ············if (this.usedConnections.ContainsKey( id ))
93 ············{
94 ················return this.usedConnections[id];
95 ············}
96 ············else
97 ············{
98 ················var conn = factory();
99 ················this.usedConnections.Add( id, conn );
100 ················if (this.isInTransaction)
101 ····················OpenConnAndStartTransaction( id, conn );
102 ················return conn;
103 ············}
104 ········}
105
106
107 ········///<inheritdoc/>
108 ········public IDbTransaction GetTransaction( string id )
109 ········{
110 ············if (isInTransaction)
111 ············{
112 ················IDbTransaction tx = null;
113 ················this.usedTransactions.TryGetValue( id, out tx );
114 ················return tx;
115 ············}
116
117 ············return null;
118 ········}
119
120 ········///<inheritdoc/>
121 ········public void Dispose()
122 ········{
123 ············RollbackTransactions();
124 ············CloseConnections();
125 ············this.isInTransaction = false;
126 ········}
127
128 ········private void RollbackTransactions()
129 ········{
130 ············foreach (var key in usedTransactions.Keys)
131 ············{
132 ················var tx = this.usedTransactions[key];
133 ················var id = tx.GetHashCode();
134 ················try
135 ················{
136 ····················// See https://github.com/dotnet/runtime/issues/95399
137 ····················// We don't have any information about the state of the transaction.
138 ····················// If it is completed, we will get an exception here.
139 ····················// Given that in most cases it's possible to track the tx state outside of NDO,
140 ····················// we are safe here in the most cases.
141 ····················tx.Rollback();
142 ················}
143 ················catch
144 ················{
145 ················}
146 ················IDbConnection conn = null;
147 ················this.usedConnections.TryGetValue( key, out conn );
148 pm. LogIfVerbose( $"Rollback transaction { id. ToString( "X" ) } at connection '{ conn. DisplayName( ) } '" ) ;
 
 
 
149 ············}
150
151 ············usedTransactions.Clear();
152 ········}
153
154 ········private void CloseConnections()
155 ········{
156 ············foreach (var conn in this.usedConnections.Values.Where( c => c.State == ConnectionState.Open ))
157 ············{
 
 
158 ················conn.Close();
159 ················pm.LogIfVerbose( $"Closed connection {conn.DisplayName()}" );
160 ············}
161
162 ············this.usedConnections.Clear();
163 ········}
164
165 ········/// <inheritdoc/>
166 ········public INDOTransactionScope Initialize( PersistenceManager pm )
167 ········{
168 ············this.pm = pm;
169 ············return this;
170 ········}
171 ····}
172
173 ····static class ConnectionExtension
174 ····{
175 ········public static string DisplayName(this IDbConnection conn)
176 ········{
177 ············if (conn == null)
178 ················return "??";
179
180 ············var str = conn.ConnectionString;
181 ············if (String.IsNullOrEmpty( str ))
182 ················return str;
183 ············Regex regex = new Regex( "password=[^;]*" );
184 ············return regex.Replace( str, "password=***" );
185 ········}
186 ····}
187 }
188
New Commit (f856804)
1 using NDO.Mapping;
2 using NDOInterfaces;
3 using System;
4 using System.Collections.Generic;
5 using System.Data;
6 using System.Linq;
7 using System.Text.RegularExpressions;
8
9 namespace NDO
10 {
11 ····/// <summary>
12 ····/// class NDOTransactionScope
13 ····/// </summary>
14 ····public class NDOTransactionScope : INDOTransactionScope
15 ····{
16 ········private PersistenceManager pm;
17
18 ········private Dictionary<string, IDbConnection> usedConnections = new Dictionary<string, IDbConnection>();
19 ········private Dictionary<string, IDbTransaction> usedTransactions = new Dictionary<string, IDbTransaction>();
20
21 ········///<inheritdoc/>
22 ········public IsolationLevel IsolationLevel { get; set; }
23 ········///<inheritdoc/>
24 ········public TransactionMode TransactionMode { get; set; }
25
26 ········bool isInTransaction = false;
27
28 ········/// <summary>
29 ········/// Constructs an NDOTransactionScope object.
30 ········/// </summary>
31 ········public NDOTransactionScope()
32 ········{
33 ············IsolationLevel = IsolationLevel.ReadCommitted;
34 ············TransactionMode = TransactionMode.Optimistic;
35 ········}
36
37 ········///<inheritdoc/>
38 ········public void CheckTransaction()
39 ········{
40 ············if (TransactionMode == TransactionMode.None)
41 ············{
42 ················return;
43 ············}
44
45 ············if (!this.isInTransaction)
46 ············{
47 ················foreach (var connId in this.usedConnections.Keys)
48 ················{
49 ····················OpenConnAndStartTransaction( connId, this.usedConnections[connId] );
50 ················}
51 ············}
52
53 ············this.isInTransaction = true;
54 ········}
55
56 ········private void OpenConnAndStartTransaction( string connId, IDbConnection conn )
57 ········{
58 ············conn.Open();
59 var serverId = ( ( INdoDbConnection) conn) . ConnectionId;
60 ············pm.LogIfVerbose( $"Opening connection {serverId} = '{conn.DisplayName()}'" );
61 ············var tx = conn.BeginTransaction(IsolationLevel);
62 ············usedTransactions.Add( connId, tx );
63 this. pm. LogIfVerbose( $"Starting transaction { tx. GetHashCode( ) :X} at connection { serverId} = '{ conn. DisplayName( ) } '" ) ;
64 ········}
65
66 ········///<inheritdoc/>
67 ········public void Complete()
68 ········{
69 ············CommitTransactions();
70 ············CloseConnections();
71 ············isInTransaction = false;
72 ········}
73
74 ········private void CommitTransactions()
75 ········{
76 ············foreach (var id in usedTransactions.Keys)
77 ············{
78 ················var tx = usedTransactions[id];
79 ················tx.Commit();
80
81 ················IDbConnection conn = null;
82 ················usedConnections.TryGetValue( id, out conn );
83 ················if (conn == null)
84 ····················throw new NDOException( 121, $"Can't commit. No open connection found for NDO Connection {id} ({conn.DisplayName()})" );
85 var serverId = ( ( INdoDbConnection) conn) . ConnectionId;
86 ················this.pm.LogIfVerbose( $"Committing transaction {tx.GetHashCode():X} at connection {serverId} = '{conn.DisplayName()}'" );
87 ············}
88
89 ············usedTransactions.Clear();
90 ········}
91
92 ········///<inheritdoc/>
93 ········public IDbConnection GetConnection( string id, Func<IDbConnection> factory )
94 ········{
95 ············if (this.usedConnections.ContainsKey( id ))
96 ············{
97 ················return this.usedConnections[id];
98 ············}
99 ············else
100 ············{
101 ················var conn = factory();
102 ················this.usedConnections.Add( id, conn );
103 ················if (this.isInTransaction)
104 ····················OpenConnAndStartTransaction( id, conn );
105 ················return conn;
106 ············}
107 ········}
108
109
110 ········///<inheritdoc/>
111 ········public IDbTransaction GetTransaction( string id )
112 ········{
113 ············if (isInTransaction)
114 ············{
115 ················IDbTransaction tx = null;
116 ················this.usedTransactions.TryGetValue( id, out tx );
117 ················return tx;
118 ············}
119
120 ············return null;
121 ········}
122
123 ········///<inheritdoc/>
124 ········public void Dispose()
125 ········{
126 ············RollbackTransactions();
127 ············CloseConnections();
128 ············this.isInTransaction = false;
129 ········}
130
131 ········private void RollbackTransactions()
132 ········{
133 ············foreach (var key in usedTransactions.Keys)
134 ············{
135 ················var tx = this.usedTransactions[key];
136 ················var id = tx.GetHashCode();
137 ················try
138 ················{
139 ····················// See https://github.com/dotnet/runtime/issues/95399
140 ····················// We don't have any information about the state of the transaction.
141 ····················// If it is completed, we will get an exception here.
142 ····················// Given that in most cases it's possible to track the tx state outside of NDO,
143 ····················// we are safe here in the most cases.
144 ····················tx.Rollback();
145 ················}
146 ················catch
147 ················{
148 ················}
149 ················IDbConnection conn = null;
150 ················this.usedConnections.TryGetValue( key, out conn );
151 {
152 ····················var serverId = ((INdoDbConnection)conn).ConnectionId;
153 ····················this.pm.LogIfVerbose( $"Rollback transaction {id.ToString( "X" )} at connection {serverId} = '{conn.DisplayName()}'" );
154 ················}
155 ············}
156
157 ············usedTransactions.Clear();
158 ········}
159
160 ········private void CloseConnections()
161 ········{
162 ············foreach (var conn in this.usedConnections.Values.Where( c => c.State == ConnectionState.Open ))
163 ············{
164 ················var serverId = ((INdoDbConnection)conn).ConnectionId;
165 ················pm.LogIfVerbose( $"Closed connection {serverId} = '{conn.DisplayName()}'" );
166 ················conn.Close();
 
167 ············}
168
169 ············this.usedConnections.Clear();
170 ········}
171
172 ········/// <inheritdoc/>
173 ········public INDOTransactionScope Initialize( PersistenceManager pm )
174 ········{
175 ············this.pm = pm;
176 ············return this;
177 ········}
178 ····}
179
180 ····static class ConnectionExtension
181 ····{
182 ········public static string DisplayName(this IDbConnection conn)
183 ········{
184 ············if (conn == null)
185 ················return "??";
186
187 ············var str = conn.ConnectionString;
188 ············if (String.IsNullOrEmpty( str ))
189 ················return str;
190 ············Regex regex = new Regex( "password=[^;]*" );
191 ············return regex.Replace( str, "password=***" );
192 ········}
193 ····}
194 }
195