/// <summary> /// Execute database command /// </summary> /// <param name="server">Database server</param> /// <param name="executionOptions">Execution options</param> /// <param name="databaseExecutionCommands">Database execution commands</param> /// <param name="useTransaction">Whether use transaction</param> /// <returns>Return affected data number</returns> async Task <int> ExecuteDatabaseCommandAsync(DatabaseServer server, CommandExecutionOptions executionOptions, IEnumerable <DatabaseExecutionCommand> databaseExecutionCommands, bool useTransaction) { int resultValue = 0; bool success = true; using (var conn = PostgreSqlManager.GetConnection(server)) { IDbTransaction transaction = null; if (useTransaction) { transaction = PostgreSqlManager.GetExecutionTransaction(conn, executionOptions); } try { foreach (var cmd in databaseExecutionCommands) { var cmdDefinition = new CommandDefinition(cmd.CommandText, PostgreSqlManager.ConvertCmdParameters(cmd.Parameters), transaction: transaction, commandType: cmd.CommandType, cancellationToken: executionOptions?.CancellationToken ?? default); var executeResultValue = await conn.ExecuteAsync(cmdDefinition).ConfigureAwait(false); success = success && (cmd.MustAffectedData ? executeResultValue > 0 : true); resultValue += executeResultValue; if (useTransaction && !success) { break; } } if (!useTransaction) { return(resultValue); } if (success) { transaction.Commit(); } else { resultValue = 0; transaction.Rollback(); } return(resultValue); } catch (Exception ex) { resultValue = 0; transaction?.Rollback(); throw ex; } } }