public async Task <int> ExecuteAsync(Dictionary <string, object> commands) { await using var conn = new MySqlConnection(_connectionString); await conn.OpenAsync(); await using var transaction = await conn.BeginTransactionAsync(); try { using var batch = conn.CreateBatch(); batch.Transaction = transaction; foreach (var(key, value) in commands) { var command = new MySqlBatchCommand(key); command.SetParameters(value); batch.BatchCommands.Add(command); } var result = await batch.ExecuteNonQueryAsync(); await transaction.CommitAsync(); return(result); } catch (Exception) { await transaction.RollbackAsync(); return(0); } }
public void CreateBatchDoesNotSetTransaction() { using var connection = new MySqlConnection(AppConfig.ConnectionString); connection.Open(); using var transaction = connection.BeginTransaction(); using var batch = connection.CreateBatch(); Assert.Null(batch.Transaction); }
public void IgnoreBatchTransactionIgnoresNull() { using var connection = new MySqlConnection(GetIgnoreCommandTransactionConnectionString()); connection.Open(); using var transaction = connection.BeginTransaction(); using var batch = connection.CreateBatch(); batch.BatchCommands.Add(new MySqlBatchCommand("SELECT 1;")); TestUtilities.AssertIsOne(batch.ExecuteScalar()); }
public void IgnoreCommandTransactionIgnoresDifferentTransaction() { using var connection1 = new MySqlConnection(AppConfig.ConnectionString); using var connection2 = new MySqlConnection(GetIgnoreCommandTransactionConnectionString()); connection1.Open(); connection2.Open(); using var transaction1 = connection1.BeginTransaction(); using var batch2 = connection2.CreateBatch(); batch2.Transaction = transaction1; batch2.BatchCommands.Add(new MySqlBatchCommand("SELECT 1;")); TestUtilities.AssertIsOne(batch2.ExecuteScalar()); }
public void BatchTransactionMustBeSet() { using var connection = new MySqlConnection(AppConfig.ConnectionString); connection.Open(); using var transaction = connection.BeginTransaction(); using var batch = connection.CreateBatch(); batch.BatchCommands.Add(new MySqlBatchCommand("SELECT 1;")); Assert.Throws <InvalidOperationException>(() => batch.ExecuteScalar()); batch.Transaction = transaction; TestUtilities.AssertIsOne(batch.ExecuteScalar()); }
public void IgnoreCommandTransactionIgnoresDisposedTransaction() { using (var connection = new MySqlConnection(GetIgnoreCommandTransactionConnectionString())) { connection.Open(); var transaction = connection.BeginTransaction(); transaction.Commit(); transaction.Dispose(); using (var batch = connection.CreateBatch()) { batch.BatchCommands.Add(new MySqlBatchCommand("SELECT 1;")); batch.Transaction = transaction; TestUtilities.AssertIsOne(batch.ExecuteScalar()); } } }