/// <summary> /// Run the specified SQL command as an asynchronous operation. /// </summary> /// <typeparam name="T">The expected result type.</typeparam> /// <param name="context">The SQL context to run.</param> /// <param name="processor"> /// The query processor. If this value is null, a non-query type command /// is assumed and the integer type will be assumed. /// </param> /// <param name="cancel">A token to monitor for cancellation requests.</param> /// <returns>An asynchronous task for the query result.</returns> private async Task <T> RunCommandAsync <T>(IContext context, IResultProcessor processor = null, CancellationToken cancel = default) { AssertCorrectReturnType <T>(processor); using (var connection = await CreateConnectionAsync()) { using (var command = connection.CreateCommand()) { // initialize command command.Connection = connection; command.CommandText = context.CommandText; AddParametersToCommand(command, context); object result; using (var scope = CreateScope(context)) { try { await connection.OpenAsync(cancel); if (processor == null) { result = await command.ExecuteNonQueryAsync(cancel); } else { using (var reader = await command.ExecuteReaderAsync(cancel)) { result = processor.Process(reader); } } connection.Close(); } catch { scope.Span.SetTag(Tags.Error, true); throw; } } return((T)result); } } }
/// <summary> /// Run the specified SQL command as an normal, thread-blocking operation. /// </summary> /// <typeparam name="T">The expected result type.</typeparam> /// <param name="context">The SQL context to run.</param> /// <param name="processor"> /// The query processor. If this value is null, a non-query type command /// is assumed and the integer type will be assumed. /// </param> /// <returns>An asynchronous task for the query result.</returns> private T RunCommand <T>(IContext context, IResultProcessor processor = null) { AssertCorrectReturnType <T>(processor); using (var connection = AsyncHelper.RunSync(() => CreateConnectionAsync())) { using (var command = connection.CreateCommand()) { // initialize command command.Connection = connection; command.CommandText = context.CommandText; AddParametersToCommand(command, context); object result; using (var scope = CreateScope(context)) { try { connection.Open(); if (processor == null) { result = command.ExecuteNonQuery(); } else { using (var reader = command.ExecuteReader()) { result = processor.Process(reader); } } connection.Close(); } catch { scope.Span.SetTag(Tags.Error, true); throw; } } return((T)result); } } }