SqlInternalConnectionSmi.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. //------------------------------------------------------------------------------
  2. // <copyright file="SqlInternalConnectionSmi.cs" company="Microsoft">
  3. // Copyright (c) Microsoft Corporation. All rights reserved.
  4. // </copyright>
  5. // <owner current="true" primary="true">[....]</owner>
  6. // <owner current="true" primary="false">[....]</owner>
  7. //------------------------------------------------------------------------------
  8. namespace System.Data.SqlClient {
  9. using Microsoft.SqlServer.Server;
  10. using System.Data;
  11. using System.Data.Common;
  12. using System.Diagnostics;
  13. using SysTx = System.Transactions;
  14. sealed internal class SqlInternalConnectionSmi : SqlInternalConnection {
  15. private SmiContext _smiContext;
  16. private SmiConnection _smiConnection;
  17. private SmiEventSink_Default _smiEventSink;
  18. private int _isInUse; // 1 = Connected to open outer connection, 0 = not connected
  19. private SqlInternalTransaction _pendingTransaction; // transaction awaiting event signalling that it is active
  20. private SqlInternalTransaction _currentTransaction; // currently active non-context transaction.
  21. sealed private class EventSink : SmiEventSink_Default {
  22. SqlInternalConnectionSmi _connection;
  23. override internal string ServerVersion {
  24. get {
  25. return SmiContextFactory.Instance.ServerVersion;
  26. }
  27. }
  28. override protected void DispatchMessages(bool ignoreNonFatalMessages) {
  29. // Override this on the Connection event sink, since we can deal
  30. // with info messages here.
  31. SqlException exception = ProcessMessages(false, ignoreNonFatalMessages);
  32. if (null != exception) {
  33. // SQLBUVSTS 225982, query for connection once to avoid race condition between GC (that may collect the connection) and the user thread
  34. SqlConnection connection = _connection.Connection;
  35. if (null != connection && connection.FireInfoMessageEventOnUserErrors) {
  36. connection.OnInfoMessage(new SqlInfoMessageEventArgs(exception));
  37. }
  38. else {
  39. _connection.OnError(exception, false); // we can't really ever break the direct connection, can we?
  40. }
  41. }
  42. }
  43. internal EventSink(SqlInternalConnectionSmi connection) {
  44. Debug.Assert(null != connection, "null connection?");
  45. _connection = connection;
  46. }
  47. internal override void DefaultDatabaseChanged( string databaseName ) {
  48. if (Bid.AdvancedOn) {
  49. Bid.Trace("<sc.SqlInternalConnectionSmi.EventSink.DefaultDatabaseChanged|ADV> %d#, databaseName='%ls'.\n", _connection.ObjectID, databaseName);
  50. }
  51. _connection.CurrentDatabase = databaseName;
  52. }
  53. internal override void TransactionCommitted( long transactionId ) {
  54. if (Bid.AdvancedOn) {
  55. Bid.Trace("<sc.SqlInternalConnectionSmi.EventSink.TransactionCommitted|ADV> %d#, transactionId=0x%I64x.\n", _connection.ObjectID, transactionId);
  56. }
  57. _connection.TransactionEnded(transactionId, TransactionState.Committed);
  58. }
  59. internal override void TransactionDefected( long transactionId ) {
  60. if (Bid.AdvancedOn) {
  61. Bid.Trace("<sc.SqlInternalConnectionSmi.EventSink.TransactionDefected|ADV> %d#, transactionId=0x%I64x.\n", _connection.ObjectID, transactionId);
  62. }
  63. _connection.TransactionEnded(transactionId, TransactionState.Unknown);
  64. }
  65. internal override void TransactionEnlisted( long transactionId ) {
  66. if (Bid.AdvancedOn) {
  67. Bid.Trace("<sc.SqlInternalConnectionSmi.EventSink.TransactionEnlisted|ADV> %d#, transactionId=0x%I64x.\n", _connection.ObjectID, transactionId);
  68. }
  69. _connection.TransactionStarted(transactionId, true); // distributed;
  70. }
  71. internal override void TransactionEnded( long transactionId ) {
  72. if (Bid.AdvancedOn) {
  73. Bid.Trace("<sc.SqlInternalConnectionSmi.EventSink.TransactionEnded|ADV> %d#, transactionId=0x%I64x.\n", _connection.ObjectID, transactionId);
  74. }
  75. _connection.TransactionEndedByServer(transactionId, TransactionState.Unknown);
  76. }
  77. internal override void TransactionRolledBack( long transactionId ) {
  78. if (Bid.AdvancedOn) {
  79. Bid.Trace("<sc.SqlInternalConnectionSmi.EventSink.TransactionRolledBack|ADV> %d#, transactionId=0x%I64x.\n", _connection.ObjectID, transactionId);
  80. }
  81. // Dev11 1066: ensure delegated transaction is rolled back
  82. _connection.TransactionEndedByServer(transactionId, TransactionState.Aborted);
  83. }
  84. internal override void TransactionStarted( long transactionId ) {
  85. if (Bid.AdvancedOn) {
  86. Bid.Trace("<sc.SqlInternalConnectionSmi.EventSink.TransactionStarted|ADV> %d#, transactionId=0x%I64x.\n", _connection.ObjectID, transactionId);
  87. }
  88. _connection.TransactionStarted(transactionId, false); // not distributed;
  89. }
  90. }
  91. internal SqlInternalConnectionSmi(SqlConnectionString connectionOptions, SmiContext smiContext) : base(connectionOptions) {
  92. Debug.Assert(null != smiContext, "null smiContext?");
  93. _smiContext = smiContext;
  94. _smiContext.OutOfScope += new EventHandler(OnOutOfScope);
  95. _smiConnection = _smiContext.ContextConnection;
  96. Debug.Assert(null != _smiConnection, "null SmiContext.ContextConnection?");
  97. _smiEventSink = new EventSink(this);
  98. if (Bid.AdvancedOn) {
  99. Bid.Trace("<sc.SqlInternalConnectionSmi.ctor|ADV> %d#, constructed new SMI internal connection\n", ObjectID);
  100. }
  101. }
  102. internal SmiContext InternalContext {
  103. get {
  104. return _smiContext;
  105. }
  106. }
  107. internal SmiConnection SmiConnection {
  108. get {
  109. return _smiConnection;
  110. }
  111. }
  112. internal SmiEventSink CurrentEventSink {
  113. get {
  114. return _smiEventSink;
  115. }
  116. }
  117. override internal SqlInternalTransaction CurrentTransaction {
  118. get {
  119. return _currentTransaction;
  120. }
  121. }
  122. override internal bool IsLockedForBulkCopy {
  123. get {
  124. return false; // no bulk copy in the Direct connection case.
  125. }
  126. }
  127. override internal bool IsShiloh {
  128. get {
  129. return false; // Can't be direct connecting to Shiloh.
  130. }
  131. }
  132. override internal bool IsYukonOrNewer {
  133. get {
  134. return true; // Must be direct connecting to Yukon or newer.
  135. }
  136. }
  137. override internal bool IsKatmaiOrNewer {
  138. get {
  139. return SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion;
  140. }
  141. }
  142. override internal SqlInternalTransaction PendingTransaction {
  143. get {
  144. return CurrentTransaction; // there are no differences between pending and current in proc.
  145. }
  146. }
  147. override public string ServerVersion {
  148. get {
  149. return SmiContextFactory.Instance.ServerVersion;
  150. }
  151. }
  152. /// <summary>
  153. /// Get boolean that specifies whether an enlisted transaction can be unbound from
  154. /// the connection when that transaction completes.
  155. /// </summary>
  156. /// <value>
  157. /// True if the connection string property "TransactionBinding" is set to TransactionBindingEnum.ImplicitUnbind;
  158. /// otherwise, false.
  159. /// </value>
  160. protected override bool UnbindOnTransactionCompletion
  161. {
  162. get
  163. {
  164. return ConnectionOptions.TransactionBinding == SqlConnectionString.TransactionBindingEnum.ImplicitUnbind;
  165. }
  166. }
  167. // Workaround to access context transaction without rewriting connection pool & internalconnections properly.
  168. // Context transactions SHOULD be considered enlisted.
  169. // This works for now only because we can't unenlist from the context transaction
  170. // DON'T START USING THIS ANYWHERE EXCEPT IN InternalTransaction and in InternalConnectionSmi!!!
  171. private SysTx.Transaction ContextTransaction
  172. {
  173. get;
  174. set;
  175. }
  176. private SysTx.Transaction InternalEnlistedTransaction
  177. {
  178. get
  179. {
  180. // Workaround to access context transaction without rewriting connection pool & internalconnections properly.
  181. // This SHOULD be a simple wrapper around EnlistedTransaction.
  182. // This works for now only because we can't unenlist from the context transaction
  183. SysTx.Transaction tx = EnlistedTransaction;
  184. if (null == tx)
  185. {
  186. tx = ContextTransaction;
  187. }
  188. return tx;
  189. }
  190. }
  191. override protected void Activate(SysTx.Transaction transaction)
  192. {
  193. Debug.Assert(false, "Activating an internal SMI connection?"); // we should never be activating, because that would indicate we're being pooled.
  194. }
  195. internal void Activate() {
  196. int wasInUse = System.Threading.Interlocked.Exchange(ref _isInUse, 1);
  197. if (0 != wasInUse) {
  198. throw SQL.ContextConnectionIsInUse();
  199. }
  200. CurrentDatabase = _smiConnection.GetCurrentDatabase(_smiEventSink);
  201. _smiEventSink.ProcessMessagesAndThrow();
  202. }
  203. internal void AutomaticEnlistment() {
  204. SysTx.Transaction currentSystemTransaction = ADP.GetCurrentTransaction(); // NOTE: Must be first to ensure _smiContext.ContextTransaction is set!
  205. SysTx.Transaction contextTransaction = _smiContext.ContextTransaction; // returns the transaction that was handed to SysTx that wraps the ContextTransactionId.
  206. long contextTransactionId = _smiContext.ContextTransactionId;
  207. if (Bid.AdvancedOn) {
  208. Bid.Trace("<sc.SqlInternalConnectionSmi.AutomaticEnlistment|ADV> %d#, contextTransactionId=0x%I64x, contextTransaction=%d#, currentSystemTransaction=%d#.\n",
  209. base.ObjectID,
  210. contextTransactionId,
  211. (null != contextTransaction) ? contextTransaction.GetHashCode() : 0,
  212. (null != currentSystemTransaction) ? currentSystemTransaction.GetHashCode() : 0);
  213. }
  214. if (SqlInternalTransaction.NullTransactionId != contextTransactionId) {
  215. if (null != currentSystemTransaction && contextTransaction != currentSystemTransaction) {
  216. throw SQL.NestedTransactionScopesNotSupported(); // can't use TransactionScope(RequiresNew) inside a Sql Transaction.
  217. }
  218. if (Bid.AdvancedOn) {
  219. Bid.Trace("<sc.SqlInternalConnectionSmi.AutomaticEnlistment|ADV> %d#, using context transaction with transactionId=0x%I64x\n", base.ObjectID, contextTransactionId);
  220. }
  221. _currentTransaction = new SqlInternalTransaction(this, TransactionType.Context, null, contextTransactionId);
  222. ContextTransaction = contextTransaction;
  223. }
  224. else if (null == currentSystemTransaction) {
  225. _currentTransaction = null; // there really isn't a transaction.
  226. if (Bid.AdvancedOn) {
  227. Bid.Trace("<sc.SqlInternalConnectionSmi.AutomaticEnlistment|ADV> %d#, no transaction.\n", base.ObjectID);
  228. }
  229. }
  230. else {
  231. if (Bid.AdvancedOn) {
  232. Bid.Trace("<sc.SqlInternalConnectionSmi.AutomaticEnlistment|ADV> %d#, using current System.Transaction.\n", base.ObjectID);
  233. }
  234. base.Enlist(currentSystemTransaction);
  235. }
  236. }
  237. override protected void ChangeDatabaseInternal(string database) {
  238. _smiConnection.SetCurrentDatabase(database, _smiEventSink);
  239. _smiEventSink.ProcessMessagesAndThrow();
  240. }
  241. override protected void InternalDeactivate() {
  242. if (Bid.AdvancedOn) {
  243. Bid.Trace("<sc.SqlInternalConnectionSmi.Deactivate|ADV> %d#, Deactivating.\n", base.ObjectID);
  244. }
  245. // When we put this to bed, we should not hold on to the transaction
  246. // or any activity (commit/rollback) may cause it to stop responding.
  247. if (!IsNonPoolableTransactionRoot) {
  248. base.Enlist(null);
  249. }
  250. if (null != _currentTransaction) {
  251. if (_currentTransaction.IsContext) {
  252. _currentTransaction = null;
  253. }
  254. else if (_currentTransaction.IsLocal) {
  255. _currentTransaction.CloseFromConnection();
  256. }
  257. }
  258. ContextTransaction = null;
  259. _isInUse = 0; // don't need compare-exchange.
  260. }
  261. override internal void DelegatedTransactionEnded() {
  262. base.DelegatedTransactionEnded();
  263. if (Bid.AdvancedOn) {
  264. Bid.Trace("<sc.SqlInternalConnectionSmi.DelegatedTransactionEnded|ADV> %d#, cleaning up after Delegated Transaction Completion\n", base.ObjectID);
  265. }
  266. _currentTransaction = null; // clean up our current transaction too
  267. }
  268. override internal void DisconnectTransaction(SqlInternalTransaction internalTransaction) {
  269. if (Bid.AdvancedOn) {
  270. Bid.Trace("<sc.SqlInternalConnectionSmi.DisconnectTransaction|ADV> %d#, Disconnecting Transaction %d#.\n", base.ObjectID, internalTransaction.ObjectID);
  271. }
  272. // VSTS 215465/15029: allow _currentTransaction to be null - it can be cleared before by server's callback
  273. Debug.Assert(_currentTransaction == null || _currentTransaction == internalTransaction, "disconnecting different transaction");
  274. if (_currentTransaction != null && _currentTransaction == internalTransaction) {
  275. _currentTransaction = null;
  276. }
  277. }
  278. override public void Dispose() {
  279. _smiContext.OutOfScope -= new EventHandler(OnOutOfScope);
  280. base.Dispose();
  281. }
  282. override internal void ExecuteTransaction(
  283. TransactionRequest transactionRequest,
  284. string transactionName,
  285. IsolationLevel iso,
  286. SqlInternalTransaction internalTransaction,
  287. bool isDelegateControlRequest) {
  288. if (Bid.AdvancedOn) {
  289. Bid.Trace("<sc.SqlInternalConnectionSmi.ExecuteTransaction|ADV> %d#, transactionRequest=%ls, transactionName='%ls', isolationLevel=%ls, internalTransaction=#%d transactionId=0x%I64x.\n",
  290. base.ObjectID,
  291. transactionRequest.ToString(),
  292. (null != transactionName) ? transactionName : "null",
  293. iso.ToString(),
  294. (null != internalTransaction) ? internalTransaction.ObjectID : 0,
  295. (null != internalTransaction) ? internalTransaction.TransactionId : SqlInternalTransaction.NullTransactionId
  296. );
  297. }
  298. switch (transactionRequest) {
  299. case TransactionRequest.Begin:
  300. try {
  301. _pendingTransaction = internalTransaction; // store this for the time being.
  302. _smiConnection.BeginTransaction(transactionName, iso, _smiEventSink);
  303. }
  304. finally {
  305. _pendingTransaction = null;
  306. }
  307. Debug.Assert(_smiEventSink.HasMessages || null != _currentTransaction, "begin transaction without TransactionStarted event?");
  308. break;
  309. case TransactionRequest.Commit:
  310. Debug.Assert(null != _currentTransaction, "commit transaction without TransactionStarted event?");
  311. _smiConnection.CommitTransaction(_currentTransaction.TransactionId, _smiEventSink);
  312. break;
  313. case TransactionRequest.Promote:
  314. Debug.Assert(null != _currentTransaction, "promote transaction without TransactionStarted event?");
  315. PromotedDTCToken = _smiConnection.PromoteTransaction(_currentTransaction.TransactionId, _smiEventSink);
  316. break;
  317. case TransactionRequest.Rollback:
  318. case TransactionRequest.IfRollback:
  319. Debug.Assert(null != _currentTransaction, "rollback/ifrollback transaction without TransactionStarted event?");
  320. _smiConnection.RollbackTransaction(_currentTransaction.TransactionId, transactionName, _smiEventSink);
  321. break;
  322. case TransactionRequest.Save:
  323. Debug.Assert(null != _currentTransaction, "save transaction without TransactionStarted event?");
  324. _smiConnection.CreateTransactionSavePoint(_currentTransaction.TransactionId, transactionName, _smiEventSink);
  325. break;
  326. default:
  327. Debug.Assert (false, "unhandled case for TransactionRequest");
  328. break;
  329. }
  330. _smiEventSink.ProcessMessagesAndThrow();
  331. }
  332. override protected byte[] GetDTCAddress() {
  333. byte[] whereAbouts = _smiConnection.GetDTCAddress(_smiEventSink); // might want to store this on the SmiLink because it doesn't change, but we want to be compatible with TDS which doesn't have a link yet.
  334. _smiEventSink.ProcessMessagesAndThrow();
  335. if (Bid.AdvancedOn) {
  336. if (null != whereAbouts) {
  337. Bid.TraceBin("<sc.SqlInternalConnectionSmi.GetDTCAddress|ADV> whereAbouts", whereAbouts, (UInt16)whereAbouts.Length);
  338. }
  339. else {
  340. Bid.Trace("<sc.SqlInternalConnectionSmi.GetDTCAddress|ADV> whereAbouts=null\n");
  341. }
  342. }
  343. return whereAbouts;
  344. }
  345. internal void GetCurrentTransactionPair(out long transactionId, out SysTx.Transaction transaction) {
  346. // SQLBU 214740: Transaction state could change between obtaining tranid and transaction
  347. // due to background SqlDelegatedTransaction processing. Lock the connection to prevent that.
  348. lock (this) {
  349. transactionId = (null != CurrentTransaction) ? CurrentTransaction.TransactionId : 0;
  350. transaction = null;
  351. if (0 != transactionId) {
  352. transaction = InternalEnlistedTransaction;
  353. }
  354. }
  355. }
  356. private void OnOutOfScope(object s, EventArgs e) {
  357. // Called whenever the context goes out of scope, we need to make
  358. // sure that we close the connection, or the next person that uses
  359. // the context may appear to have the connection in use.
  360. if (Bid.AdvancedOn) {
  361. Bid.Trace("<sc.SqlInternalConnectionSmi.OutOfScope|ADV> %d# context is out of scope\n", base.ObjectID);
  362. }
  363. //
  364. DelegatedTransaction = null; // we don't want to hold this over to the next usage; it will automatically be reused as the context transaction...
  365. DbConnection owningObject = (DbConnection)Owner;
  366. try {
  367. if (null != owningObject && 1 == _isInUse) {
  368. // SQLBU 369953
  369. // for various reasons, the owning object may no longer be connection to this
  370. // so call close on the owner, rather than trying to bypass to use internal close logic.
  371. owningObject.Close();
  372. }
  373. }
  374. finally {
  375. // Now make sure this object is not left in an in-use state
  376. // this is safe, because no user code should be accessing the connection by this time
  377. ContextTransaction = null;
  378. _isInUse = 0;
  379. }
  380. }
  381. override protected void PropagateTransactionCookie(byte[] transactionCookie) {
  382. if (Bid.AdvancedOn) {
  383. if (null != transactionCookie) {
  384. Bid.TraceBin("<sc.SqlInternalConnectionSmi.PropagateTransactionCookie|ADV> transactionCookie", transactionCookie, (UInt16)transactionCookie.Length);
  385. }
  386. else {
  387. Bid.Trace("<sc.SqlInternalConnectionSmi.PropagateTransactionCookie|ADV> null\n");
  388. }
  389. }
  390. // Propagate the transaction cookie to the server
  391. _smiConnection.EnlistTransaction(transactionCookie, _smiEventSink);
  392. _smiEventSink.ProcessMessagesAndThrow();
  393. }
  394. private void TransactionEndedByServer(long transactionId, TransactionState transactionState) {
  395. // Some extra steps required when the server initiates the ending of a transaction unilaterally
  396. // as opposed to the client initiating it.
  397. // Basically, we have to make the delegated transaction (if there is one) aware of the situation.
  398. SqlDelegatedTransaction delegatedTransaction = DelegatedTransaction;
  399. if (null != delegatedTransaction) {
  400. delegatedTransaction.Transaction.Rollback(); // just to make sure...
  401. DelegatedTransaction = null; // He's dead, Jim.
  402. }
  403. // Now handle the standard transaction-ended stuff.
  404. TransactionEnded(transactionId, transactionState);
  405. }
  406. private void TransactionEnded(long transactionId, TransactionState transactionState) {
  407. // When we get notification of a completed transaction
  408. // we null out the current transaction.
  409. if (null != _currentTransaction) {
  410. #if DEBUG
  411. // Check null for case where Begin and Rollback obtained in the same message.
  412. if (0 != _currentTransaction.TransactionId) {
  413. Debug.Assert(_currentTransaction.TransactionId == transactionId, "transaction id's are not equal!");
  414. }
  415. #endif
  416. _currentTransaction.Completed(transactionState);
  417. _currentTransaction = null;
  418. }
  419. }
  420. private void TransactionStarted(long transactionId, bool isDistributed) {
  421. // When we get notification from the server of a new
  422. // transaction, we move any pending transaction over to
  423. // the current transaction, then we store the token in it.
  424. // if there isn't a pending transaction, then it's either
  425. // a TSQL transaction or a distributed transaction.
  426. Debug.Assert(null == _currentTransaction, "non-null current transaction with an env change");
  427. _currentTransaction = _pendingTransaction;
  428. _pendingTransaction = null;
  429. if (null != _currentTransaction) {
  430. _currentTransaction.TransactionId = transactionId; // this is defined as a ULongLong in the server and in the TDS Spec.
  431. }
  432. else {
  433. TransactionType transactionType = (isDistributed) ? TransactionType.Distributed : TransactionType.LocalFromTSQL;
  434. _currentTransaction = new SqlInternalTransaction(this, transactionType, null, transactionId);
  435. }
  436. _currentTransaction.Activate(); // SQLBUDT #376531 -- ensure this is activated to prevent asserts later.
  437. }
  438. override internal void ValidateConnectionForExecute(SqlCommand command) {
  439. SqlDataReader reader = FindLiveReader(null);
  440. if (null != reader) {
  441. // if MARS is on, then a datareader associated with the command exists
  442. // or if MARS is off, then a datareader exists
  443. throw ADP.OpenReaderExists(); // MDAC 66411
  444. }
  445. }
  446. }
  447. }