//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// DataHelpers.SQL satellite library | Author: Sergei Y.Kitáev
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
using System;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using u = user_rtx;

namespace DataHelpers.SQL {

partial class HQueryExecContextBase {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

/// <exception cref="InvalidOperationException" />
[u.async_local]
public static async Task Connect_A() =>
   await Current.DoConnect_A().ConfigureAwait(false);

async Task DoConnect_A()
{
   if ( _connectionOpenAttempt )
      throw ConnectionError_RepeatedAttempt;
   await DoEnsureConnected_A().ConfigureAwait(false);
}

//--------------------------------------------------------------------------------------------------

/// <exception cref="InvalidOperationException" />
[u.async_local]
public static async Task EnsureConnected_A() =>
   await Current.DoEnsureConnected_A().ConfigureAwait(false);

/// <exception cref="InvalidOperationException" />
async Task DoEnsureConnected_A()
{
   if ( !_hasConnectionOwnership )
      return;
   if ( _connectionOpenAttempt ) {
      if ( _connectionException != null )
         throw _connectionException;
      EnsureConnected_UnexpectedConnectionState( ConnectionNN );
      return;
   }
   _connectionOpenAttempt = true;
   try { await ConnectionNN.OpenAsync().ConfigureAwait(false); }
   catch (Exception e) {
      _connectionException = e;
      throw; }
}

//--------------------------------------------------------------------------------------------------

/// <exception cref="InvalidOperationException" />
/// <exception cref="Exception" />
[u.async_local]
public static async Task<SqlConnection> GetOpenConnection_A() =>
   await Current.DoGetOpenConnection_A().ConfigureAwait(false);

async Task<SqlConnection> DoGetOpenConnection_A()
{
   await EnsureConnected_A().ConfigureAwait(false);
   return _connection.NN();
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
} // HQueryExecContextBase

} // DataHelpers.SQL
