From 385254826f469cd7a8720d4d5ffabb6b951cb307 Mon Sep 17 00:00:00 2001 From: Bradley Grainger Date: Sat, 26 Jan 2019 09:29:02 -0800 Subject: [PATCH] Use C# 8 using declarations. --- .../Ed25519AuthenticationPlugin.cs | 184 ++- src/MySqlConnector/Core/CachedProcedure.cs | 83 +- src/MySqlConnector/Core/CommandExecutor.cs | 40 +- src/MySqlConnector/Core/ConnectionPool.cs | 4 +- src/MySqlConnector/Core/ResultSet.cs | 28 +- src/MySqlConnector/Core/SchemaProvider.cs | 12 +- src/MySqlConnector/Core/ServerSession.cs | 54 +- .../Core/StandardEnlistedTransaction.cs | 12 +- .../Core/XaEnlistedTransaction.cs | 8 +- .../MySql.Data.MySqlClient/MySqlBatch.cs | 34 +- .../MySql.Data.MySqlClient/MySqlCommand.cs | 34 +- .../MySql.Data.MySqlClient/MySqlConnection.cs | 12 +- .../MySql.Data.MySqlClient/MySqlDataReader.cs | 12 +- .../MySqlTransaction.cs | 2 +- .../Protocol/Serialization/AuthGSSAPI.cs | 50 +- .../Serialization/AuthenticationUtility.cs | 48 +- .../Serialization/CompressedPayloadHandler.cs | 67 +- .../Conformance.Tests.csproj | 1 + tests/Conformance.Tests/SelectValueFixture.cs | 16 +- tests/MySqlConnector.Tests/ConnectionTests.cs | 62 +- .../FakeMySqlServerConnection.cs | 16 +- .../MySqlConnector.Tests.csproj | 1 + .../StatementPreparerTests.cs | 48 +- tests/SideBySide/BatchTests.cs | 336 +++--- tests/SideBySide/BulkLoaderAsync.cs | 563 +++++---- tests/SideBySide/BulkLoaderSync.cs | 661 +++++------ tests/SideBySide/CancelTests.cs | 860 +++++++------- tests/SideBySide/CharacterSetTests.cs | 68 +- tests/SideBySide/CommandBuilderTests.cs | 24 +- tests/SideBySide/CommandTests.cs | 304 ++--- tests/SideBySide/CommandTimeoutTests.cs | 183 ++- tests/SideBySide/ConnectAsync.cs | 304 ++--- tests/SideBySide/ConnectSync.cs | 354 +++--- tests/SideBySide/ConnectionPool.cs | 62 +- tests/SideBySide/ConnectionTests.cs | 128 +- tests/SideBySide/DataAdapterTests.cs | 150 ++- tests/SideBySide/DataTypes.cs | 1040 ++++++++--------- tests/SideBySide/InsertTests.cs | 165 ++- tests/SideBySide/PreparedCommandTests.cs | 381 +++--- tests/SideBySide/QueryTests.cs | 803 ++++++------- tests/SideBySide/SideBySide.csproj | 3 +- tests/SideBySide/SslTests.cs | 118 +- tests/SideBySide/StoredProcedureTests.cs | 679 +++++------ tests/SideBySide/TransactionScopeTests.cs | 243 ++-- tests/SideBySide/UpdateTests.cs | 10 +- 45 files changed, 3694 insertions(+), 4573 deletions(-) diff --git a/src/MySqlConnector.Authentication.Ed25519/Ed25519AuthenticationPlugin.cs b/src/MySqlConnector.Authentication.Ed25519/Ed25519AuthenticationPlugin.cs index 80a95770b..263ea9ca7 100644 --- a/src/MySqlConnector.Authentication.Ed25519/Ed25519AuthenticationPlugin.cs +++ b/src/MySqlConnector.Authentication.Ed25519/Ed25519AuthenticationPlugin.cs @@ -58,99 +58,97 @@ public byte[] CreateResponse(string password, ReadOnlySpan authenticationD az[31] |= 64; */ - using (var sha512 = SHA512.Create()) - { - byte[] az = sha512.ComputeHash(passwordBytes); - ScalarOperations.sc_clamp(az, 0); - - /*** Java - int mlen = seed.length; - final byte[] sm = new byte[64 + mlen]; - - System.arraycopy(seed, 0, sm, 64, mlen); - System.arraycopy(az, 32, sm, 32, 32); - - byte[] buff = Arrays.copyOfRange(sm, 32, 96); - hash.reset(); - byte[] nonce = hash.digest(buff); - */ - /*** C - unsigned char nonce[64]; - unsigned char hram[64]; - - memmove(sm + 64,m,mlen); - memmove(sm + 32,az + 32,32); - crypto_hash_sha512(nonce,sm + 32,mlen + 32); - */ - - byte[] sm = new byte[64 + authenticationData.Length]; - authenticationData.CopyTo(sm.AsSpan().Slice(64)); - Buffer.BlockCopy(az, 32, sm, 32, 32); - byte[] nonce = sha512.ComputeHash(sm, 32, authenticationData.Length + 32); - - /*** Java - ScalarOps scalar = new ScalarOps(); - - EdDSAParameterSpec spec = EdDSANamedCurveTable.getByName("Ed25519"); - GroupElement elementAvalue = spec.getB().scalarMultiply(az); - byte[] elementAarray = elementAvalue.toByteArray(); - System.arraycopy(elementAarray, 0, sm, 32, elementAarray.length); - */ - /*** C - ge_p3 A; - - ge_scalarmult_base(&A,az); - ge_p3_tobytes(sm + 32,&A); - */ - - GroupOperations.ge_scalarmult_base(out var A, az, 0); - GroupOperations.ge_p3_tobytes(sm, 32, ref A); - - /*** Java - nonce = scalar.reduce(nonce); - GroupElement elementRvalue = spec.getB().scalarMultiply(nonce); - byte[] elementRarray = elementRvalue.toByteArray(); - System.arraycopy(elementRarray, 0, sm, 0, elementRarray.length); - */ - /*** C - ge_p3 R; - - sc_reduce(nonce); - ge_scalarmult_base(&R,nonce); - ge_p3_tobytes(sm,&R); - */ - ScalarOperations.sc_reduce(nonce); - GroupOperations.ge_scalarmult_base(out var R, nonce, 0); - GroupOperations.ge_p3_tobytes(sm, 0, ref R); - - /*** Java - hash.reset(); - byte[] hram = hash.digest(sm); - hram = scalar.reduce(hram); - byte[] tt = scalar.multiplyAndAdd(hram, az, nonce); - System.arraycopy(tt, 0, sm, 32, tt.length); - - return Arrays.copyOfRange(sm, 0, 64); - */ - /*** C - unsigned char hram[64]; - - crypto_hash_sha512(hram,sm,mlen + 64); - sc_reduce(hram); - sc_muladd(sm + 32,hram,az,nonce); - - return 0; - */ - var hram = sha512.ComputeHash(sm); - ScalarOperations.sc_reduce(hram); - var temp = new byte[32]; - ScalarOperations.sc_muladd(temp, hram, az, nonce); - Buffer.BlockCopy(temp, 0, sm, 32, temp.Length); - - var result = new byte[64]; - Buffer.BlockCopy(sm, 0, result, 0, result.Length); - return result; - } + using var sha512 = SHA512.Create(); + byte[] az = sha512.ComputeHash(passwordBytes); + ScalarOperations.sc_clamp(az, 0); + + /*** Java + int mlen = seed.length; + final byte[] sm = new byte[64 + mlen]; + + System.arraycopy(seed, 0, sm, 64, mlen); + System.arraycopy(az, 32, sm, 32, 32); + + byte[] buff = Arrays.copyOfRange(sm, 32, 96); + hash.reset(); + byte[] nonce = hash.digest(buff); + */ + /*** C + unsigned char nonce[64]; + unsigned char hram[64]; + + memmove(sm + 64,m,mlen); + memmove(sm + 32,az + 32,32); + crypto_hash_sha512(nonce,sm + 32,mlen + 32); + */ + + byte[] sm = new byte[64 + authenticationData.Length]; + authenticationData.CopyTo(sm.AsSpan().Slice(64)); + Buffer.BlockCopy(az, 32, sm, 32, 32); + byte[] nonce = sha512.ComputeHash(sm, 32, authenticationData.Length + 32); + + /*** Java + ScalarOps scalar = new ScalarOps(); + + EdDSAParameterSpec spec = EdDSANamedCurveTable.getByName("Ed25519"); + GroupElement elementAvalue = spec.getB().scalarMultiply(az); + byte[] elementAarray = elementAvalue.toByteArray(); + System.arraycopy(elementAarray, 0, sm, 32, elementAarray.length); + */ + /*** C + ge_p3 A; + + ge_scalarmult_base(&A,az); + ge_p3_tobytes(sm + 32,&A); + */ + + GroupOperations.ge_scalarmult_base(out var A, az, 0); + GroupOperations.ge_p3_tobytes(sm, 32, ref A); + + /*** Java + nonce = scalar.reduce(nonce); + GroupElement elementRvalue = spec.getB().scalarMultiply(nonce); + byte[] elementRarray = elementRvalue.toByteArray(); + System.arraycopy(elementRarray, 0, sm, 0, elementRarray.length); + */ + /*** C + ge_p3 R; + + sc_reduce(nonce); + ge_scalarmult_base(&R,nonce); + ge_p3_tobytes(sm,&R); + */ + ScalarOperations.sc_reduce(nonce); + GroupOperations.ge_scalarmult_base(out var R, nonce, 0); + GroupOperations.ge_p3_tobytes(sm, 0, ref R); + + /*** Java + hash.reset(); + byte[] hram = hash.digest(sm); + hram = scalar.reduce(hram); + byte[] tt = scalar.multiplyAndAdd(hram, az, nonce); + System.arraycopy(tt, 0, sm, 32, tt.length); + + return Arrays.copyOfRange(sm, 0, 64); + */ + /*** C + unsigned char hram[64]; + + crypto_hash_sha512(hram,sm,mlen + 64); + sc_reduce(hram); + sc_muladd(sm + 32,hram,az,nonce); + + return 0; + */ + var hram = sha512.ComputeHash(sm); + ScalarOperations.sc_reduce(hram); + var temp = new byte[32]; + ScalarOperations.sc_muladd(temp, hram, az, nonce); + Buffer.BlockCopy(temp, 0, sm, 32, temp.Length); + + var result = new byte[64]; + Buffer.BlockCopy(sm, 0, result, 0, result.Length); + return result; } private Ed25519AuthenticationPlugin() diff --git a/src/MySqlConnector/Core/CachedProcedure.cs b/src/MySqlConnector/Core/CachedProcedure.cs index 11246d6cb..8b6a0e34a 100644 --- a/src/MySqlConnector/Core/CachedProcedure.cs +++ b/src/MySqlConnector/Core/CachedProcedure.cs @@ -23,35 +23,32 @@ internal sealed class CachedProcedure { try { - using (var cmd = connection.CreateCommand()) + using var cmd = connection.CreateCommand(); + cmd.Transaction = connection.CurrentTransaction; + cmd.CommandText = @"SELECT param_list, returns FROM mysql.proc WHERE db = @schema AND name = @component"; + cmd.Parameters.AddWithValue("@schema", schema); + cmd.Parameters.AddWithValue("@component", component); + + using var reader = (MySqlDataReader) await cmd.ExecuteReaderAsync(CommandBehavior.Default, ioBehavior, cancellationToken).ConfigureAwait(false); + var exists = await reader.ReadAsync(cancellationToken).ConfigureAwait(false); + if (!exists) + return null; + + var parametersSqlBytes = (byte[]) reader.GetValue(0); + var returnsSqlBytes = (byte[]) reader.GetValue(1); + + // ASSUME this is UTF-8 encoded; it's possible that the `character_set_client` column would need to be used? + var parametersSql = Encoding.UTF8.GetString(parametersSqlBytes); + var returnsSql = Encoding.UTF8.GetString(returnsSqlBytes); + + var parsedParameters = ParseParameters(parametersSql); + if (returnsSql.Length != 0) { - cmd.Transaction = connection.CurrentTransaction; - cmd.CommandText = @"SELECT param_list, returns FROM mysql.proc WHERE db = @schema AND name = @component"; - cmd.Parameters.AddWithValue("@schema", schema); - cmd.Parameters.AddWithValue("@component", component); - using (var reader = (MySqlDataReader) await cmd.ExecuteReaderAsync(CommandBehavior.Default, ioBehavior, cancellationToken).ConfigureAwait(false)) - { - var exists = await reader.ReadAsync(cancellationToken).ConfigureAwait(false); - if (!exists) - return null; - - var parametersSqlBytes = (byte[]) reader.GetValue(0); - var returnsSqlBytes = (byte[]) reader.GetValue(1); - - // ASSUME this is UTF-8 encoded; it's possible that the `character_set_client` column would need to be used? - var parametersSql = Encoding.UTF8.GetString(parametersSqlBytes); - var returnsSql = Encoding.UTF8.GetString(returnsSqlBytes); - - var parsedParameters = ParseParameters(parametersSql); - if (returnsSql.Length != 0) - { - var returnDataType = ParseDataType(returnsSql, out var unsigned, out var length); - parsedParameters.Insert(0, CreateCachedParameter(0, null, null, returnDataType, unsigned, length, returnsSql)); - } - - return new CachedProcedure(schema, component, parsedParameters); - } + var returnDataType = ParseDataType(returnsSql, out var unsigned, out var length); + parsedParameters.Insert(0, CreateCachedParameter(0, null, null, returnDataType, unsigned, length, returnsSql)); } + + return new CachedProcedure(schema, component, parsedParameters); } catch (MySqlException ex) { @@ -82,24 +79,22 @@ FROM information_schema.parameters cmd.Parameters.AddWithValue("@schema", schema); cmd.Parameters.AddWithValue("@component", component); - using (var reader = (MySqlDataReader) await cmd.ExecuteReaderAsync(CommandBehavior.Default, ioBehavior, cancellationToken).ConfigureAwait(false)) - { - await reader.ReadAsync(cancellationToken).ConfigureAwait(false); - routineCount = reader.GetInt32(0); - await reader.NextResultAsync(cancellationToken).ConfigureAwait(false); + using var reader = (MySqlDataReader) await cmd.ExecuteReaderAsync(CommandBehavior.Default, ioBehavior, cancellationToken).ConfigureAwait(false); + await reader.ReadAsync(cancellationToken).ConfigureAwait(false); + routineCount = reader.GetInt32(0); + await reader.NextResultAsync(cancellationToken).ConfigureAwait(false); - while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) - { - var dataType = ParseDataType(reader.GetString(3), out var unsigned, out var length); - parameters.Add(new CachedParameter( - reader.GetInt32(0), - !reader.IsDBNull(1) ? reader.GetString(1) : null, - !reader.IsDBNull(2) ? reader.GetString(2) : null, - dataType, - unsigned, - length - )); - } + while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) + { + var dataType = ParseDataType(reader.GetString(3), out var unsigned, out var length); + parameters.Add(new CachedParameter( + reader.GetInt32(0), + !reader.IsDBNull(1) ? reader.GetString(1) : null, + !reader.IsDBNull(2) ? reader.GetString(2) : null, + dataType, + unsigned, + length + )); } } diff --git a/src/MySqlConnector/Core/CommandExecutor.cs b/src/MySqlConnector/Core/CommandExecutor.cs index 024886aec..202034c6f 100644 --- a/src/MySqlConnector/Core/CommandExecutor.cs +++ b/src/MySqlConnector/Core/CommandExecutor.cs @@ -53,28 +53,26 @@ public static async Task ExecuteReaderAsync(IReadOnlyList 4_194_304 && (ex is SocketException || ex is IOException || ex is MySqlProtocolException)) - { - // the default MySQL Server value for max_allowed_packet (in MySQL 5.7) is 4MiB: https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_max_allowed_packet - // use "decimal megabytes" (to round up) when creating the exception message - int megabytes = payload.Span.Length / 1_000_000; - throw new MySqlException("Error submitting {0}MB packet; ensure 'max_allowed_packet' is greater than {0}MB.".FormatInvariant(megabytes), ex); - } + await connection.Session.SendAsync(payload, ioBehavior, CancellationToken.None).ConfigureAwait(false); + return await MySqlDataReader.CreateAsync(commandListPosition, payloadCreator, cachedProcedures, command, behavior, ioBehavior, cancellationToken).ConfigureAwait(false); + } + catch (MySqlException ex) when (ex.Number == (int) MySqlErrorCode.QueryInterrupted && cancellationToken.IsCancellationRequested) + { + Log.Warn("Session{0} query was interrupted", connection.Session.Id); + throw new OperationCanceledException(cancellationToken); + } + catch (Exception ex) when (payload.Span.Length > 4_194_304 && (ex is SocketException || ex is IOException || ex is MySqlProtocolException)) + { + // the default MySQL Server value for max_allowed_packet (in MySQL 5.7) is 4MiB: https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_max_allowed_packet + // use "decimal megabytes" (to round up) when creating the exception message + int megabytes = payload.Span.Length / 1_000_000; + throw new MySqlException("Error submitting {0}MB packet; ensure 'max_allowed_packet' is greater than {0}MB.".FormatInvariant(megabytes), ex); } } diff --git a/src/MySqlConnector/Core/ConnectionPool.cs b/src/MySqlConnector/Core/ConnectionPool.cs index 162731d3f..6f9005125 100644 --- a/src/MySqlConnector/Core/ConnectionPool.cs +++ b/src/MySqlConnector/Core/ConnectionPool.cs @@ -475,8 +475,8 @@ private void StartReaperTask() var task = Task.Delay(reaperInterval); try { - using (var source = new CancellationTokenSource(reaperInterval)) - await ReapAsync(IOBehavior.Asynchronous, source.Token).ConfigureAwait(false); + using var source = new CancellationTokenSource(reaperInterval); + await ReapAsync(IOBehavior.Asynchronous, source.Token).ConfigureAwait(false); } catch { diff --git a/src/MySqlConnector/Core/ResultSet.cs b/src/MySqlConnector/Core/ResultSet.cs index 4f832dad5..a4b117bc5 100644 --- a/src/MySqlConnector/Core/ResultSet.cs +++ b/src/MySqlConnector/Core/ResultSet.cs @@ -76,17 +76,15 @@ public async Task ReadResultSetHeaderAsync(IOBehavior ioBehavior) && !localInfile.FileName.StartsWith(MySqlBulkLoader.StreamPrefix, StringComparison.Ordinal)) throw new NotSupportedException("Use SourceStream or SslMode >= VerifyCA for LOAD DATA LOCAL INFILE. See https://fl.vu/mysql-load-data"); - using (var stream = localInfile.FileName.StartsWith(MySqlBulkLoader.StreamPrefix, StringComparison.Ordinal) ? + using var stream = localInfile.FileName.StartsWith(MySqlBulkLoader.StreamPrefix, StringComparison.Ordinal) ? MySqlBulkLoader.GetAndRemoveStream(localInfile.FileName) : - File.OpenRead(localInfile.FileName)) + File.OpenRead(localInfile.FileName); + var readBuffer = new byte[65536]; + int byteCount; + while ((byteCount = await stream.ReadAsync(readBuffer, 0, readBuffer.Length).ConfigureAwait(false)) > 0) { - byte[] readBuffer = new byte[65536]; - int byteCount; - while ((byteCount = await stream.ReadAsync(readBuffer, 0, readBuffer.Length).ConfigureAwait(false)) > 0) - { - payload = new PayloadData(new ArraySegment(readBuffer, 0, byteCount)); - await Session.SendReplyAsync(payload, ioBehavior, CancellationToken.None).ConfigureAwait(false); - } + payload = new PayloadData(new ArraySegment(readBuffer, 0, byteCount)); + await Session.SendReplyAsync(payload, ioBehavior, CancellationToken.None).ConfigureAwait(false); } } catch (Exception ex) @@ -213,13 +211,11 @@ public async Task ReadAsync(IOBehavior ioBehavior, CancellationToken cance if (BufferState == ResultSetState.HasMoreData || BufferState == ResultSetState.NoMoreData || BufferState == ResultSetState.None) return new ValueTask(default(Row?)); - using (Command.CancellableCommand.RegisterCancel(cancellationToken)) - { - var payloadValueTask = Session.ReceiveReplyAsync(ioBehavior, CancellationToken.None); - return payloadValueTask.IsCompletedSuccessfully - ? new ValueTask(ScanRowAsyncRemainder(this, payloadValueTask.Result, row)) - : new ValueTask(ScanRowAsyncAwaited(this, payloadValueTask.AsTask(), row, cancellationToken)); - } + using var registration = Command.CancellableCommand.RegisterCancel(cancellationToken); + var payloadValueTask = Session.ReceiveReplyAsync(ioBehavior, CancellationToken.None); + return payloadValueTask.IsCompletedSuccessfully + ? new ValueTask(ScanRowAsyncRemainder(this, payloadValueTask.Result, row)) + : new ValueTask(ScanRowAsyncAwaited(this, payloadValueTask.AsTask(), row, cancellationToken)); static async Task ScanRowAsyncAwaited(ResultSet this_, Task payloadTask, Row? row_, CancellationToken token) { diff --git a/src/MySqlConnector/Core/SchemaProvider.cs b/src/MySqlConnector/Core/SchemaProvider.cs index 4534fac88..557f21da8 100644 --- a/src/MySqlConnector/Core/SchemaProvider.cs +++ b/src/MySqlConnector/Core/SchemaProvider.cs @@ -166,14 +166,12 @@ private void FillProcedures(DataTable dataTable) using (var command = m_connection.CreateCommand()) { command.CommandText = "SELECT " + string.Join(", ", dataTable.Columns.Cast().Select(x => x.ColumnName)) + " FROM INFORMATION_SCHEMA.ROUTINES;"; - using (var reader = command.ExecuteReader()) + using var reader = command.ExecuteReader(); + while (reader.Read()) { - while (reader.Read()) - { - var rowValues = new object[dataTable.Columns.Count]; - reader.GetValues(rowValues); - dataTable.Rows.Add(rowValues); - } + var rowValues = new object[dataTable.Columns.Count]; + reader.GetValues(rowValues); + dataTable.Rows.Add(rowValues); } } diff --git a/src/MySqlConnector/Core/ServerSession.cs b/src/MySqlConnector/Core/ServerSession.cs index 6e58ca288..d163de445 100644 --- a/src/MySqlConnector/Core/ServerSession.cs +++ b/src/MySqlConnector/Core/ServerSession.cs @@ -630,22 +630,20 @@ private async Task SendEncryptedPasswordAsync( var passwordBytes = Encoding.UTF8.GetBytes(cs.Password); Array.Resize(ref passwordBytes, passwordBytes.Length + 1); - using (var rsa = RSA.Create()) - { - rsa.ImportParameters(rsaParameters); - - // XOR the password bytes with the challenge - AuthPluginData = Utility.TrimZeroByte(switchRequest.Data); - for (var i = 0; i < passwordBytes.Length; i++) - passwordBytes[i] ^= AuthPluginData[i % AuthPluginData.Length]; - - // encrypt with RSA public key - var padding = RSAEncryptionPadding.OaepSHA1; - var encryptedPassword = rsa.Encrypt(passwordBytes, padding); - var payload = new PayloadData(encryptedPassword); - await SendReplyAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false); - return await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false); - } + using var rsa = RSA.Create(); + rsa.ImportParameters(rsaParameters); + + // XOR the password bytes with the challenge + AuthPluginData = Utility.TrimZeroByte(switchRequest.Data); + for (var i = 0; i < passwordBytes.Length; i++) + passwordBytes[i] ^= AuthPluginData[i % AuthPluginData.Length]; + + // encrypt with RSA public key + var padding = RSAEncryptionPadding.OaepSHA1; + var encryptedPassword = rsa.Encrypt(passwordBytes, padding); + var payload = new PayloadData(encryptedPassword); + await SendReplyAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false); + return await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false); } #endif @@ -1477,25 +1475,21 @@ private byte[] CreateConnectionAttributes(string programName) catch (PlatformNotSupportedException) { } - using (var process = Process.GetCurrentProcess()) - { - attributesWriter.WriteLengthEncodedString("_pid"); - attributesWriter.WriteLengthEncodedString(process.Id.ToString(CultureInfo.InvariantCulture)); - } + using var process = Process.GetCurrentProcess(); + attributesWriter.WriteLengthEncodedString("_pid"); + attributesWriter.WriteLengthEncodedString(process.Id.ToString(CultureInfo.InvariantCulture)); if (!string.IsNullOrEmpty(programName)) { attributesWriter.WriteLengthEncodedString("program_name"); attributesWriter.WriteLengthEncodedString(programName); } - using (var connectionAttributesPayload = attributesWriter.ToPayloadData()) - { - var connectionAttributes = connectionAttributesPayload.Span; - var writer = new ByteBufferWriter(connectionAttributes.Length + 9); - writer.WriteLengthEncodedInteger((ulong) connectionAttributes.Length); - writer.Write(connectionAttributes); - using (var payload = writer.ToPayloadData()) - return payload.Memory.ToArray(); - } + using var connectionAttributesPayload = attributesWriter.ToPayloadData(); + var connectionAttributes = connectionAttributesPayload.Span; + var writer = new ByteBufferWriter(connectionAttributes.Length + 9); + writer.WriteLengthEncodedInteger((ulong) connectionAttributes.Length); + writer.Write(connectionAttributes); + using var payload = writer.ToPayloadData(); + return payload.Memory.ToArray(); } private Exception CreateExceptionForErrorPayload(ReadOnlySpan span) diff --git a/src/MySqlConnector/Core/StandardEnlistedTransaction.cs b/src/MySqlConnector/Core/StandardEnlistedTransaction.cs index b0994a035..40b61cac2 100644 --- a/src/MySqlConnector/Core/StandardEnlistedTransaction.cs +++ b/src/MySqlConnector/Core/StandardEnlistedTransaction.cs @@ -29,8 +29,8 @@ protected override void OnStart() _ => "repeatable read", }; - using (var cmd = new MySqlCommand("set transaction isolation level " + isolationLevel + "; start transaction;", Connection)) - cmd.ExecuteNonQuery(); + using var cmd = new MySqlCommand("set transaction isolation level " + isolationLevel + "; start transaction;", Connection); + cmd.ExecuteNonQuery(); } protected override void OnPrepare(PreparingEnlistment enlistment) @@ -39,14 +39,14 @@ protected override void OnPrepare(PreparingEnlistment enlistment) protected override void OnCommit(Enlistment enlistment) { - using (var cmd = new MySqlCommand("commit;", Connection)) - cmd.ExecuteNonQuery(); + using var cmd = new MySqlCommand("commit;", Connection); + cmd.ExecuteNonQuery(); } protected override void OnRollback(Enlistment enlistment) { - using (var cmd = new MySqlCommand("rollback;", Connection)) - cmd.ExecuteNonQuery(); + using var cmd = new MySqlCommand("rollback;", Connection); + cmd.ExecuteNonQuery(); } } } diff --git a/src/MySqlConnector/Core/XaEnlistedTransaction.cs b/src/MySqlConnector/Core/XaEnlistedTransaction.cs index 8ae970b65..a71dfacdc 100644 --- a/src/MySqlConnector/Core/XaEnlistedTransaction.cs +++ b/src/MySqlConnector/Core/XaEnlistedTransaction.cs @@ -44,11 +44,9 @@ protected override void OnRollback(Enlistment enlistment) private void ExecuteXaCommand(string statement) { - using (var cmd = Connection.CreateCommand()) - { - cmd.CommandText = "XA " + statement + " " + m_xid; - cmd.ExecuteNonQuery(); - } + using var cmd = Connection.CreateCommand(); + cmd.CommandText = "XA " + statement + " " + m_xid; + cmd.ExecuteNonQuery(); } static int s_currentId; diff --git a/src/MySqlConnector/MySql.Data.MySqlClient/MySqlBatch.cs b/src/MySqlConnector/MySql.Data.MySqlClient/MySqlBatch.cs index e32fc615a..26c41203b 100644 --- a/src/MySqlConnector/MySql.Data.MySqlClient/MySqlBatch.cs +++ b/src/MySqlConnector/MySql.Data.MySqlClient/MySqlBatch.cs @@ -106,16 +106,14 @@ IDisposable ICancellableCommand.RegisterCancel(CancellationToken token) private async Task ExecuteNonQueryAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) { ((ICancellableCommand) this).ResetCommandTimeout(); - using (var reader = (MySqlDataReader) await ExecuteReaderAsync(ioBehavior, cancellationToken).ConfigureAwait(false)) + using var reader = (MySqlDataReader) await ExecuteReaderAsync(ioBehavior, cancellationToken).ConfigureAwait(false); + do { - do + while (await reader.ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false)) { - while (await reader.ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false)) - { - } - } while (await reader.NextResultAsync(ioBehavior, cancellationToken).ConfigureAwait(false)); - return reader.RecordsAffected; - } + } + } while (await reader.NextResultAsync(ioBehavior, cancellationToken).ConfigureAwait(false)); + return reader.RecordsAffected; } private async Task ExecuteScalarAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) @@ -123,19 +121,17 @@ private async Task ExecuteScalarAsync(IOBehavior ioBehavior, Cancellatio ((ICancellableCommand) this).ResetCommandTimeout(); var hasSetResult = false; object result = null; - using (var reader = (MySqlDataReader) await ExecuteReaderAsync(ioBehavior, cancellationToken).ConfigureAwait(false)) + using var reader = (MySqlDataReader) await ExecuteReaderAsync(ioBehavior, cancellationToken).ConfigureAwait(false); + do { - do + var hasResult = await reader.ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false); + if (!hasSetResult) { - var hasResult = await reader.ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false); - if (!hasSetResult) - { - if (hasResult) - result = reader.GetValue(0); - hasSetResult = true; - } - } while (await reader.NextResultAsync(ioBehavior, cancellationToken).ConfigureAwait(false)); - } + if (hasResult) + result = reader.GetValue(0); + hasSetResult = true; + } + } while (await reader.NextResultAsync(ioBehavior, cancellationToken).ConfigureAwait(false)); return result; } diff --git a/src/MySqlConnector/MySql.Data.MySqlClient/MySqlCommand.cs b/src/MySqlConnector/MySql.Data.MySqlClient/MySqlCommand.cs index 7961f1350..7c13e9e7e 100644 --- a/src/MySqlConnector/MySql.Data.MySqlClient/MySqlCommand.cs +++ b/src/MySqlConnector/MySql.Data.MySqlClient/MySqlCommand.cs @@ -224,16 +224,14 @@ public override Task ExecuteNonQueryAsync(CancellationToken cancellationTok internal async Task ExecuteNonQueryAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) { this.ResetCommandTimeout(); - using (var reader = (MySqlDataReader) await ExecuteReaderAsync(CommandBehavior.Default, ioBehavior, cancellationToken).ConfigureAwait(false)) + using var reader = (MySqlDataReader) await ExecuteReaderAsync(CommandBehavior.Default, ioBehavior, cancellationToken).ConfigureAwait(false); + do { - do + while (await reader.ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false)) { - while (await reader.ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false)) - { - } - } while (await reader.NextResultAsync(ioBehavior, cancellationToken).ConfigureAwait(false)); - return reader.RecordsAffected; - } + } + } while (await reader.NextResultAsync(ioBehavior, cancellationToken).ConfigureAwait(false)); + return reader.RecordsAffected; } public override Task ExecuteScalarAsync(CancellationToken cancellationToken) => @@ -244,19 +242,17 @@ internal async Task ExecuteScalarAsync(IOBehavior ioBehavior, Cancellati this.ResetCommandTimeout(); var hasSetResult = false; object result = null; - using (var reader = (MySqlDataReader) await ExecuteReaderAsync(CommandBehavior.Default, ioBehavior, cancellationToken).ConfigureAwait(false)) + using var reader = (MySqlDataReader) await ExecuteReaderAsync(CommandBehavior.Default, ioBehavior, cancellationToken).ConfigureAwait(false); + do { - do + var hasResult = await reader.ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false); + if (!hasSetResult) { - var hasResult = await reader.ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false); - if (!hasSetResult) - { - if (hasResult) - result = reader.GetValue(0); - hasSetResult = true; - } - } while (await reader.NextResultAsync(ioBehavior, cancellationToken).ConfigureAwait(false)); - } + if (hasResult) + result = reader.GetValue(0); + hasSetResult = true; + } + } while (await reader.NextResultAsync(ioBehavior, cancellationToken).ConfigureAwait(false)); return result; } diff --git a/src/MySqlConnector/MySql.Data.MySqlClient/MySqlConnection.cs b/src/MySqlConnector/MySql.Data.MySqlClient/MySqlConnection.cs index 65b1122d0..2bdd10413 100644 --- a/src/MySqlConnector/MySql.Data.MySqlClient/MySqlConnection.cs +++ b/src/MySqlConnector/MySql.Data.MySqlClient/MySqlConnection.cs @@ -466,14 +466,10 @@ internal void Cancel(ICancellableCommand command) csb.Server = m_session.IPAddress.ToString(); csb.ConnectionTimeout = 3u; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); - using (var killCommand = new MySqlCommand("KILL QUERY {0}".FormatInvariant(command.Connection.ServerThread), connection)) - { - session.DoCancel(command, killCommand); - } - } + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); + using var killCommand = new MySqlCommand("KILL QUERY {0}".FormatInvariant(command.Connection.ServerThread), connection); + session.DoCancel(command, killCommand); } catch (MySqlException ex) { diff --git a/src/MySqlConnector/MySql.Data.MySqlClient/MySqlDataReader.cs b/src/MySqlConnector/MySql.Data.MySqlClient/MySqlDataReader.cs index a3cf430b2..866e8680e 100644 --- a/src/MySqlConnector/MySql.Data.MySqlClient/MySqlDataReader.cs +++ b/src/MySqlConnector/MySql.Data.MySqlClient/MySqlDataReader.cs @@ -74,13 +74,11 @@ internal async Task NextResultAsync(IOBehavior ioBehavior, CancellationTok var writer = new ByteBufferWriter(); if (!Command.Connection.Session.IsCancelingQuery && m_payloadCreator.WriteQueryCommand(ref m_commandListPosition, m_cachedProcedures, writer)) { - using (var payload = writer.ToPayloadData()) - { - await Command.Connection.Session.SendAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false); - await m_resultSet.ReadResultSetHeaderAsync(ioBehavior).ConfigureAwait(false); - ActivateResultSet(); - m_hasMoreResults = true; - } + using var payload = writer.ToPayloadData(); + await Command.Connection.Session.SendAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false); + await m_resultSet.ReadResultSetHeaderAsync(ioBehavior).ConfigureAwait(false); + ActivateResultSet(); + m_hasMoreResults = true; } } } diff --git a/src/MySqlConnector/MySql.Data.MySqlClient/MySqlTransaction.cs b/src/MySqlConnector/MySql.Data.MySqlClient/MySqlTransaction.cs index 3ebb6bc8c..914086b2b 100644 --- a/src/MySqlConnector/MySql.Data.MySqlClient/MySqlTransaction.cs +++ b/src/MySqlConnector/MySql.Data.MySqlClient/MySqlTransaction.cs @@ -80,7 +80,7 @@ protected override void Dispose(bool disposing) try { if (disposing) - DisposeAsync(IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult(); + DisposeAsync(IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult(); } finally { diff --git a/src/MySqlConnector/Protocol/Serialization/AuthGSSAPI.cs b/src/MySqlConnector/Protocol/Serialization/AuthGSSAPI.cs index 8e51a6b11..f149b673d 100644 --- a/src/MySqlConnector/Protocol/Serialization/AuthGSSAPI.cs +++ b/src/MySqlConnector/Protocol/Serialization/AuthGSSAPI.cs @@ -217,36 +217,34 @@ private static string GetServicePrincipalName(byte[] switchRequest) public static async Task AuthenticateAsync(ConnectionSettings cs, byte[] switchRequestPayloadData, ServerSession session, IOBehavior ioBehavior, CancellationToken cancellationToken) { - using (var innerStream = new NegotiateToMySqlConverterStream(session, ioBehavior, cancellationToken)) - using (var negotiateStream = new NegotiateStream(innerStream)) - { - var targetName =cs.ServerSPN ?? GetServicePrincipalName(switchRequestPayloadData); + using var innerStream = new NegotiateToMySqlConverterStream(session, ioBehavior, cancellationToken); + using var negotiateStream = new NegotiateStream(innerStream); + var targetName =cs.ServerSPN ?? GetServicePrincipalName(switchRequestPayloadData); #if NETSTANDARD1_3 - await negotiateStream.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, targetName).ConfigureAwait(false); + await negotiateStream.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, targetName).ConfigureAwait(false); #else - if (ioBehavior == IOBehavior.Synchronous) - { - negotiateStream.AuthenticateAsClient(CredentialCache.DefaultNetworkCredentials, targetName); - } - else - { - await negotiateStream.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, targetName).ConfigureAwait(false); - } + if (ioBehavior == IOBehavior.Synchronous) + { + negotiateStream.AuthenticateAsClient(CredentialCache.DefaultNetworkCredentials, targetName); + } + else + { + await negotiateStream.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, targetName).ConfigureAwait(false); + } #endif - if (cs.ServerSPN is object && !negotiateStream.IsMutuallyAuthenticated) - { - // Negotiate used NTLM fallback, server name cannot be verified. - throw new AuthenticationException(String.Format( - "GSSAPI : Unable to verify server principal name using authentication type {0}", - negotiateStream.RemoteIdentity?.AuthenticationType)); - } - if (innerStream.MySQLProtocolPayload is PayloadData payload) - // return already pre-read OK packet. - return payload; - - // Read final OK packet from server - return await session.ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false); + if (cs.ServerSPN is object && !negotiateStream.IsMutuallyAuthenticated) + { + // Negotiate used NTLM fallback, server name cannot be verified. + throw new AuthenticationException(String.Format( + "GSSAPI : Unable to verify server principal name using authentication type {0}", + negotiateStream.RemoteIdentity?.AuthenticationType)); } + if (innerStream.MySQLProtocolPayload is PayloadData payload) + // return already pre-read OK packet. + return payload; + + // Read final OK packet from server + return await session.ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false); } } } diff --git a/src/MySqlConnector/Protocol/Serialization/AuthenticationUtility.cs b/src/MySqlConnector/Protocol/Serialization/AuthenticationUtility.cs index 13c2c0d70..8d886d8b3 100644 --- a/src/MySqlConnector/Protocol/Serialization/AuthenticationUtility.cs +++ b/src/MySqlConnector/Protocol/Serialization/AuthenticationUtility.cs @@ -20,23 +20,21 @@ public static byte[] CreateAuthenticationResponse(byte[] challenge, int offset, /// See Secure Password Authentication. public static byte[] HashPassword(byte[] challenge, int offset, string password) { - using (var sha1 = SHA1.Create()) - { - var combined = new byte[40]; - Buffer.BlockCopy(challenge, offset, combined, 0, 20); + using var sha1 = SHA1.Create(); + var combined = new byte[40]; + Buffer.BlockCopy(challenge, offset, combined, 0, 20); - var passwordBytes = Encoding.UTF8.GetBytes(password); - var hashedPassword = sha1.ComputeHash(passwordBytes); + var passwordBytes = Encoding.UTF8.GetBytes(password); + var hashedPassword = sha1.ComputeHash(passwordBytes); - var doubleHashedPassword = sha1.ComputeHash(hashedPassword); - Buffer.BlockCopy(doubleHashedPassword, 0, combined, 20, 20); + var doubleHashedPassword = sha1.ComputeHash(hashedPassword); + Buffer.BlockCopy(doubleHashedPassword, 0, combined, 20, 20); - var xorBytes = sha1.ComputeHash(combined); - for (int i = 0; i < hashedPassword.Length; i++) - hashedPassword[i] ^= xorBytes[i]; + var xorBytes = sha1.ComputeHash(combined); + for (int i = 0; i < hashedPassword.Length; i++) + hashedPassword[i] ^= xorBytes[i]; - return hashedPassword; - } + return hashedPassword; } public static byte[] CreateScrambleResponse(byte[] nonce, string password) @@ -50,23 +48,21 @@ public static byte[] CreateScrambleResponse(byte[] nonce, string password) private static byte[] HashPasswordWithNonce(byte[] nonce, string password) { - using (var sha256 = SHA256.Create()) - { - var passwordBytes = Encoding.UTF8.GetBytes(password); - var hashedPassword = sha256.ComputeHash(passwordBytes); + using var sha256 = SHA256.Create(); + var passwordBytes = Encoding.UTF8.GetBytes(password); + var hashedPassword = sha256.ComputeHash(passwordBytes); - var doubleHashedPassword = sha256.ComputeHash(hashedPassword); - var combined = new byte[doubleHashedPassword.Length + nonce.Length]; + var doubleHashedPassword = sha256.ComputeHash(hashedPassword); + var combined = new byte[doubleHashedPassword.Length + nonce.Length]; - Buffer.BlockCopy(doubleHashedPassword, 0, combined, 0, doubleHashedPassword.Length); - Buffer.BlockCopy(nonce, 0, combined, doubleHashedPassword.Length, nonce.Length); + Buffer.BlockCopy(doubleHashedPassword, 0, combined, 0, doubleHashedPassword.Length); + Buffer.BlockCopy(nonce, 0, combined, doubleHashedPassword.Length, nonce.Length); - var xorBytes = sha256.ComputeHash(combined); - for (int i = 0; i < hashedPassword.Length; i++) - hashedPassword[i] ^= xorBytes[i]; + var xorBytes = sha256.ComputeHash(combined); + for (int i = 0; i < hashedPassword.Length; i++) + hashedPassword[i] ^= xorBytes[i]; - return hashedPassword; - } + return hashedPassword; } } } diff --git a/src/MySqlConnector/Protocol/Serialization/CompressedPayloadHandler.cs b/src/MySqlConnector/Protocol/Serialization/CompressedPayloadHandler.cs index ed110c51a..133f65bcd 100644 --- a/src/MySqlConnector/Protocol/Serialization/CompressedPayloadHandler.cs +++ b/src/MySqlConnector/Protocol/Serialization/CompressedPayloadHandler.cs @@ -40,8 +40,8 @@ public IByteHandler ByteHandler public ValueTask> ReadPayloadAsync(ArraySegmentHolder cache, ProtocolErrorBehavior protocolErrorBehavior, IOBehavior ioBehavior) { - using (var compressedByteHandler = new CompressedByteHandler(this, protocolErrorBehavior)) - return ProtocolUtility.ReadPayloadAsync(m_bufferedByteReader, compressedByteHandler, () => -1, cache, protocolErrorBehavior, ioBehavior); + using var compressedByteHandler = new CompressedByteHandler(this, protocolErrorBehavior); + return ProtocolUtility.ReadPayloadAsync(m_bufferedByteReader, compressedByteHandler, () => -1, cache, protocolErrorBehavior, ioBehavior); } public ValueTask WritePayloadAsync(ReadOnlyMemory payload, IOBehavior ioBehavior) @@ -147,23 +147,21 @@ private ValueTask ReadBytesAsync(ArraySegment buffer, ProtocolErrorBe const int headerSize = 2; const int checksumSize = 4; var uncompressedData = new byte[uncompressedLength]; - using (var compressedStream = new MemoryStream(payloadReadBytes.Array, payloadReadBytes.Offset + headerSize, payloadReadBytes.Count - headerSize - checksumSize)) - using (var decompressingStream = new DeflateStream(compressedStream, CompressionMode.Decompress)) + using var compressedStream = new MemoryStream(payloadReadBytes.Array, payloadReadBytes.Offset + headerSize, payloadReadBytes.Count - headerSize - checksumSize); + using var decompressingStream = new DeflateStream(compressedStream, CompressionMode.Decompress); + var bytesRead = decompressingStream.Read(uncompressedData, 0, uncompressedLength); + m_remainingData = new ArraySegment(uncompressedData, 0, bytesRead); + + var checksum = ComputeAdler32Checksum(uncompressedData, 0, bytesRead); + int adlerStartOffset = payloadReadBytes.Offset + payloadReadBytes.Count - 4; + if (payloadReadBytes.Array[adlerStartOffset + 0] != ((checksum >> 24) & 0xFF) || + payloadReadBytes.Array[adlerStartOffset + 1] != ((checksum >> 16) & 0xFF) || + payloadReadBytes.Array[adlerStartOffset + 2] != ((checksum >> 8) & 0xFF) || + payloadReadBytes.Array[adlerStartOffset + 3] != (checksum & 0xFF)) { - var bytesRead = decompressingStream.Read(uncompressedData, 0, uncompressedLength); - m_remainingData = new ArraySegment(uncompressedData, 0, bytesRead); - - var checksum = ComputeAdler32Checksum(uncompressedData, 0, bytesRead); - int adlerStartOffset = payloadReadBytes.Offset + payloadReadBytes.Count - 4; - if (payloadReadBytes.Array[adlerStartOffset + 0] != ((checksum >> 24) & 0xFF) || - payloadReadBytes.Array[adlerStartOffset + 1] != ((checksum >> 16) & 0xFF) || - payloadReadBytes.Array[adlerStartOffset + 2] != ((checksum >> 8) & 0xFF) || - payloadReadBytes.Array[adlerStartOffset + 3] != (checksum & 0xFF)) - { - return protocolErrorBehavior == ProtocolErrorBehavior.Ignore ? - default(ValueTask) : - ValueTaskExtensions.FromException(new NotSupportedException("Invalid Adler-32 checksum of uncompressed data.")); - } + return protocolErrorBehavior == ProtocolErrorBehavior.Ignore ? + default(ValueTask) : + ValueTaskExtensions.FromException(new NotSupportedException("Invalid Adler-32 checksum of uncompressed data.")); } } @@ -188,27 +186,26 @@ private ValueTask CompressAndWrite(ArraySegment remainingUncompressed var compressedData = default(ArraySegment); if (remainingUncompressedBytes > 80) { - using (var compressedStream = new MemoryStream()) - { - // write CMF: 32K window + deflate algorithm - compressedStream.WriteByte(0x78); + using var compressedStream = new MemoryStream(); + + // write CMF: 32K window + deflate algorithm + compressedStream.WriteByte(0x78); - // write FLG: maximum compression + checksum - compressedStream.WriteByte(0xDA); + // write FLG: maximum compression + checksum + compressedStream.WriteByte(0xDA); - using (var deflateStream = new DeflateStream(compressedStream, CompressionLevel.Optimal, leaveOpen: true)) - deflateStream.Write(remainingUncompressedData.Array, remainingUncompressedData.Offset, remainingUncompressedBytes); + using (var deflateStream = new DeflateStream(compressedStream, CompressionLevel.Optimal, leaveOpen: true)) + deflateStream.Write(remainingUncompressedData.Array, remainingUncompressedData.Offset, remainingUncompressedBytes); - // write Adler-32 checksum to stream - var checksum = ComputeAdler32Checksum(remainingUncompressedData.Array, remainingUncompressedData.Offset, remainingUncompressedBytes); - compressedStream.WriteByte((byte) ((checksum >> 24) & 0xFF)); - compressedStream.WriteByte((byte) ((checksum >> 16) & 0xFF)); - compressedStream.WriteByte((byte) ((checksum >> 8) & 0xFF)); - compressedStream.WriteByte((byte) (checksum & 0xFF)); + // write Adler-32 checksum to stream + var checksum = ComputeAdler32Checksum(remainingUncompressedData.Array, remainingUncompressedData.Offset, remainingUncompressedBytes); + compressedStream.WriteByte((byte) ((checksum >> 24) & 0xFF)); + compressedStream.WriteByte((byte) ((checksum >> 16) & 0xFF)); + compressedStream.WriteByte((byte) ((checksum >> 8) & 0xFF)); + compressedStream.WriteByte((byte) (checksum & 0xFF)); - if (!compressedStream.TryGetBuffer(out compressedData)) - throw new InvalidOperationException("Couldn't get compressed stream buffer."); - } + if (!compressedStream.TryGetBuffer(out compressedData)) + throw new InvalidOperationException("Couldn't get compressed stream buffer."); } uint uncompressedLength = (uint) remainingUncompressedBytes; diff --git a/tests/Conformance.Tests/Conformance.Tests.csproj b/tests/Conformance.Tests/Conformance.Tests.csproj index 9c1b3f2bd..1dff43db2 100644 --- a/tests/Conformance.Tests/Conformance.Tests.csproj +++ b/tests/Conformance.Tests/Conformance.Tests.csproj @@ -7,6 +7,7 @@ true ..\..\MySqlConnector.snk true + 8.0 diff --git a/tests/Conformance.Tests/SelectValueFixture.cs b/tests/Conformance.Tests/SelectValueFixture.cs index dfc7b277b..2f91df7af 100644 --- a/tests/Conformance.Tests/SelectValueFixture.cs +++ b/tests/Conformance.Tests/SelectValueFixture.cs @@ -87,17 +87,13 @@ insert into select_value values private void ExecuteNonQuery(string sql) { - using (var connection = Factory.CreateConnection()) - { - connection.ConnectionString = ConnectionString; - connection.Open(); + using var connection = Factory.CreateConnection(); + connection.ConnectionString = ConnectionString; + connection.Open(); - using (var command = connection.CreateCommand()) - { - command.CommandText = sql; - command.ExecuteNonQuery(); - } - } + using var command = connection.CreateCommand(); + command.CommandText = sql; + command.ExecuteNonQuery(); } } } diff --git a/tests/MySqlConnector.Tests/ConnectionTests.cs b/tests/MySqlConnector.Tests/ConnectionTests.cs index b996b90e9..a6fb93227 100644 --- a/tests/MySqlConnector.Tests/ConnectionTests.cs +++ b/tests/MySqlConnector.Tests/ConnectionTests.cs @@ -71,16 +71,14 @@ public async Task UnpooledConnectionIsClosed() Assert.Equal(0, m_server.ActiveConnections); m_csb.Pooling = false; - using (var connection = new MySqlConnection(m_csb.ConnectionString)) - { - await connection.OpenAsync(); - Assert.Equal(1, m_server.ActiveConnections); + using var connection = new MySqlConnection(m_csb.ConnectionString); + await connection.OpenAsync(); + Assert.Equal(1, m_server.ActiveConnections); - Assert.Equal(m_server.ServerVersion, connection.ServerVersion); - connection.Close(); + Assert.Equal(m_server.ServerVersion, connection.ServerVersion); + connection.Close(); - await WaitForConditionAsync(0, () => m_server.ActiveConnections); - } + await WaitForConditionAsync(0, () => m_server.ActiveConnections); } [Theory] @@ -117,11 +115,9 @@ public async Task ConnectionLifeTime(uint lifeTime, uint delaySeconds, bool shou public async Task MinimumPoolSize(int size) { m_csb.MinimumPoolSize = (uint) size; - using (var connection = new MySqlConnection(m_csb.ConnectionString)) - { - await connection.OpenAsync(); - Assert.Equal(size, m_server.ActiveConnections); - } + using var connection = new MySqlConnection(m_csb.ConnectionString); + await connection.OpenAsync(); + Assert.Equal(size, m_server.ActiveConnections); } [Fact] @@ -154,46 +150,38 @@ public void LeakReaders() public void AuthPluginNameNotNullTerminated() { m_server.SuppressAuthPluginNameTerminatingNull = true; - using (var connection = new MySqlConnection(m_csb.ConnectionString)) - { - connection.Open(); - Assert.Equal(ConnectionState.Open, connection.State); - } + using var connection = new MySqlConnection(m_csb.ConnectionString); + connection.Open(); + Assert.Equal(ConnectionState.Open, connection.State); } [Fact] public void IncompleteServerHandshake() { m_server.SendIncompletePostHandshakeResponse = true; - using (var connection = new MySqlConnection(m_csb.ConnectionString)) - { - Assert.Throws(() => connection.Open()); - } + using var connection = new MySqlConnection(m_csb.ConnectionString); + Assert.Throws(() => connection.Open()); } [Fact] public void Ping() { - using (var connection = new MySqlConnection(m_csb.ConnectionString)) - { - connection.Open(); - Assert.Equal(ConnectionState.Open, connection.State); - Assert.True(connection.Ping()); - Assert.Equal(ConnectionState.Open, connection.State); - } + using var connection = new MySqlConnection(m_csb.ConnectionString); + connection.Open(); + Assert.Equal(ConnectionState.Open, connection.State); + Assert.True(connection.Ping()); + Assert.Equal(ConnectionState.Open, connection.State); } [Fact] public void PingWhenClosed() { - using (var connection = new MySqlConnection(m_csb.ConnectionString)) - { - connection.Open(); - Assert.Equal(ConnectionState.Open, connection.State); - m_server.Stop(); - Assert.False(connection.Ping()); - Assert.Equal(ConnectionState.Closed, connection.State); - } + using var connection = new MySqlConnection(m_csb.ConnectionString); + connection.Open(); + Assert.Equal(ConnectionState.Open, connection.State); + m_server.Stop(); + Assert.False(connection.Ping()); + Assert.Equal(ConnectionState.Closed, connection.State); } private static async Task WaitForConditionAsync(T expected, Func getValue) diff --git a/tests/MySqlConnector.Tests/FakeMySqlServerConnection.cs b/tests/MySqlConnector.Tests/FakeMySqlServerConnection.cs index 6e472a301..33fc7aad3 100644 --- a/tests/MySqlConnector.Tests/FakeMySqlServerConnection.cs +++ b/tests/MySqlConnector.Tests/FakeMySqlServerConnection.cs @@ -110,17 +110,15 @@ private static async Task SendAsync(Stream stream, int sequenceNumber, Action writePayload) { - using (var memoryStream = new MemoryStream()) + using var memoryStream = new MemoryStream(); + using (var writer = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true)) { - using (var writer = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true)) - { - writer.Write(default(int)); - writePayload(writer); - memoryStream.Position = 0; - writer.Write(((int) (memoryStream.Length - 4)) | ((sequenceNumber % 256) << 24)); - } - return memoryStream.ToArray(); + writer.Write(default(int)); + writePayload(writer); + memoryStream.Position = 0; + writer.Write(((int) (memoryStream.Length - 4)) | ((sequenceNumber % 256) << 24)); } + return memoryStream.ToArray(); } private static async Task ReadPayloadAsync(Stream stream, CancellationToken token) diff --git a/tests/MySqlConnector.Tests/MySqlConnector.Tests.csproj b/tests/MySqlConnector.Tests/MySqlConnector.Tests.csproj index a031ac692..516fbb3e0 100644 --- a/tests/MySqlConnector.Tests/MySqlConnector.Tests.csproj +++ b/tests/MySqlConnector.Tests/MySqlConnector.Tests.csproj @@ -18,6 +18,7 @@ MySqlConnector.Tests MySqlConnector.Tests true + 8.0 diff --git a/tests/MySqlConnector.Tests/StatementPreparerTests.cs b/tests/MySqlConnector.Tests/StatementPreparerTests.cs index 88aba74bf..d5aa2286f 100644 --- a/tests/MySqlConnector.Tests/StatementPreparerTests.cs +++ b/tests/MySqlConnector.Tests/StatementPreparerTests.cs @@ -239,34 +239,32 @@ public void SplitStatement(string sql, string[] expectedStatements, string expec }; var preparer = new StatementPreparer(sql, parameters, StatementPreparerOptions.None); - using (var parsedStatements = preparer.SplitStatements()) + using var parsedStatements = preparer.SplitStatements(); + var splitStatements = parsedStatements.Statements; + Assert.Equal(expectedStatements.Length, splitStatements.Count); + for (var i = 0; i < splitStatements.Count; i++) { - var splitStatements = parsedStatements.Statements; - Assert.Equal(expectedStatements.Length, splitStatements.Count); - for (var i = 0; i < splitStatements.Count; i++) - { - var parsedSql = Encoding.UTF8.GetString(splitStatements[i].StatementBytes.Slice(1)); - Assert.Equal(expectedStatements[i], parsedSql); + var parsedSql = Encoding.UTF8.GetString(splitStatements[i].StatementBytes.Slice(1)); + Assert.Equal(expectedStatements[i], parsedSql); - var expectedParameterNamesOrIndexes = expectedStatementParameters[i].Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); - var expectedParameterIndexes = new int[expectedParameterNamesOrIndexes.Length]; - var expectedParameterNames = new string[expectedParameterNamesOrIndexes.Length]; - for (var j = 0; j < expectedParameterNamesOrIndexes.Length; j++) + var expectedParameterNamesOrIndexes = expectedStatementParameters[i].Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + var expectedParameterIndexes = new int[expectedParameterNamesOrIndexes.Length]; + var expectedParameterNames = new string[expectedParameterNamesOrIndexes.Length]; + for (var j = 0; j < expectedParameterNamesOrIndexes.Length; j++) + { + if (expectedParameterNamesOrIndexes[j][0] == '@') { - if (expectedParameterNamesOrIndexes[j][0] == '@') - { - expectedParameterNames[j] = expectedParameterNamesOrIndexes[j]; - expectedParameterIndexes[j] = -1; - } - else - { - expectedParameterIndexes[j] = int.Parse(expectedParameterNamesOrIndexes[j], CultureInfo.InvariantCulture); - } + expectedParameterNames[j] = expectedParameterNamesOrIndexes[j]; + expectedParameterIndexes[j] = -1; + } + else + { + expectedParameterIndexes[j] = int.Parse(expectedParameterNamesOrIndexes[j], CultureInfo.InvariantCulture); } - - Assert.Equal(expectedParameterIndexes, splitStatements[i].ParameterIndexes); - Assert.Equal(expectedParameterNames, splitStatements[i].ParameterNames); } + + Assert.Equal(expectedParameterIndexes, splitStatements[i].ParameterIndexes); + Assert.Equal(expectedParameterNames, splitStatements[i].ParameterNames); } } @@ -275,8 +273,8 @@ private static string GetParsedSql(string input, MySqlParameterCollection parame var preparer = new StatementPreparer(input, parameters ?? new MySqlParameterCollection(), options); var writer = new ByteBufferWriter(); preparer.ParseAndBindParameters(writer); - using (var payload = writer.ToPayloadData()) - return Encoding.UTF8.GetString(payload.Span); + using var payload = writer.ToPayloadData(); + return Encoding.UTF8.GetString(payload.Span); } } } diff --git a/tests/SideBySide/BatchTests.cs b/tests/SideBySide/BatchTests.cs index 293c8b9e9..74e24de17 100644 --- a/tests/SideBySide/BatchTests.cs +++ b/tests/SideBySide/BatchTests.cs @@ -15,160 +15,126 @@ public BatchTests(DatabaseFixture database) [Fact] public void NeedsConnection() { - using (var batch = new MySqlBatch + using var batch = new MySqlBatch { BatchCommands = { new MySqlBatchCommand("SELECT 1;"), }, - }) - { - Assert.Throws(() => batch.ExecuteNonQuery()); - } + }; + Assert.Throws(() => batch.ExecuteNonQuery()); } [Fact] public void NeedsOpenConnection() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - using (var batch = new MySqlBatch(connection) + using var connection = new MySqlConnection(AppConfig.ConnectionString); + using var batch = new MySqlBatch(connection) { BatchCommands = { new MySqlBatchCommand("SELECT 1;"), }, - }) - { - Assert.Throws(() => batch.ExecuteNonQuery()); - } + }; + Assert.Throws(() => batch.ExecuteNonQuery()); } [Fact] public void NeedsCommands() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - { - connection.Open(); - using (var batch = new MySqlBatch(connection)) - { - Assert.Throws(() => batch.ExecuteNonQuery()); - } - } + using var connection = new MySqlConnection(AppConfig.ConnectionString); + connection.Open(); + using var batch = new MySqlBatch(connection); + Assert.Throws(() => batch.ExecuteNonQuery()); } [Fact] public void NotDisposed() { - using (var batch = new MySqlBatch()) - { - batch.Dispose(); - Assert.Throws(() => batch.ExecuteNonQuery()); - } + using var batch = new MySqlBatch(); + batch.Dispose(); + Assert.Throws(() => batch.ExecuteNonQuery()); } [Fact] public void NoCloseConnection() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) + using var connection = new MySqlConnection(AppConfig.ConnectionString); + connection.Open(); + using var batch = new MySqlBatch(connection) { - connection.Open(); - using (var batch = new MySqlBatch(connection) - { - BatchCommands = - { - new MySqlBatchCommand("SELECT 1;") { CommandBehavior = CommandBehavior.CloseConnection }, - }, - }) + BatchCommands = { - Assert.Throws(() => batch.ExecuteNonQuery()); - } - } + new MySqlBatchCommand("SELECT 1;") { CommandBehavior = CommandBehavior.CloseConnection }, + }, + }; + Assert.Throws(() => batch.ExecuteNonQuery()); } [Fact] public void CreateBatchDoesNotSetTransaction() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - { - connection.Open(); - using (connection.BeginTransaction()) - using (var batch = connection.CreateBatch()) - { - Assert.Null(batch.Transaction); - } - } + using var connection = new MySqlConnection(AppConfig.ConnectionString); + connection.Open(); + using var transaction = connection.BeginTransaction(); + using var batch = connection.CreateBatch(); + Assert.Null(batch.Transaction); } [Fact] 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(() => batch.ExecuteScalar()); + 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(() => batch.ExecuteScalar()); - batch.Transaction = transaction; - TestUtilities.AssertIsOne(batch.ExecuteScalar()); - } - } + batch.Transaction = transaction; + TestUtilities.AssertIsOne(batch.ExecuteScalar()); } [Fact] public void IgnoreBatchTransactionIgnoresNull() { - using (var connection = new MySqlConnection(GetIgnoreCommandTransactionConnectionString())) - { - connection.Open(); - using (connection.BeginTransaction()) - using (var batch = connection.CreateBatch()) - { - batch.BatchCommands.Add(new MySqlBatchCommand("SELECT 1;")); - TestUtilities.AssertIsOne(batch.ExecuteScalar()); - } - } + 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()); } [Fact] public void IgnoreCommandTransactionIgnoresDisposedTransaction() { - using (var connection = new MySqlConnection(GetIgnoreCommandTransactionConnectionString())) - { - connection.Open(); + using var connection = new MySqlConnection(GetIgnoreCommandTransactionConnectionString()); + connection.Open(); - var transaction = connection.BeginTransaction(); - transaction.Commit(); - transaction.Dispose(); + 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()); - } - } + using var batch = connection.CreateBatch(); + batch.BatchCommands.Add(new MySqlBatchCommand("SELECT 1;")); + batch.Transaction = transaction; + TestUtilities.AssertIsOne(batch.ExecuteScalar()); } [Fact] 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()); - } - } + 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()); } [Theory] @@ -181,159 +147,139 @@ public void IgnoreCommandTransactionIgnoresDifferentTransaction() [InlineData(" # ")] public void ExecuteBatch(string suffix) { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) + using var connection = new MySqlConnection(AppConfig.ConnectionString); + connection.Open(); + using var batch = new MySqlBatch(connection) { - connection.Open(); - using (var batch = new MySqlBatch(connection) - { - BatchCommands = - { - new MySqlBatchCommand("SELECT 1" + suffix), - new MySqlBatchCommand("SELECT 2" + suffix), - new MySqlBatchCommand("SELECT 3" + suffix), - }, - }) - using (var reader = batch.ExecuteReader()) + BatchCommands = { - var total = 0; + new MySqlBatchCommand("SELECT 1" + suffix), + new MySqlBatchCommand("SELECT 2" + suffix), + new MySqlBatchCommand("SELECT 3" + suffix), + }, + }; + using var reader = batch.ExecuteReader(); + var total = 0; - Assert.True(reader.Read()); - total += reader.GetInt32(0); - Assert.False(reader.Read()); - Assert.True(reader.NextResult()); + Assert.True(reader.Read()); + total += reader.GetInt32(0); + Assert.False(reader.Read()); + Assert.True(reader.NextResult()); - Assert.True(reader.Read()); - total += reader.GetInt32(0); - Assert.False(reader.Read()); - Assert.True(reader.NextResult()); + Assert.True(reader.Read()); + total += reader.GetInt32(0); + Assert.False(reader.Read()); + Assert.True(reader.NextResult()); - Assert.True(reader.Read()); - total += reader.GetInt32(0); - Assert.False(reader.Read()); - Assert.False(reader.NextResult()); + Assert.True(reader.Read()); + total += reader.GetInt32(0); + Assert.False(reader.Read()); + Assert.False(reader.NextResult()); - Assert.Equal(6, total); - } - } + Assert.Equal(6, total); } [Fact(Skip = "COM_MULTI")] public void ExecuteInvalidSqlBatch() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) + using var connection = new MySqlConnection(AppConfig.ConnectionString); + connection.Open(); + using var batch = new MySqlBatch(connection) { - connection.Open(); - using (var batch = new MySqlBatch(connection) - { - BatchCommands = - { - new MySqlBatchCommand("SELECT 1;"), - new MySqlBatchCommand("SELECT 2 /* incomplete"), - new MySqlBatchCommand("SELECT 3;"), - }, - }) - using (var reader = batch.ExecuteReader()) + BatchCommands = { - Assert.True(reader.Read()); - Assert.Equal(1, reader.GetInt32(0)); - Assert.False(reader.Read()); + new MySqlBatchCommand("SELECT 1;"), + new MySqlBatchCommand("SELECT 2 /* incomplete"), + new MySqlBatchCommand("SELECT 3;"), + }, + }; + using var reader = batch.ExecuteReader(); + Assert.True(reader.Read()); + Assert.Equal(1, reader.GetInt32(0)); + Assert.False(reader.Read()); - try - { - reader.NextResult(); - Assert.True(false, "Shouldn't get here"); - } - catch (MySqlException ex) - { - Assert.Equal(MySqlErrorCode.ParseError, (MySqlErrorCode) ex.Number); - } - } + try + { + reader.NextResult(); + Assert.True(false, "Shouldn't get here"); + } + catch (MySqlException ex) + { + Assert.Equal(MySqlErrorCode.ParseError, (MySqlErrorCode) ex.Number); } } [Fact] public void SingleRow() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - { - connection.Open(); - using (var command = new MySqlCommand(@"drop table if exists batch_single_row; + using var connection = new MySqlConnection(AppConfig.ConnectionString); + connection.Open(); + using (var command = new MySqlCommand(@"drop table if exists batch_single_row; create table batch_single_row(id integer not null primary key); insert into batch_single_row(id) values(1),(2),(3);", connection)) - { - command.ExecuteNonQuery(); - } + { + command.ExecuteNonQuery(); + } - using (var batch = new MySqlBatch(connection) - { - BatchCommands = - { - new MySqlBatchCommand("SELECT id FROM batch_single_row ORDER BY id"), - new MySqlBatchCommand("SELECT id FROM batch_single_row ORDER BY id") { CommandBehavior = CommandBehavior.SingleRow }, - }, - }) - using (var reader = batch.ExecuteReader()) + using var batch = new MySqlBatch(connection) + { + BatchCommands = { - Assert.True(reader.Read()); - Assert.Equal(1, reader.GetInt32(0)); - Assert.True(reader.Read()); - Assert.Equal(2, reader.GetInt32(0)); - Assert.True(reader.Read()); - Assert.Equal(3, reader.GetInt32(0)); - Assert.False(reader.Read()); + new MySqlBatchCommand("SELECT id FROM batch_single_row ORDER BY id"), + new MySqlBatchCommand("SELECT id FROM batch_single_row ORDER BY id") { CommandBehavior = CommandBehavior.SingleRow }, + }, + }; + using var reader = batch.ExecuteReader(); + Assert.True(reader.Read()); + Assert.Equal(1, reader.GetInt32(0)); + Assert.True(reader.Read()); + Assert.Equal(2, reader.GetInt32(0)); + Assert.True(reader.Read()); + Assert.Equal(3, reader.GetInt32(0)); + Assert.False(reader.Read()); - Assert.True(reader.NextResult()); - Assert.True(reader.Read()); - Assert.Equal(1, reader.GetInt32(0)); - Assert.False(reader.Read()); + Assert.True(reader.NextResult()); + Assert.True(reader.Read()); + Assert.Equal(1, reader.GetInt32(0)); + Assert.False(reader.Read()); - Assert.False(reader.NextResult()); - } - } + Assert.False(reader.NextResult()); } [Fact] public void PrepareNeedsConnection() { - using (var batch = new MySqlBatch + using var batch = new MySqlBatch { BatchCommands = { new MySqlBatchCommand("SELECT 1;"), }, - }) - { - Assert.Throws(() => batch.Prepare()); - } + }; + Assert.Throws(() => batch.Prepare()); } [Fact] public void PrepareNeedsOpenConnection() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - using (var batch = new MySqlBatch(connection) + using var connection = new MySqlConnection(AppConfig.ConnectionString); + using var batch = new MySqlBatch(connection) { BatchCommands = { new MySqlBatchCommand("SELECT 1;"), }, - }) - { - Assert.Throws(() => batch.Prepare()); - } + }; + Assert.Throws(() => batch.Prepare()); } [Fact] public void PrepareNeedsCommands() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - { - connection.Open(); - using (var batch = new MySqlBatch(connection)) - { - Assert.Throws(() => batch.Prepare()); - } - } + using var connection = new MySqlConnection(AppConfig.ConnectionString); + connection.Open(); + using var batch = new MySqlBatch(connection); + Assert.Throws(() => batch.Prepare()); } private static string GetIgnoreCommandTransactionConnectionString() => diff --git a/tests/SideBySide/BulkLoaderAsync.cs b/tests/SideBySide/BulkLoaderAsync.cs index 6d9f8ce67..1f2ef845b 100644 --- a/tests/SideBySide/BulkLoaderAsync.cs +++ b/tests/SideBySide/BulkLoaderAsync.cs @@ -39,141 +39,129 @@ one int primary key [SkippableFact(ConfigSettings.TsvFile)] public async Task BulkLoadTsvFile() { - using (var connection = new MySqlConnection(GetConnectionString())) - { - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - bl.FileName = AppConfig.MySqlBulkLoaderTsvFile; - bl.TableName = m_testTable; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.Expressions.Add("five = UNHEX(five)"); - bl.Local = false; - int rowCount = await bl.LoadAsync(); - Assert.Equal(20, rowCount); - } + using var connection = new MySqlConnection(GetConnectionString()); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + bl.FileName = AppConfig.MySqlBulkLoaderTsvFile; + bl.TableName = m_testTable; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.Expressions.Add("five = UNHEX(five)"); + bl.Local = false; + int rowCount = await bl.LoadAsync(); + Assert.Equal(20, rowCount); } [SkippableFact(ConfigSettings.LocalTsvFile)] public async Task BulkLoadLocalTsvFile() { - using (var connection = new MySqlConnection(GetLocalConnectionString())) - { - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - bl.FileName = AppConfig.MySqlBulkLoaderLocalTsvFile; - bl.TableName = m_testTable; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.Expressions.Add("five = UNHEX(five)"); - bl.Local = true; - int rowCount = await bl.LoadAsync(); - Assert.Equal(20, rowCount); - } + using var connection = new MySqlConnection(GetLocalConnectionString()); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + bl.FileName = AppConfig.MySqlBulkLoaderLocalTsvFile; + bl.TableName = m_testTable; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.Expressions.Add("five = UNHEX(five)"); + bl.Local = true; + int rowCount = await bl.LoadAsync(); + Assert.Equal(20, rowCount); } [SkippableFact(ConfigSettings.LocalTsvFile)] public async Task BulkLoadLocalTsvFileDoubleEscapedTerminators() { - using (var connection = new MySqlConnection(GetLocalConnectionString())) - { - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - bl.FileName = AppConfig.MySqlBulkLoaderLocalTsvFile; - bl.TableName = m_testTable; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.Expressions.Add("five = UNHEX(five)"); - bl.LineTerminator = "\\n"; - bl.FieldTerminator = "\\t"; - bl.Local = true; - int rowCount = await bl.LoadAsync(); - Assert.Equal(20, rowCount); - } + using var connection = new MySqlConnection(GetLocalConnectionString()); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + bl.FileName = AppConfig.MySqlBulkLoaderLocalTsvFile; + bl.TableName = m_testTable; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.Expressions.Add("five = UNHEX(five)"); + bl.LineTerminator = "\\n"; + bl.FieldTerminator = "\\t"; + bl.Local = true; + int rowCount = await bl.LoadAsync(); + Assert.Equal(20, rowCount); } [SkippableFact(ConfigSettings.CsvFile)] public async Task BulkLoadCsvFile() { - using (var connection = new MySqlConnection(GetConnectionString())) - { - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - bl.FileName = AppConfig.MySqlBulkLoaderCsvFile; - bl.TableName = m_testTable; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.FieldTerminator = ","; - bl.FieldQuotationCharacter = '"'; - bl.FieldQuotationOptional = true; - bl.Expressions.Add("five = UNHEX(five)"); - bl.Local = false; - int rowCount = await bl.LoadAsync(); - Assert.Equal(20, rowCount); - } + using var connection = new MySqlConnection(GetConnectionString()); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + bl.FileName = AppConfig.MySqlBulkLoaderCsvFile; + bl.TableName = m_testTable; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.FieldTerminator = ","; + bl.FieldQuotationCharacter = '"'; + bl.FieldQuotationOptional = true; + bl.Expressions.Add("five = UNHEX(five)"); + bl.Local = false; + int rowCount = await bl.LoadAsync(); + Assert.Equal(20, rowCount); } [SkippableFact(ConfigSettings.LocalCsvFile)] public async Task BulkLoadLocalCsvFile() { - using (var connection = new MySqlConnection(GetLocalConnectionString())) - { - await connection.OpenAsync(); - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - bl.FileName = AppConfig.MySqlBulkLoaderLocalCsvFile; - bl.TableName = m_testTable; - bl.CharacterSet = "UTF8"; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.FieldTerminator = ","; - bl.FieldQuotationCharacter = '"'; - bl.FieldQuotationOptional = true; - bl.Expressions.Add("five = UNHEX(five)"); - bl.Local = true; - int rowCount = await bl.LoadAsync(); - Assert.Equal(20, rowCount); - } + using var connection = new MySqlConnection(GetLocalConnectionString()); + await connection.OpenAsync(); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + bl.FileName = AppConfig.MySqlBulkLoaderLocalCsvFile; + bl.TableName = m_testTable; + bl.CharacterSet = "UTF8"; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.FieldTerminator = ","; + bl.FieldQuotationCharacter = '"'; + bl.FieldQuotationOptional = true; + bl.Expressions.Add("five = UNHEX(five)"); + bl.Local = true; + int rowCount = await bl.LoadAsync(); + Assert.Equal(20, rowCount); } [Fact] public async Task BulkLoadCsvFileNotFound() { - using (var connection = new MySqlConnection(GetConnectionString())) - { - await connection.OpenAsync(); + using var connection = new MySqlConnection(GetConnectionString()); + await connection.OpenAsync(); - var secureFilePath = await connection.ExecuteScalarAsync(@"select @@global.secure_file_priv;"); - if (string.IsNullOrEmpty(secureFilePath) || secureFilePath == "NULL") - return; + var secureFilePath = await connection.ExecuteScalarAsync(@"select @@global.secure_file_priv;"); + if (string.IsNullOrEmpty(secureFilePath) || secureFilePath == "NULL") + return; - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - bl.FileName = Path.Combine(secureFilePath, AppConfig.MySqlBulkLoaderCsvFile + "-junk"); - bl.TableName = m_testTable; - bl.CharacterSet = "UTF8"; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.FieldTerminator = ","; - bl.FieldQuotationCharacter = '"'; - bl.FieldQuotationOptional = true; - bl.Expressions.Add("five = UNHEX(five)"); - bl.Local = false; - try - { - int rowCount = await bl.LoadAsync(); - } - catch (Exception exception) - { - while (exception.InnerException is object) - exception = exception.InnerException; + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + bl.FileName = Path.Combine(secureFilePath, AppConfig.MySqlBulkLoaderCsvFile + "-junk"); + bl.TableName = m_testTable; + bl.CharacterSet = "UTF8"; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.FieldTerminator = ","; + bl.FieldQuotationCharacter = '"'; + bl.FieldQuotationOptional = true; + bl.Expressions.Add("five = UNHEX(five)"); + bl.Local = false; + try + { + int rowCount = await bl.LoadAsync(); + } + catch (Exception exception) + { + while (exception.InnerException is object) + exception = exception.InnerException; - if (!(exception is FileNotFoundException)) + if (!(exception is FileNotFoundException)) + { + try + { + Assert.Contains("Errcode: 2 ", exception.Message, StringComparison.OrdinalIgnoreCase); + } + catch (ContainsException) { - try - { - Assert.Contains("Errcode: 2 ", exception.Message, StringComparison.OrdinalIgnoreCase); - } - catch (ContainsException) - { - Assert.Contains("OS errno 2 ", exception.Message, StringComparison.OrdinalIgnoreCase); - } - Assert.Contains("No such file or directory", exception.Message); + Assert.Contains("OS errno 2 ", exception.Message, StringComparison.OrdinalIgnoreCase); } + Assert.Contains("No such file or directory", exception.Message); } } } @@ -181,271 +169,244 @@ public async Task BulkLoadCsvFileNotFound() [Fact] public async Task BulkLoadLocalCsvFileNotFound() { - using (var connection = new MySqlConnection(GetLocalConnectionString())) + using var connection = new MySqlConnection(GetLocalConnectionString()); + await connection.OpenAsync(); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + bl.Timeout = 3; //Set a short timeout for this test because the file not found exception takes a long time otherwise, the timeout does not change the result + bl.FileName = AppConfig.MySqlBulkLoaderLocalCsvFile + "-junk"; + bl.TableName = m_testTable; + bl.CharacterSet = "UTF8"; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.FieldTerminator = ","; + bl.FieldQuotationCharacter = '"'; + bl.FieldQuotationOptional = true; + bl.Expressions.Add("five = UNHEX(five)"); + bl.Local = true; + try { - await connection.OpenAsync(); - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - bl.Timeout = 3; //Set a short timeout for this test because the file not found exception takes a long time otherwise, the timeout does not change the result - bl.FileName = AppConfig.MySqlBulkLoaderLocalCsvFile + "-junk"; - bl.TableName = m_testTable; - bl.CharacterSet = "UTF8"; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.FieldTerminator = ","; - bl.FieldQuotationCharacter = '"'; - bl.FieldQuotationOptional = true; - bl.Expressions.Add("five = UNHEX(five)"); - bl.Local = true; - try - { - int rowCount = await bl.LoadAsync(); - } - catch (MySqlException mySqlException) + int rowCount = await bl.LoadAsync(); + } + catch (MySqlException mySqlException) + { + while (mySqlException.InnerException is object) { - while (mySqlException.InnerException is object) + if (mySqlException.InnerException is MySqlException innerException) { - if (mySqlException.InnerException is MySqlException innerException) - { - mySqlException = innerException; - } - else - { - Assert.IsType(mySqlException.InnerException); - break; - } + mySqlException = innerException; } - if (mySqlException.InnerException is null) + else { - Assert.IsType(mySqlException); + Assert.IsType(mySqlException.InnerException); + break; } } - catch (Exception exception) + if (mySqlException.InnerException is null) { - //We know that the exception is not a MySqlException, just use the assertion to fail the test - Assert.IsType(exception); + Assert.IsType(mySqlException); } - ; + } + catch (Exception exception) + { + //We know that the exception is not a MySqlException, just use the assertion to fail the test + Assert.IsType(exception); } } [SkippableFact(ConfigSettings.LocalCsvFile)] public async Task BulkLoadLocalCsvFileInTransactionWithCommit() { - using (var connection = new MySqlConnection(GetLocalConnectionString())) + using var connection = new MySqlConnection(GetLocalConnectionString()); + await connection.OpenAsync(); + using (var transaction = connection.BeginTransaction()) { - await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction()) + var bulkLoader = new MySqlBulkLoader(connection) { - var bulkLoader = new MySqlBulkLoader(connection) - { - FileName = AppConfig.MySqlBulkLoaderLocalCsvFile, - TableName = m_testTable, - CharacterSet = "UTF8", - NumberOfLinesToSkip = 1, - FieldTerminator = ",", - FieldQuotationCharacter = '"', - FieldQuotationOptional = true, - Local = true, - }; - bulkLoader.Expressions.Add("five = UNHEX(five)"); - bulkLoader.Columns.AddRange(new[] { "one", "two", "three", "four", "five" }); + FileName = AppConfig.MySqlBulkLoaderLocalCsvFile, + TableName = m_testTable, + CharacterSet = "UTF8", + NumberOfLinesToSkip = 1, + FieldTerminator = ",", + FieldQuotationCharacter = '"', + FieldQuotationOptional = true, + Local = true, + }; + bulkLoader.Expressions.Add("five = UNHEX(five)"); + bulkLoader.Columns.AddRange(new[] { "one", "two", "three", "four", "five" }); - var rowCount = await bulkLoader.LoadAsync(); - Assert.Equal(20, rowCount); - - transaction.Commit(); - } + var rowCount = await bulkLoader.LoadAsync(); + Assert.Equal(20, rowCount); - Assert.Equal(20, await connection.ExecuteScalarAsync($@"select count(*) from {m_testTable};")); + transaction.Commit(); } + + Assert.Equal(20, await connection.ExecuteScalarAsync($@"select count(*) from {m_testTable};")); } [SkippableFact(ConfigSettings.LocalCsvFile)] public async Task BulkLoadLocalCsvFileInTransactionWithRollback() { - using (var connection = new MySqlConnection(GetLocalConnectionString())) + using var connection = new MySqlConnection(GetLocalConnectionString()); + await connection.OpenAsync(); + using (var transaction = connection.BeginTransaction()) { - await connection.OpenAsync(); - using (var transaction = connection.BeginTransaction()) + var bulkLoader = new MySqlBulkLoader(connection) { - var bulkLoader = new MySqlBulkLoader(connection) - { - FileName = AppConfig.MySqlBulkLoaderLocalCsvFile, - TableName = m_testTable, - CharacterSet = "UTF8", - NumberOfLinesToSkip = 1, - FieldTerminator = ",", - FieldQuotationCharacter = '"', - FieldQuotationOptional = true, - Local = true, - }; - bulkLoader.Expressions.Add("five = UNHEX(five)"); - bulkLoader.Columns.AddRange(new[] { "one", "two", "three", "four", "five" }); + FileName = AppConfig.MySqlBulkLoaderLocalCsvFile, + TableName = m_testTable, + CharacterSet = "UTF8", + NumberOfLinesToSkip = 1, + FieldTerminator = ",", + FieldQuotationCharacter = '"', + FieldQuotationOptional = true, + Local = true, + }; + bulkLoader.Expressions.Add("five = UNHEX(five)"); + bulkLoader.Columns.AddRange(new[] { "one", "two", "three", "four", "five" }); - var rowCount = await bulkLoader.LoadAsync(); - Assert.Equal(20, rowCount); - - transaction.Rollback(); - } + var rowCount = await bulkLoader.LoadAsync(); + Assert.Equal(20, rowCount); - Assert.Equal(0, await connection.ExecuteScalarAsync($@"select count(*) from {m_testTable};")); + transaction.Rollback(); } + + Assert.Equal(0, await connection.ExecuteScalarAsync($@"select count(*) from {m_testTable};")); } [Fact] public async Task BulkLoadMissingFileName() { - using (var connection = new MySqlConnection(GetConnectionString())) - { - await connection.OpenAsync(); - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - bl.TableName = m_testTable; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.FieldTerminator = ","; - bl.FieldQuotationCharacter = '"'; - bl.FieldQuotationOptional = true; - bl.Expressions.Add("five = UNHEX(five)"); - bl.Local = false; + using var connection = new MySqlConnection(GetConnectionString()); + await connection.OpenAsync(); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + bl.TableName = m_testTable; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.FieldTerminator = ","; + bl.FieldQuotationCharacter = '"'; + bl.FieldQuotationOptional = true; + bl.Expressions.Add("five = UNHEX(five)"); + bl.Local = false; #if BASELINE - await Assert.ThrowsAsync(async () => - { - int rowCount = await bl.LoadAsync(); - }); + await Assert.ThrowsAsync(async () => + { + int rowCount = await bl.LoadAsync(); + }); #else - await Assert.ThrowsAsync(async () => - { - int rowCount = await bl.LoadAsync(); - }); + await Assert.ThrowsAsync(async () => + { + int rowCount = await bl.LoadAsync(); + }); #endif - } } [SkippableFact(ConfigSettings.LocalCsvFile)] public async Task BulkLoadMissingTableName() { - using (var connection = new MySqlConnection(GetConnectionString())) - { - await connection.OpenAsync(); - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - bl.FileName = AppConfig.MySqlBulkLoaderLocalCsvFile; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.FieldTerminator = ","; - bl.FieldQuotationCharacter = '"'; - bl.FieldQuotationOptional = true; - bl.Expressions.Add("five = UNHEX(five)"); - bl.Local = false; + using var connection = new MySqlConnection(GetConnectionString()); + await connection.OpenAsync(); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + bl.FileName = AppConfig.MySqlBulkLoaderLocalCsvFile; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.FieldTerminator = ","; + bl.FieldQuotationCharacter = '"'; + bl.FieldQuotationOptional = true; + bl.Expressions.Add("five = UNHEX(five)"); + bl.Local = false; #if BASELINE - await Assert.ThrowsAsync(async () => - { - int rowCount = await bl.LoadAsync(); - }); + await Assert.ThrowsAsync(async () => + { + int rowCount = await bl.LoadAsync(); + }); #else - await Assert.ThrowsAsync(async () => - { - int rowCount = await bl.LoadAsync(); - }); + await Assert.ThrowsAsync(async () => + { + int rowCount = await bl.LoadAsync(); + }); #endif - } } #if !BASELINE [SkippableFact(ConfigSettings.LocalCsvFile)] public async Task BulkLoadFileStreamInvalidOperation() { - using (var connection = new MySqlConnection(GetConnectionString())) + using var connection = new MySqlConnection(GetConnectionString()); + var bl = new MySqlBulkLoader(connection); + using var fileStream = new FileStream(AppConfig.MySqlBulkLoaderLocalCsvFile, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true); + bl.SourceStream = fileStream; + bl.TableName = m_testTable; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.FieldTerminator = ","; + bl.FieldQuotationCharacter = '"'; + bl.FieldQuotationOptional = true; + bl.Expressions.Add("five = UNHEX(five)"); + bl.Local = false; + await Assert.ThrowsAsync(async () => { - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - using (var fileStream = new FileStream(AppConfig.MySqlBulkLoaderLocalCsvFile, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) - { - bl.SourceStream = fileStream; - bl.TableName = m_testTable; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.FieldTerminator = ","; - bl.FieldQuotationCharacter = '"'; - bl.FieldQuotationOptional = true; - bl.Expressions.Add("five = UNHEX(five)"); - bl.Local = false; - await Assert.ThrowsAsync(async () => - { - int rowCount = await bl.LoadAsync(); - }); - } - } + int rowCount = await bl.LoadAsync(); + }); } [SkippableFact(ConfigSettings.LocalCsvFile)] public async Task BulkLoadLocalFileStream() { - using (var connection = new MySqlConnection(GetLocalConnectionString())) - { - await connection.OpenAsync(); - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - using (var fileStream = new FileStream(AppConfig.MySqlBulkLoaderLocalCsvFile, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) - { - bl.SourceStream = fileStream; - bl.TableName = m_testTable; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.FieldTerminator = ","; - bl.FieldQuotationCharacter = '"'; - bl.FieldQuotationOptional = true; - bl.Expressions.Add("five = UNHEX(five)"); - bl.Local = true; - int rowCount = await bl.LoadAsync(); - Assert.Equal(20, rowCount); - } - } + using var connection = new MySqlConnection(GetLocalConnectionString()); + await connection.OpenAsync(); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + using var fileStream = new FileStream(AppConfig.MySqlBulkLoaderLocalCsvFile, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true); + bl.SourceStream = fileStream; + bl.TableName = m_testTable; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.FieldTerminator = ","; + bl.FieldQuotationCharacter = '"'; + bl.FieldQuotationOptional = true; + bl.Expressions.Add("five = UNHEX(five)"); + bl.Local = true; + int rowCount = await bl.LoadAsync(); + Assert.Equal(20, rowCount); } [Fact] public async Task BulkLoadMemoryStreamInvalidOperation() { - using (var connection = new MySqlConnection(GetConnectionString())) + using var connection = new MySqlConnection(GetConnectionString()); + await connection.OpenAsync(); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + using var memoryStream = new MemoryStream(m_memoryStreamBytes, false); + bl.SourceStream = memoryStream; + bl.TableName = m_testTable; + bl.Columns.AddRange(new string[] { "one", "two", "three" }); + bl.NumberOfLinesToSkip = 0; + bl.FieldTerminator = ","; + bl.FieldQuotationCharacter = '"'; + bl.FieldQuotationOptional = true; + bl.Local = false; + await Assert.ThrowsAsync(async () => { - await connection.OpenAsync(); - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - using (var memoryStream = new MemoryStream(m_memoryStreamBytes, false)) - { - bl.SourceStream = memoryStream; - bl.TableName = m_testTable; - bl.Columns.AddRange(new string[] { "one", "two", "three" }); - bl.NumberOfLinesToSkip = 0; - bl.FieldTerminator = ","; - bl.FieldQuotationCharacter = '"'; - bl.FieldQuotationOptional = true; - bl.Local = false; - await Assert.ThrowsAsync(async () => - { - int rowCount = await bl.LoadAsync(); - }); - } - } + int rowCount = await bl.LoadAsync(); + }); } [Fact] public async Task BulkLoadLocalMemoryStream() { - using (var connection = new MySqlConnection(GetLocalConnectionString())) - { - await connection.OpenAsync(); - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - using (var memoryStream = new MemoryStream(m_memoryStreamBytes, false)) - { - bl.SourceStream = memoryStream; - bl.TableName = m_testTable; - bl.Columns.AddRange(new string[] { "one", "two", "three" }); - bl.NumberOfLinesToSkip = 0; - bl.FieldTerminator = ","; - bl.FieldQuotationCharacter = '"'; - bl.FieldQuotationOptional = true; - bl.Local = true; - int rowCount = await bl.LoadAsync(); - Assert.Equal(5, rowCount); - } - } + using var connection = new MySqlConnection(GetLocalConnectionString()); + await connection.OpenAsync(); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + using var memoryStream = new MemoryStream(m_memoryStreamBytes, false); + bl.SourceStream = memoryStream; + bl.TableName = m_testTable; + bl.Columns.AddRange(new string[] { "one", "two", "three" }); + bl.NumberOfLinesToSkip = 0; + bl.FieldTerminator = ","; + bl.FieldQuotationCharacter = '"'; + bl.FieldQuotationOptional = true; + bl.Local = true; + int rowCount = await bl.LoadAsync(); + Assert.Equal(5, rowCount); } #endif diff --git a/tests/SideBySide/BulkLoaderSync.cs b/tests/SideBySide/BulkLoaderSync.cs index 83f4d0fac..56b5664fd 100644 --- a/tests/SideBySide/BulkLoaderSync.cs +++ b/tests/SideBySide/BulkLoaderSync.cs @@ -39,162 +39,148 @@ one int primary key [Fact] public void FileNameAndSourceStream() { - using (var connection = new MySqlConnection(GetConnectionString())) + using var connection = new MySqlConnection(GetConnectionString()); + connection.Open(); + var bl = new MySqlBulkLoader(connection) { - connection.Open(); - var bl = new MySqlBulkLoader(connection) - { - FileName = "test.dat", - SourceStream = new MemoryStream(), - TableName = m_testTable, - }; - Assert.Throws(() => bl.Load()); - } + FileName = "test.dat", + SourceStream = new MemoryStream(), + TableName = m_testTable, + }; + Assert.Throws(() => bl.Load()); } #endif [SkippableFact(ConfigSettings.TsvFile)] public void BulkLoadTsvFile() { - using (var connection = new MySqlConnection(GetConnectionString())) - { - connection.Open(); - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - bl.FileName = AppConfig.MySqlBulkLoaderTsvFile; - bl.TableName = m_testTable; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.Expressions.Add("five = UNHEX(five)"); - bl.Local = false; - int rowCount = bl.Load(); - Assert.Equal(20, rowCount); - } + using var connection = new MySqlConnection(GetConnectionString()); + connection.Open(); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + bl.FileName = AppConfig.MySqlBulkLoaderTsvFile; + bl.TableName = m_testTable; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.Expressions.Add("five = UNHEX(five)"); + bl.Local = false; + int rowCount = bl.Load(); + Assert.Equal(20, rowCount); } [SkippableFact(ConfigSettings.LocalTsvFile)] public void BulkLoadLocalTsvFile() { - using (var connection = new MySqlConnection(GetLocalConnectionString())) - { - connection.Open(); - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - bl.FileName = AppConfig.MySqlBulkLoaderLocalTsvFile; - bl.TableName = m_testTable; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.Expressions.Add("five = UNHEX(five)"); - bl.Local = true; - int rowCount = bl.Load(); - Assert.Equal(20, rowCount); - } + using var connection = new MySqlConnection(GetLocalConnectionString()); + connection.Open(); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + bl.FileName = AppConfig.MySqlBulkLoaderLocalTsvFile; + bl.TableName = m_testTable; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.Expressions.Add("five = UNHEX(five)"); + bl.Local = true; + int rowCount = bl.Load(); + Assert.Equal(20, rowCount); } [SkippableFact(ConfigSettings.LocalTsvFile)] public void BulkLoadLocalTsvFileDoubleEscapedTerminators() { - using (var connection = new MySqlConnection(GetLocalConnectionString())) - { - connection.Open(); - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - bl.FileName = AppConfig.MySqlBulkLoaderLocalTsvFile; - bl.TableName = m_testTable; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.Expressions.Add("five = UNHEX(five)"); - bl.LineTerminator = "\\n"; - bl.FieldTerminator = "\\t"; - bl.Local = true; - int rowCount = bl.Load(); - Assert.Equal(20, rowCount); - } + using var connection = new MySqlConnection(GetLocalConnectionString()); + connection.Open(); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + bl.FileName = AppConfig.MySqlBulkLoaderLocalTsvFile; + bl.TableName = m_testTable; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.Expressions.Add("five = UNHEX(five)"); + bl.LineTerminator = "\\n"; + bl.FieldTerminator = "\\t"; + bl.Local = true; + int rowCount = bl.Load(); + Assert.Equal(20, rowCount); } [SkippableFact(ConfigSettings.CsvFile)] public void BulkLoadCsvFile() { - using (var connection = new MySqlConnection(GetConnectionString())) - { - connection.Open(); - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - bl.FileName = AppConfig.MySqlBulkLoaderCsvFile; - bl.TableName = m_testTable; - bl.CharacterSet = "UTF8"; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.FieldTerminator = ","; - bl.FieldQuotationCharacter = '"'; - bl.FieldQuotationOptional = true; - bl.Expressions.Add("five = UNHEX(five)"); - bl.Local = false; - int rowCount = bl.Load(); - Assert.Equal(20, rowCount); - } + using var connection = new MySqlConnection(GetConnectionString()); + connection.Open(); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + bl.FileName = AppConfig.MySqlBulkLoaderCsvFile; + bl.TableName = m_testTable; + bl.CharacterSet = "UTF8"; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.FieldTerminator = ","; + bl.FieldQuotationCharacter = '"'; + bl.FieldQuotationOptional = true; + bl.Expressions.Add("five = UNHEX(five)"); + bl.Local = false; + int rowCount = bl.Load(); + Assert.Equal(20, rowCount); } [SkippableFact(ConfigSettings.LocalCsvFile)] public void BulkLoadLocalCsvFile() { - using (var connection = new MySqlConnection(GetLocalConnectionString())) - { - connection.Open(); - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - bl.FileName = AppConfig.MySqlBulkLoaderLocalCsvFile; - bl.TableName = m_testTable; - bl.CharacterSet = "UTF8"; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.FieldTerminator = ","; - bl.FieldQuotationCharacter = '"'; - bl.FieldQuotationOptional = true; - bl.Expressions.Add("five = UNHEX(five)"); - bl.Local = true; - int rowCount = bl.Load(); - Assert.Equal(20, rowCount); - } + using var connection = new MySqlConnection(GetLocalConnectionString()); + connection.Open(); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + bl.FileName = AppConfig.MySqlBulkLoaderLocalCsvFile; + bl.TableName = m_testTable; + bl.CharacterSet = "UTF8"; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.FieldTerminator = ","; + bl.FieldQuotationCharacter = '"'; + bl.FieldQuotationOptional = true; + bl.Expressions.Add("five = UNHEX(five)"); + bl.Local = true; + int rowCount = bl.Load(); + Assert.Equal(20, rowCount); } [Fact] public void BulkLoadCsvFileNotFound() { - using (var connection = new MySqlConnection(GetConnectionString())) + using var connection = new MySqlConnection(GetConnectionString()); + connection.Open(); + var secureFilePath = connection.ExecuteScalar(@"select @@global.secure_file_priv;"); + if (string.IsNullOrEmpty(secureFilePath) || secureFilePath == "NULL") + return; + + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + bl.FileName = Path.Combine(secureFilePath, AppConfig.MySqlBulkLoaderCsvFile + "-junk"); + bl.TableName = m_testTable; + bl.CharacterSet = "UTF8"; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.FieldTerminator = ","; + bl.FieldQuotationCharacter = '"'; + bl.FieldQuotationOptional = true; + bl.Expressions.Add("five = UNHEX(five)"); + bl.Local = false; + try { - connection.Open(); - var secureFilePath = connection.ExecuteScalar(@"select @@global.secure_file_priv;"); - if (string.IsNullOrEmpty(secureFilePath) || secureFilePath == "NULL") - return; - - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - bl.FileName = Path.Combine(secureFilePath, AppConfig.MySqlBulkLoaderCsvFile + "-junk"); - bl.TableName = m_testTable; - bl.CharacterSet = "UTF8"; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.FieldTerminator = ","; - bl.FieldQuotationCharacter = '"'; - bl.FieldQuotationOptional = true; - bl.Expressions.Add("five = UNHEX(five)"); - bl.Local = false; - try - { - int rowCount = bl.Load(); - } - catch (Exception exception) - { - while (exception.InnerException is object) - exception = exception.InnerException; + int rowCount = bl.Load(); + } + catch (Exception exception) + { + while (exception.InnerException is object) + exception = exception.InnerException; - if (!(exception is FileNotFoundException)) + if (!(exception is FileNotFoundException)) + { + try { - try - { - Assert.Contains("Errcode: 2 ", exception.Message, StringComparison.OrdinalIgnoreCase); - } - catch (ContainsException) - { - Assert.Contains("OS errno 2 ", exception.Message, StringComparison.OrdinalIgnoreCase); - } - Assert.Contains("No such file or directory", exception.Message); + Assert.Contains("Errcode: 2 ", exception.Message, StringComparison.OrdinalIgnoreCase); } + catch (ContainsException) + { + Assert.Contains("OS errno 2 ", exception.Message, StringComparison.OrdinalIgnoreCase); + } + Assert.Contains("No such file or directory", exception.Message); } } } @@ -202,90 +188,57 @@ public void BulkLoadCsvFileNotFound() [Fact] public void BulkLoadLocalCsvFileNotFound() { - using (var connection = new MySqlConnection(GetLocalConnectionString())) + using var connection = new MySqlConnection(GetLocalConnectionString()); + connection.Open(); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + bl.Timeout = 3; //Set a short timeout for this test because the file not found exception takes a long time otherwise, the timeout does not change the result + bl.FileName = AppConfig.MySqlBulkLoaderLocalCsvFile + "-junk"; + bl.TableName = m_testTable; + bl.CharacterSet = "UTF8"; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.FieldTerminator = ","; + bl.FieldQuotationCharacter = '"'; + bl.FieldQuotationOptional = true; + bl.Expressions.Add("five = UNHEX(five)"); + bl.Local = true; + try { - connection.Open(); - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - bl.Timeout = 3; //Set a short timeout for this test because the file not found exception takes a long time otherwise, the timeout does not change the result - bl.FileName = AppConfig.MySqlBulkLoaderLocalCsvFile + "-junk"; - bl.TableName = m_testTable; - bl.CharacterSet = "UTF8"; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.FieldTerminator = ","; - bl.FieldQuotationCharacter = '"'; - bl.FieldQuotationOptional = true; - bl.Expressions.Add("five = UNHEX(five)"); - bl.Local = true; - try - { - int rowCount = bl.Load(); - } - catch (MySqlException mySqlException) + int rowCount = bl.Load(); + } + catch (MySqlException mySqlException) + { + while (mySqlException.InnerException is object) { - while (mySqlException.InnerException is object) + if (mySqlException.InnerException is MySqlException innerException) { - if (mySqlException.InnerException is MySqlException innerException) - { - mySqlException = innerException; - } - else - { - Assert.IsType(mySqlException.InnerException); - break; - } + mySqlException = innerException; } - if (mySqlException.InnerException is null) + else { - Assert.IsType(mySqlException); + Assert.IsType(mySqlException.InnerException); + break; } } - catch (Exception exception) + if (mySqlException.InnerException is null) { - //We know that the exception is not a MySqlException, just use the assertion to fail the test - Assert.IsType(exception); + Assert.IsType(mySqlException); } } - } - - [SkippableFact(ConfigSettings.LocalCsvFile)] - public void BulkLoadLocalCsvFileInTransactionWithCommit() - { - using (var connection = new MySqlConnection(GetLocalConnectionString())) + catch (Exception exception) { - connection.Open(); - using (var transaction = connection.BeginTransaction()) - { - var bulkLoader = new MySqlBulkLoader(connection) - { - FileName = AppConfig.MySqlBulkLoaderLocalCsvFile, - TableName = m_testTable, - CharacterSet = "UTF8", - NumberOfLinesToSkip = 1, - FieldTerminator = ",", - FieldQuotationCharacter = '"', - FieldQuotationOptional = true, - Local = true, - }; - bulkLoader.Expressions.Add("five = UNHEX(five)"); - bulkLoader.Columns.AddRange(new[] { "one", "two", "three", "four", "five" }); - - var rowCount = bulkLoader.Load(); - Assert.Equal(20, rowCount); - - transaction.Commit(); - } - - Assert.Equal(20, connection.ExecuteScalar($@"select count(*) from {m_testTable};")); + //We know that the exception is not a MySqlException, just use the assertion to fail the test + Assert.IsType(exception); } } [SkippableFact(ConfigSettings.LocalCsvFile)] - public void BulkLoadLocalCsvFileBeforeTransactionWithCommit() + public void BulkLoadLocalCsvFileInTransactionWithCommit() { - using (var connection = new MySqlConnection(GetLocalConnectionString())) + using var connection = new MySqlConnection(GetLocalConnectionString()); + connection.Open(); + using (var transaction = connection.BeginTransaction()) { - connection.Open(); var bulkLoader = new MySqlBulkLoader(connection) { FileName = AppConfig.MySqlBulkLoaderLocalCsvFile, @@ -300,56 +253,52 @@ public void BulkLoadLocalCsvFileBeforeTransactionWithCommit() bulkLoader.Expressions.Add("five = UNHEX(five)"); bulkLoader.Columns.AddRange(new[] { "one", "two", "three", "four", "five" }); - using (var transaction = connection.BeginTransaction()) - { - var rowCount = bulkLoader.Load(); - Assert.Equal(20, rowCount); - - transaction.Commit(); - } + var rowCount = bulkLoader.Load(); + Assert.Equal(20, rowCount); - Assert.Equal(20, connection.ExecuteScalar($@"select count(*) from {m_testTable};")); + transaction.Commit(); } + + Assert.Equal(20, connection.ExecuteScalar($@"select count(*) from {m_testTable};")); } [SkippableFact(ConfigSettings.LocalCsvFile)] - public void BulkLoadLocalCsvFileInTransactionWithRollback() + public void BulkLoadLocalCsvFileBeforeTransactionWithCommit() { - using (var connection = new MySqlConnection(GetLocalConnectionString())) + using var connection = new MySqlConnection(GetLocalConnectionString()); + connection.Open(); + var bulkLoader = new MySqlBulkLoader(connection) { - connection.Open(); - using (var transaction = connection.BeginTransaction()) - { - var bulkLoader = new MySqlBulkLoader(connection) - { - FileName = AppConfig.MySqlBulkLoaderLocalCsvFile, - TableName = m_testTable, - CharacterSet = "UTF8", - NumberOfLinesToSkip = 1, - FieldTerminator = ",", - FieldQuotationCharacter = '"', - FieldQuotationOptional = true, - Local = true, - }; - bulkLoader.Expressions.Add("five = UNHEX(five)"); - bulkLoader.Columns.AddRange(new[] { "one", "two", "three", "four", "five" }); - - var rowCount = bulkLoader.Load(); - Assert.Equal(20, rowCount); - - transaction.Rollback(); - } + FileName = AppConfig.MySqlBulkLoaderLocalCsvFile, + TableName = m_testTable, + CharacterSet = "UTF8", + NumberOfLinesToSkip = 1, + FieldTerminator = ",", + FieldQuotationCharacter = '"', + FieldQuotationOptional = true, + Local = true, + }; + bulkLoader.Expressions.Add("five = UNHEX(five)"); + bulkLoader.Columns.AddRange(new[] { "one", "two", "three", "four", "five" }); + + using (var transaction = connection.BeginTransaction()) + { + var rowCount = bulkLoader.Load(); + Assert.Equal(20, rowCount); - Assert.Equal(0, connection.ExecuteScalar($@"select count(*) from {m_testTable};")); + transaction.Commit(); } + + Assert.Equal(20, connection.ExecuteScalar($@"select count(*) from {m_testTable};")); } [SkippableFact(ConfigSettings.LocalCsvFile)] - public void BulkLoadLocalCsvFileBeforeTransactionWithRollback() + public void BulkLoadLocalCsvFileInTransactionWithRollback() { - using (var connection = new MySqlConnection(GetLocalConnectionString())) + using var connection = new MySqlConnection(GetLocalConnectionString()); + connection.Open(); + using (var transaction = connection.BeginTransaction()) { - connection.Open(); var bulkLoader = new MySqlBulkLoader(connection) { FileName = AppConfig.MySqlBulkLoaderLocalCsvFile, @@ -364,178 +313,182 @@ public void BulkLoadLocalCsvFileBeforeTransactionWithRollback() bulkLoader.Expressions.Add("five = UNHEX(five)"); bulkLoader.Columns.AddRange(new[] { "one", "two", "three", "four", "five" }); - using (var transaction = connection.BeginTransaction()) - { - var rowCount = bulkLoader.Load(); - Assert.Equal(20, rowCount); + var rowCount = bulkLoader.Load(); + Assert.Equal(20, rowCount); - transaction.Rollback(); - } + transaction.Rollback(); + } + + Assert.Equal(0, connection.ExecuteScalar($@"select count(*) from {m_testTable};")); + } - Assert.Equal(0, connection.ExecuteScalar($@"select count(*) from {m_testTable};")); + [SkippableFact(ConfigSettings.LocalCsvFile)] + public void BulkLoadLocalCsvFileBeforeTransactionWithRollback() + { + using var connection = new MySqlConnection(GetLocalConnectionString()); + connection.Open(); + var bulkLoader = new MySqlBulkLoader(connection) + { + FileName = AppConfig.MySqlBulkLoaderLocalCsvFile, + TableName = m_testTable, + CharacterSet = "UTF8", + NumberOfLinesToSkip = 1, + FieldTerminator = ",", + FieldQuotationCharacter = '"', + FieldQuotationOptional = true, + Local = true, + }; + bulkLoader.Expressions.Add("five = UNHEX(five)"); + bulkLoader.Columns.AddRange(new[] { "one", "two", "three", "four", "five" }); + + using (var transaction = connection.BeginTransaction()) + { + var rowCount = bulkLoader.Load(); + Assert.Equal(20, rowCount); + + transaction.Rollback(); } + + Assert.Equal(0, connection.ExecuteScalar($@"select count(*) from {m_testTable};")); } [Fact] public void BulkLoadMissingFileName() { - using (var connection = new MySqlConnection(GetConnectionString())) - { - connection.Open(); - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - bl.TableName = m_testTable; - bl.CharacterSet = "UTF8"; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.FieldTerminator = ","; - bl.FieldQuotationCharacter = '"'; - bl.FieldQuotationOptional = true; - bl.Expressions.Add("five = UNHEX(five)"); - bl.Local = false; + using var connection = new MySqlConnection(GetConnectionString()); + connection.Open(); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + bl.TableName = m_testTable; + bl.CharacterSet = "UTF8"; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.FieldTerminator = ","; + bl.FieldQuotationCharacter = '"'; + bl.FieldQuotationOptional = true; + bl.Expressions.Add("five = UNHEX(five)"); + bl.Local = false; #if BASELINE - Assert.Throws(() => - { - int rowCount = bl.Load(); - }); + Assert.Throws(() => + { + int rowCount = bl.Load(); + }); #else - Assert.Throws(() => - { - int rowCount = bl.Load(); - }); + Assert.Throws(() => + { + int rowCount = bl.Load(); + }); #endif - } } [SkippableFact(ConfigSettings.LocalCsvFile)] public void BulkLoadMissingTableName() { - using (var connection = new MySqlConnection(GetConnectionString())) - { - connection.Open(); - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - bl.FileName = AppConfig.MySqlBulkLoaderLocalCsvFile; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.FieldTerminator = ","; - bl.FieldQuotationCharacter = '"'; - bl.FieldQuotationOptional = true; - bl.Expressions.Add("five = UNHEX(five)"); - bl.Local = false; + using var connection = new MySqlConnection(GetConnectionString()); + connection.Open(); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + bl.FileName = AppConfig.MySqlBulkLoaderLocalCsvFile; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.FieldTerminator = ","; + bl.FieldQuotationCharacter = '"'; + bl.FieldQuotationOptional = true; + bl.Expressions.Add("five = UNHEX(five)"); + bl.Local = false; #if BASELINE - Assert.Throws(() => - { - int rowCount = bl.Load(); - }); + Assert.Throws(() => + { + int rowCount = bl.Load(); + }); #else - Assert.Throws(() => - { - int rowCount = bl.Load(); - }); + Assert.Throws(() => + { + int rowCount = bl.Load(); + }); #endif - } } #if !BASELINE [SkippableFact(ConfigSettings.LocalCsvFile)] public void BulkLoadFileStreamInvalidOperation() { - using (var connection = new MySqlConnection(GetConnectionString())) + using var connection = new MySqlConnection(GetConnectionString()); + connection.Open(); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + using var fileStream = new FileStream(AppConfig.MySqlBulkLoaderLocalCsvFile, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true); + bl.SourceStream = fileStream; + bl.TableName = m_testTable; + bl.CharacterSet = "UTF8"; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.FieldTerminator = ","; + bl.FieldQuotationCharacter = '"'; + bl.FieldQuotationOptional = true; + bl.Expressions.Add("five = UNHEX(five)"); + bl.Local = false; + Assert.Throws(() => { - connection.Open(); - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - using (var fileStream = new FileStream(AppConfig.MySqlBulkLoaderLocalCsvFile, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) - { - bl.SourceStream = fileStream; - bl.TableName = m_testTable; - bl.CharacterSet = "UTF8"; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.FieldTerminator = ","; - bl.FieldQuotationCharacter = '"'; - bl.FieldQuotationOptional = true; - bl.Expressions.Add("five = UNHEX(five)"); - bl.Local = false; - Assert.Throws(() => - { - int rowCount = bl.Load(); - }); - } - } + int rowCount = bl.Load(); + }); } [SkippableFact(ConfigSettings.LocalCsvFile)] public void BulkLoadLocalFileStream() { - using (var connection = new MySqlConnection(GetLocalConnectionString())) - { - connection.Open(); - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - using (var fileStream = new FileStream(AppConfig.MySqlBulkLoaderLocalCsvFile, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) - { - bl.SourceStream = fileStream; - bl.TableName = m_testTable; - bl.CharacterSet = "UTF8"; - bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); - bl.NumberOfLinesToSkip = 1; - bl.FieldTerminator = ","; - bl.FieldQuotationCharacter = '"'; - bl.FieldQuotationOptional = true; - bl.Expressions.Add("five = UNHEX(five)"); - bl.Local = true; - int rowCount = bl.Load(); - Assert.Equal(20, rowCount); - } - } + using var connection = new MySqlConnection(GetLocalConnectionString()); + connection.Open(); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + using var fileStream = new FileStream(AppConfig.MySqlBulkLoaderLocalCsvFile, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true); + bl.SourceStream = fileStream; + bl.TableName = m_testTable; + bl.CharacterSet = "UTF8"; + bl.Columns.AddRange(new string[] { "one", "two", "three", "four", "five" }); + bl.NumberOfLinesToSkip = 1; + bl.FieldTerminator = ","; + bl.FieldQuotationCharacter = '"'; + bl.FieldQuotationOptional = true; + bl.Expressions.Add("five = UNHEX(five)"); + bl.Local = true; + int rowCount = bl.Load(); + Assert.Equal(20, rowCount); } [Fact] public void BulkLoadMemoryStreamInvalidOperation() { - using (var connection = new MySqlConnection(GetConnectionString())) - { - connection.Open(); - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - using (var memoryStream = new MemoryStream(m_memoryStreamBytes, false)) - { - bl.SourceStream = memoryStream; - bl.TableName = m_testTable; - bl.CharacterSet = "UTF8"; - bl.Columns.AddRange(new string[] { "one", "two", "three" }); - bl.NumberOfLinesToSkip = 0; - bl.FieldTerminator = ","; - bl.FieldQuotationCharacter = '"'; - bl.FieldQuotationOptional = true; - bl.Local = false; - Assert.Throws(() => - { - int rowCount = bl.Load(); - }); - } - } + using var connection = new MySqlConnection(GetConnectionString()); + connection.Open(); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + using var memoryStream = new MemoryStream(m_memoryStreamBytes, false); + bl.SourceStream = memoryStream; + bl.TableName = m_testTable; + bl.CharacterSet = "UTF8"; + bl.Columns.AddRange(new string[] { "one", "two", "three" }); + bl.NumberOfLinesToSkip = 0; + bl.FieldTerminator = ","; + bl.FieldQuotationCharacter = '"'; + bl.FieldQuotationOptional = true; + bl.Local = false; + Assert.Throws(() => bl.Load()); } [Fact] public void BulkLoadLocalMemoryStream() { - using (var connection = new MySqlConnection(GetLocalConnectionString())) - { - connection.Open(); - MySqlBulkLoader bl = new MySqlBulkLoader(connection); - using (var memoryStream = new MemoryStream(m_memoryStreamBytes, false)) - { - bl.SourceStream = memoryStream; - bl.TableName = m_testTable; - bl.CharacterSet = "UTF8"; - bl.Columns.AddRange(new string[] { "one", "two", "three" }); - bl.NumberOfLinesToSkip = 0; - bl.FieldTerminator = ","; - bl.FieldQuotationCharacter = '"'; - bl.FieldQuotationOptional = true; - bl.Local = true; - int rowCount = bl.Load(); - Assert.Equal(5, rowCount); - } - } + using var connection = new MySqlConnection(GetLocalConnectionString()); + connection.Open(); + MySqlBulkLoader bl = new MySqlBulkLoader(connection); + using var memoryStream = new MemoryStream(m_memoryStreamBytes, false); + bl.SourceStream = memoryStream; + bl.TableName = m_testTable; + bl.CharacterSet = "UTF8"; + bl.Columns.AddRange(new string[] { "one", "two", "three" }); + bl.NumberOfLinesToSkip = 0; + bl.FieldTerminator = ","; + bl.FieldQuotationCharacter = '"'; + bl.FieldQuotationOptional = true; + bl.Local = true; + int rowCount = bl.Load(); + Assert.Equal(5, rowCount); } #endif internal static string GetConnectionString() => AppConfig.ConnectionString; diff --git a/tests/SideBySide/CancelTests.cs b/tests/SideBySide/CancelTests.cs index c67f8915e..1c636f804 100644 --- a/tests/SideBySide/CancelTests.cs +++ b/tests/SideBySide/CancelTests.cs @@ -18,139 +18,127 @@ public void Dispose() { // after cancelling, the connection should still be usable Assert.Equal(ConnectionState.Open, m_database.Connection.State); - using (var cmd = new MySqlCommand(@"select sum(value) from integers;", m_database.Connection)) - Assert.Equal(210m, cmd.ExecuteScalar()); + using var cmd = new MySqlCommand(@"select sum(value) from integers;", m_database.Connection); + Assert.Equal(210m, cmd.ExecuteScalar()); } [Fact] public void NoCancel() { - using (var cmd = new MySqlCommand("SELECT SLEEP(0.25)", m_database.Connection)) - { - var stopwatch = Stopwatch.StartNew(); - Assert.Equal(0L, Convert.ToInt64(cmd.ExecuteScalar())); - Assert.InRange(stopwatch.ElapsedMilliseconds, 100, 1000); - } + using var cmd = new MySqlCommand("SELECT SLEEP(0.25)", m_database.Connection); + var stopwatch = Stopwatch.StartNew(); + Assert.Equal(0L, Convert.ToInt64(cmd.ExecuteScalar())); + Assert.InRange(stopwatch.ElapsedMilliseconds, 100, 1000); } [SkippableFact(ServerFeatures.Timeout)] public void CancelCommand() { - using (var cmd = new MySqlCommand("SELECT SLEEP(5)", m_database.Connection)) + using var cmd = new MySqlCommand("SELECT SLEEP(5)", m_database.Connection); + var task = Task.Run(async () => { - var task = Task.Run(async () => - { - await Task.Delay(TimeSpan.FromSeconds(0.5)); - cmd.Cancel(); - }); + await Task.Delay(TimeSpan.FromSeconds(0.5)); + cmd.Cancel(); + }); - var stopwatch = Stopwatch.StartNew(); - TestUtilities.AssertIsOne(cmd.ExecuteScalar()); - Assert.InRange(stopwatch.ElapsedMilliseconds, 250, 2500); + var stopwatch = Stopwatch.StartNew(); + TestUtilities.AssertIsOne(cmd.ExecuteScalar()); + Assert.InRange(stopwatch.ElapsedMilliseconds, 250, 2500); - task.Wait(); // shouldn't throw - } + task.Wait(); // shouldn't throw } [SkippableFact(ServerFeatures.Timeout)] public void CancelReaderAsynchronously() { - using (var barrier = new Barrier(2)) - using (var cmd = new MySqlCommand(c_hugeQuery, m_database.Connection)) + using var barrier = new Barrier(2); + using var cmd = new MySqlCommand(c_hugeQuery, m_database.Connection); + var task = Task.Run(() => { - var task = Task.Run(() => - { - barrier.SignalAndWait(); - cmd.Cancel(); - }); + barrier.SignalAndWait(); + cmd.Cancel(); + }); - int rows = 0; - using (var reader = cmd.ExecuteReader()) + int rows = 0; + using (var reader = cmd.ExecuteReader()) + { + Assert.True(reader.Read()); + + barrier.SignalAndWait(); + try + { + while (reader.Read()) + rows++; + } + catch (MySqlException ex) { - Assert.True(reader.Read()); - - barrier.SignalAndWait(); - try - { - while (reader.Read()) - rows++; - } - catch (MySqlException ex) - { - Assert.Equal((int) MySqlErrorCode.QueryInterrupted, ex.Number); - } - - // query returns 25 billion rows; we shouldn't have read many of them - Assert.InRange(rows, 0, 10000000); + Assert.Equal((int) MySqlErrorCode.QueryInterrupted, ex.Number); } - task.Wait(); // shouldn't throw + // query returns 25 billion rows; we shouldn't have read many of them + Assert.InRange(rows, 0, 10000000); } + + task.Wait(); // shouldn't throw } [SkippableFact(ServerFeatures.Timeout)] public void CancelCommandBeforeRead() { - using (var cmd = new MySqlCommand(c_hugeQuery, m_database.Connection)) - { - using (var reader = cmd.ExecuteReader()) - { - cmd.Cancel(); + using var cmd = new MySqlCommand(c_hugeQuery, m_database.Connection); + using var reader = cmd.ExecuteReader(); + cmd.Cancel(); - var stopwatch = Stopwatch.StartNew(); - int rows = 0; - try - { - while (reader.Read()) - rows++; - } - catch (MySqlException ex) - { - Assert.Equal((int) MySqlErrorCode.QueryInterrupted, ex.Number); - } - Assert.False(reader.NextResult()); - TestUtilities.AssertDuration(stopwatch, 0, 1000); - Assert.InRange(rows, 0, 10000000); - } + var stopwatch = Stopwatch.StartNew(); + int rows = 0; + try + { + while (reader.Read()) + rows++; + } + catch (MySqlException ex) + { + Assert.Equal((int) MySqlErrorCode.QueryInterrupted, ex.Number); } + Assert.False(reader.NextResult()); + TestUtilities.AssertDuration(stopwatch, 0, 1000); + Assert.InRange(rows, 0, 10000000); } [SkippableFact(ServerFeatures.Timeout, Baseline = "Hangs in NextResult")] public void CancelMultiStatementReader() { - using (var barrier = new Barrier(2)) - using (var cmd = new MySqlCommand(c_hugeQuery + c_hugeQuery + c_hugeQuery, m_database.Connection)) + using var barrier = new Barrier(2); + using var cmd = new MySqlCommand(c_hugeQuery + c_hugeQuery + c_hugeQuery, m_database.Connection); + var task = Task.Run(() => { - var task = Task.Run(() => - { - barrier.SignalAndWait(); - cmd.Cancel(); - }); + barrier.SignalAndWait(); + cmd.Cancel(); + }); - int rows = 0; - using (var reader = cmd.ExecuteReader()) + int rows = 0; + using (var reader = cmd.ExecuteReader()) + { + Assert.True(reader.Read()); + + barrier.SignalAndWait(); + try + { + while (reader.Read()) + rows++; + } + catch (MySqlException ex) { - Assert.True(reader.Read()); - - barrier.SignalAndWait(); - try - { - while (reader.Read()) - rows++; - } - catch (MySqlException ex) - { - Assert.Equal((int) MySqlErrorCode.QueryInterrupted, ex.Number); - } - - // query returns 25 billion rows; we shouldn't have read many of them - Assert.InRange(rows, 0, 10000000); - - Assert.False(reader.NextResult()); + Assert.Equal((int) MySqlErrorCode.QueryInterrupted, ex.Number); } - task.Wait(); // shouldn't throw + // query returns 25 billion rows; we shouldn't have read many of them + Assert.InRange(rows, 0, 10000000); + + Assert.False(reader.NextResult()); } + + task.Wait(); // shouldn't throw } [SkippableFact(ServerFeatures.Timeout)] @@ -174,51 +162,45 @@ public void DapperQueryMultiple() [SkippableFact(ServerFeatures.Timeout)] public async Task CancelCommandWithTokenBeforeExecuteScalar() { - using (var cmd = new MySqlCommand("select 1;", m_database.Connection)) + using var cmd = new MySqlCommand("select 1;", m_database.Connection); + try { - try - { - await cmd.ExecuteScalarAsync(s_canceledToken); - Assert.True(false); - } - catch (OperationCanceledException ex) - { - Assert.Equal(s_canceledToken, ex.CancellationToken); - } + await cmd.ExecuteScalarAsync(s_canceledToken); + Assert.True(false); + } + catch (OperationCanceledException ex) + { + Assert.Equal(s_canceledToken, ex.CancellationToken); } } [SkippableFact(ServerFeatures.Timeout)] public async Task CancelCommandWithTokenBeforeExecuteNonQuery() { - using (var cmd = new MySqlCommand("select 1;", m_database.Connection)) + using var cmd = new MySqlCommand("select 1;", m_database.Connection); + try { - try - { - await cmd.ExecuteNonQueryAsync(s_canceledToken); - Assert.True(false); - } - catch (OperationCanceledException ex) - { - Assert.Equal(s_canceledToken, ex.CancellationToken); - } + await cmd.ExecuteNonQueryAsync(s_canceledToken); + Assert.True(false); + } + catch (OperationCanceledException ex) + { + Assert.Equal(s_canceledToken, ex.CancellationToken); } } [SkippableFact(ServerFeatures.Timeout)] public async Task CancelCommandWithTokenBeforeExecuteReader() { - using (var cmd = new MySqlCommand("select 1;", m_database.Connection)) + using var cmd = new MySqlCommand("select 1;", m_database.Connection); + try { - try - { - await cmd.ExecuteReaderAsync(s_canceledToken); - Assert.True(false); - } - catch (OperationCanceledException ex) - { - Assert.Equal(s_canceledToken, ex.CancellationToken); - } + await cmd.ExecuteReaderAsync(s_canceledToken); + Assert.True(false); + } + catch (OperationCanceledException ex) + { + Assert.Equal(s_canceledToken, ex.CancellationToken); } } @@ -272,256 +254,239 @@ public void ImplicitCancelWithDapper() [SkippableFact(ServerFeatures.Timeout)] public async Task CancelHugeQueryWithTokenAfterExecuteReader() { - using (var cmd = new MySqlCommand(c_hugeQuery, m_database.Connection)) - using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(0.5))) - using (var reader = await cmd.ExecuteReaderAsync(cts.Token)) + using var cmd = new MySqlCommand(c_hugeQuery, m_database.Connection); + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(0.5)); + using var reader = await cmd.ExecuteReaderAsync(cts.Token); + var rows = 0; + try { - var rows = 0; - try - { - while (await reader.ReadAsync(cts.Token)) - rows++; - Assert.True(false); - } - catch (OperationCanceledException ex) - { - Assert.Equal(cts.Token, ex.CancellationToken); - Assert.InRange(rows, 0, 10000000); - } - - // no more result sets - Assert.False(reader.Read()); - Assert.False(reader.NextResult()); + while (await reader.ReadAsync(cts.Token)) + rows++; + Assert.True(false); + } + catch (OperationCanceledException ex) + { + Assert.Equal(cts.Token, ex.CancellationToken); + Assert.InRange(rows, 0, 10000000); } + + // no more result sets + Assert.False(reader.Read()); + Assert.False(reader.NextResult()); } [SkippableFact(ServerFeatures.Timeout)] public async Task CancelHugeQueryWithTokenInNextResult() { - using (var cmd = new MySqlCommand(c_hugeQuery + "select 1, 2, 3;", m_database.Connection)) - using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(0.5))) - using (var reader = await cmd.ExecuteReaderAsync(cts.Token)) - { - // read first result set - Assert.True(await reader.ReadAsync(cts.Token)); + using var cmd = new MySqlCommand(c_hugeQuery + "select 1, 2, 3;", m_database.Connection); + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(0.5)); + using var reader = await cmd.ExecuteReaderAsync(cts.Token); - try - { - // skip to the next result set - Assert.True(await reader.NextResultAsync(cts.Token)); + // read first result set + Assert.True(await reader.ReadAsync(cts.Token)); - // shouldn't get here - Assert.True(false); - } - catch (OperationCanceledException ex) - { - Assert.Equal(cts.Token, ex.CancellationToken); - } + try + { + // skip to the next result set + Assert.True(await reader.NextResultAsync(cts.Token)); - // no more result sets - Assert.False(reader.Read()); - Assert.False(reader.NextResult()); + // shouldn't get here + Assert.True(false); + } + catch (OperationCanceledException ex) + { + Assert.Equal(cts.Token, ex.CancellationToken); } + + // no more result sets + Assert.False(reader.Read()); + Assert.False(reader.NextResult()); } [SkippableFact(ServerFeatures.Timeout)] public async Task CancelSlowQueryWithTokenAfterExecuteReader() { - using (var cmd = new MySqlCommand(c_slowQuery, m_database.Connection)) - using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(0.5))) + using var cmd = new MySqlCommand(c_slowQuery, m_database.Connection); + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(0.5)); + + // the call to ExecuteReader should block until the token is cancelled + var stopwatch = Stopwatch.StartNew(); + using var reader = await cmd.ExecuteReaderAsync(cts.Token); + TestUtilities.AssertDuration(stopwatch, 450, 3000); + + var rows = 0; + try { - // the call to ExecuteReader should block until the token is cancelled - var stopwatch = Stopwatch.StartNew(); - using (var reader = await cmd.ExecuteReaderAsync(cts.Token)) - { - TestUtilities.AssertDuration(stopwatch, 450, 3000); - - var rows = 0; - try - { - // the OperationCanceledException is thrown later, from ReadAsync - while (await reader.ReadAsync(cts.Token)) - rows++; - Assert.True(false); - } - catch (OperationCanceledException ex) - { - Assert.Equal(cts.Token, ex.CancellationToken); - Assert.InRange(rows, 0, 100); - } - } + // the OperationCanceledException is thrown later, from ReadAsync + while (await reader.ReadAsync(cts.Token)) + rows++; + Assert.True(false); + } + catch (OperationCanceledException ex) + { + Assert.Equal(cts.Token, ex.CancellationToken); + Assert.InRange(rows, 0, 100); } } [SkippableFact(ServerFeatures.Timeout)] public async Task CancelSlowQueryWithTokenAfterNextResult() { - using (var cmd = new MySqlCommand("SELECT 1; " + c_slowQuery, m_database.Connection)) - using (var reader = await cmd.ExecuteReaderAsync()) - { - // first resultset should be available immediately - Assert.True(reader.Read()); - Assert.Equal(1, reader.GetInt32(0)); - Assert.False(reader.Read()); - - using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(0.5))) - { - // the call to NextResult should block until the token is cancelled - var stopwatch = Stopwatch.StartNew(); - Assert.True(await reader.NextResultAsync(cts.Token)); - TestUtilities.AssertDuration(stopwatch, 450, 1500); - - int rows = 0; - try - { - // the OperationCanceledException is thrown later, from ReadAsync - while (await reader.ReadAsync(cts.Token)) - rows++; - } - catch (OperationCanceledException ex) - { - Assert.Equal(cts.Token, ex.CancellationToken); - Assert.InRange(rows, 0, 100); - } - } + using var cmd = new MySqlCommand("SELECT 1; " + c_slowQuery, m_database.Connection); + using var reader = await cmd.ExecuteReaderAsync(); - Assert.False(await reader.NextResultAsync()); - } - } + // first resultset should be available immediately + Assert.True(reader.Read()); + Assert.Equal(1, reader.GetInt32(0)); + Assert.False(reader.Read()); - [SkippableFact(ServerFeatures.Timeout)] - public async Task CancelMultiStatementInRead() - { - using (var cmd = new MySqlCommand(c_hugeQuery + c_hugeQuery + c_hugeQuery, m_database.Connection)) using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(0.5))) - using (var reader = await cmd.ExecuteReaderAsync()) { - var rows = 0; + // the call to NextResult should block until the token is cancelled + var stopwatch = Stopwatch.StartNew(); + Assert.True(await reader.NextResultAsync(cts.Token)); + TestUtilities.AssertDuration(stopwatch, 450, 1500); + + int rows = 0; try { + // the OperationCanceledException is thrown later, from ReadAsync while (await reader.ReadAsync(cts.Token)) rows++; - - Assert.True(false); } catch (OperationCanceledException ex) { Assert.Equal(cts.Token, ex.CancellationToken); - Assert.InRange(rows, 0, 10000000); + Assert.InRange(rows, 0, 100); } + } - // no more result sets; the whole command was cancelled - Assert.False(reader.Read()); - Assert.False(reader.NextResult()); + Assert.False(await reader.NextResultAsync()); + } + + [SkippableFact(ServerFeatures.Timeout)] + public async Task CancelMultiStatementInRead() + { + using var cmd = new MySqlCommand(c_hugeQuery + c_hugeQuery + c_hugeQuery, m_database.Connection); + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(0.5)); + using var reader = await cmd.ExecuteReaderAsync(); + var rows = 0; + try + { + while (await reader.ReadAsync(cts.Token)) + rows++; + + Assert.True(false); } + catch (OperationCanceledException ex) + { + Assert.Equal(cts.Token, ex.CancellationToken); + Assert.InRange(rows, 0, 10000000); + } + + // no more result sets; the whole command was cancelled + Assert.False(reader.Read()); + Assert.False(reader.NextResult()); } #if !BASELINE [SkippableFact(ServerFeatures.Timeout)] public void CancelBatchCommand() { - using (var batch = new MySqlBatch(m_database.Connection) + using var batch = new MySqlBatch(m_database.Connection) { BatchCommands = { new MySqlBatchCommand("SELECT SLEEP(5)"), }, - }) + }; + var task = Task.Run(async () => { - var task = Task.Run(async () => - { - await Task.Delay(TimeSpan.FromSeconds(0.5)); - batch.Cancel(); - }); + await Task.Delay(TimeSpan.FromSeconds(0.5)); + batch.Cancel(); + }); - var stopwatch = Stopwatch.StartNew(); - TestUtilities.AssertIsOne(batch.ExecuteScalar()); - Assert.InRange(stopwatch.ElapsedMilliseconds, 250, 2500); + var stopwatch = Stopwatch.StartNew(); + TestUtilities.AssertIsOne(batch.ExecuteScalar()); + Assert.InRange(stopwatch.ElapsedMilliseconds, 250, 2500); - task.Wait(); // shouldn't throw - } + task.Wait(); // shouldn't throw } [SkippableFact(ServerFeatures.Timeout)] public void CancelBatchReaderAsynchronously() { - using (var barrier = new Barrier(2)) - using (var batch = new MySqlBatch(m_database.Connection) + using var barrier = new Barrier(2); + using var batch = new MySqlBatch(m_database.Connection) { BatchCommands = { new MySqlBatchCommand(c_hugeQuery), }, - }) + }; + var task = Task.Run(() => { - var task = Task.Run(() => - { - barrier.SignalAndWait(); - batch.Cancel(); - }); + barrier.SignalAndWait(); + batch.Cancel(); + }); - int rows = 0; - using (var reader = batch.ExecuteReader()) + int rows = 0; + using (var reader = batch.ExecuteReader()) + { + Assert.True(reader.Read()); + + barrier.SignalAndWait(); + try + { + while (reader.Read()) + rows++; + } + catch (MySqlException ex) { - Assert.True(reader.Read()); - - barrier.SignalAndWait(); - try - { - while (reader.Read()) - rows++; - } - catch (MySqlException ex) - { - Assert.Equal((int) MySqlErrorCode.QueryInterrupted, ex.Number); - } - - // query returns 25 billion rows; we shouldn't have read many of them - Assert.InRange(rows, 0, 10000000); + Assert.Equal((int) MySqlErrorCode.QueryInterrupted, ex.Number); } - task.Wait(); // shouldn't throw + // query returns 25 billion rows; we shouldn't have read many of them + Assert.InRange(rows, 0, 10000000); } + + task.Wait(); // shouldn't throw } [SkippableFact(ServerFeatures.Timeout)] public void CancelBatchBeforeRead() { - using (var batch = new MySqlBatch(m_database.Connection) + using var batch = new MySqlBatch(m_database.Connection) { BatchCommands = { new MySqlBatchCommand(c_hugeQuery), }, - }) - { - using (var reader = batch.ExecuteReader()) - { - batch.Cancel(); + }; + using var reader = batch.ExecuteReader(); + batch.Cancel(); - var stopwatch = Stopwatch.StartNew(); - int rows = 0; - try - { - while (reader.Read()) - rows++; - } - catch (MySqlException ex) - { - Assert.Equal((int) MySqlErrorCode.QueryInterrupted, ex.Number); - } - Assert.False(reader.NextResult()); - TestUtilities.AssertDuration(stopwatch, 0, 1000); - Assert.InRange(rows, 0, 10000000); - } + var stopwatch = Stopwatch.StartNew(); + int rows = 0; + try + { + while (reader.Read()) + rows++; + } + catch (MySqlException ex) + { + Assert.Equal((int) MySqlErrorCode.QueryInterrupted, ex.Number); } + Assert.False(reader.NextResult()); + TestUtilities.AssertDuration(stopwatch, 0, 1000); + Assert.InRange(rows, 0, 10000000); } [SkippableFact(ServerFeatures.Timeout, Skip = "COM_MULTI")] public void CancelMultiCommandBatchReader() { - using (var barrier = new Barrier(2)) - using (var batch = new MySqlBatch(m_database.Connection) + using var barrier = new Barrier(2); + using var batch = new MySqlBatch(m_database.Connection) { BatchCommands = { @@ -529,106 +494,98 @@ public void CancelMultiCommandBatchReader() new MySqlBatchCommand(c_hugeQuery), new MySqlBatchCommand(c_hugeQuery), }, - }) + }; + var task = Task.Run(() => { - var task = Task.Run(() => - { - barrier.SignalAndWait(); - batch.Cancel(); - }); + barrier.SignalAndWait(); + batch.Cancel(); + }); - int rows = 0; - using (var reader = batch.ExecuteReader()) + int rows = 0; + using (var reader = batch.ExecuteReader()) + { + Assert.True(reader.Read()); + + barrier.SignalAndWait(); + try + { + while (reader.Read()) + rows++; + } + catch (MySqlException ex) { - Assert.True(reader.Read()); - - barrier.SignalAndWait(); - try - { - while (reader.Read()) - rows++; - } - catch (MySqlException ex) - { - Assert.Equal((int) MySqlErrorCode.QueryInterrupted, ex.Number); - } - - // query returns 25 billion rows; we shouldn't have read many of them - Assert.InRange(rows, 0, 10000000); - - Assert.False(reader.NextResult()); + Assert.Equal((int) MySqlErrorCode.QueryInterrupted, ex.Number); } - task.Wait(); // shouldn't throw + // query returns 25 billion rows; we shouldn't have read many of them + Assert.InRange(rows, 0, 10000000); + + Assert.False(reader.NextResult()); } + + task.Wait(); // shouldn't throw } [SkippableFact(ServerFeatures.Timeout)] public async Task CancelBatchWithTokenBeforeExecuteScalar() { - using (var batch = new MySqlBatch(m_database.Connection) + using var batch = new MySqlBatch(m_database.Connection) { BatchCommands = { new MySqlBatchCommand("select 1;"), }, - }) + }; + try { - try - { - await batch.ExecuteScalarAsync(s_canceledToken); - Assert.True(false); - } - catch (OperationCanceledException ex) - { - Assert.Equal(s_canceledToken, ex.CancellationToken); - } + await batch.ExecuteScalarAsync(s_canceledToken); + Assert.True(false); + } + catch (OperationCanceledException ex) + { + Assert.Equal(s_canceledToken, ex.CancellationToken); } } [SkippableFact(ServerFeatures.Timeout)] public async Task CancelBatchWithTokenBeforeExecuteNonQuery() { - using (var batch = new MySqlBatch(m_database.Connection) + using var batch = new MySqlBatch(m_database.Connection) { BatchCommands = { new MySqlBatchCommand("select 1;"), }, - }) + }; + try { - try - { - await batch.ExecuteNonQueryAsync(s_canceledToken); - Assert.True(false); - } - catch (OperationCanceledException ex) - { - Assert.Equal(s_canceledToken, ex.CancellationToken); - } + await batch.ExecuteNonQueryAsync(s_canceledToken); + Assert.True(false); + } + catch (OperationCanceledException ex) + { + Assert.Equal(s_canceledToken, ex.CancellationToken); } } [SkippableFact(ServerFeatures.Timeout)] public async Task CancelBatchWithTokenBeforeExecuteReader() { - using (var batch = new MySqlBatch(m_database.Connection) + using var batch = new MySqlBatch(m_database.Connection) { BatchCommands = { new MySqlBatchCommand("select 1;"), }, - }) + }; + try { - try - { - await batch.ExecuteReaderAsync(s_canceledToken); - Assert.True(false); - } - catch (OperationCanceledException ex) - { - Assert.Equal(s_canceledToken, ex.CancellationToken); - } + await batch.ExecuteReaderAsync(s_canceledToken); + Assert.True(false); + } + catch (OperationCanceledException ex) + { + Assert.Equal(s_canceledToken, ex.CancellationToken); } } @@ -667,153 +624,146 @@ value varchar(45) [SkippableFact(ServerFeatures.Timeout)] public async Task CancelHugeQueryBatchWithTokenAfterExecuteReader() { - using (var batch = new MySqlBatch(m_database.Connection) + using var batch = new MySqlBatch(m_database.Connection) { BatchCommands = { new MySqlBatchCommand(c_hugeQuery), }, - }) - using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(0.5))) - using (var reader = await batch.ExecuteReaderAsync(cts.Token)) + }; + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(0.5)); + using var reader = await batch.ExecuteReaderAsync(cts.Token); + var rows = 0; + try { - var rows = 0; - try - { - while (await reader.ReadAsync(cts.Token)) - rows++; - Assert.True(false); - } - catch (OperationCanceledException ex) - { - Assert.Equal(cts.Token, ex.CancellationToken); - Assert.InRange(rows, 0, 10000000); - } - - // no more result sets - Assert.False(reader.Read()); - Assert.False(reader.NextResult()); + while (await reader.ReadAsync(cts.Token)) + rows++; + Assert.True(false); } + catch (OperationCanceledException ex) + { + Assert.Equal(cts.Token, ex.CancellationToken); + Assert.InRange(rows, 0, 10000000); + } + + // no more result sets + Assert.False(reader.Read()); + Assert.False(reader.NextResult()); } [SkippableFact(ServerFeatures.Timeout, Skip = "COM_MULTI")] public async Task CancelHugeQueryBatchWithTokenInNextResult() { - using (var batch = new MySqlBatch(m_database.Connection) + using var batch = new MySqlBatch(m_database.Connection) { BatchCommands = { new MySqlBatchCommand(c_hugeQuery), new MySqlBatchCommand("select 1, 2, 3;"), }, - }) - using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(0.5))) - using (var reader = await batch.ExecuteReaderAsync(cts.Token)) - { - // read first result set - Assert.True(await reader.ReadAsync(cts.Token)); + }; + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(0.5)); + using var reader = await batch.ExecuteReaderAsync(cts.Token); - try - { - // skip to the next result set - Assert.True(await reader.NextResultAsync(cts.Token)); + // read first result set + Assert.True(await reader.ReadAsync(cts.Token)); - // shouldn't get here - Assert.True(false); - } - catch (OperationCanceledException ex) - { - Assert.Equal(cts.Token, ex.CancellationToken); - } + try + { + // skip to the next result set + Assert.True(await reader.NextResultAsync(cts.Token)); - // no more result sets - Assert.False(reader.Read()); - Assert.False(reader.NextResult()); + // shouldn't get here + Assert.True(false); + } + catch (OperationCanceledException ex) + { + Assert.Equal(cts.Token, ex.CancellationToken); } + + // no more result sets + Assert.False(reader.Read()); + Assert.False(reader.NextResult()); } [SkippableFact(ServerFeatures.Timeout)] public async Task CancelSlowQueryBatchWithTokenAfterExecuteReader() { - using (var batch = new MySqlBatch(m_database.Connection) + using var batch = new MySqlBatch(m_database.Connection) { BatchCommands = { new MySqlBatchCommand(c_slowQuery), }, - }) - using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(0.5))) + }; + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(0.5)); + + // the call to ExecuteReader should block until the token is cancelled + var stopwatch = Stopwatch.StartNew(); + using var reader = await batch.ExecuteReaderAsync(cts.Token); + TestUtilities.AssertDuration(stopwatch, 450, 3000); + + var rows = 0; + try { - // the call to ExecuteReader should block until the token is cancelled - var stopwatch = Stopwatch.StartNew(); - using (var reader = await batch.ExecuteReaderAsync(cts.Token)) - { - TestUtilities.AssertDuration(stopwatch, 450, 3000); - - var rows = 0; - try - { - // the OperationCanceledException is thrown later, from ReadAsync - while (await reader.ReadAsync(cts.Token)) - rows++; - Assert.True(false); - } - catch (OperationCanceledException ex) - { - Assert.Equal(cts.Token, ex.CancellationToken); - Assert.InRange(rows, 0, 100); - } - } + // the OperationCanceledException is thrown later, from ReadAsync + while (await reader.ReadAsync(cts.Token)) + rows++; + Assert.True(false); + } + catch (OperationCanceledException ex) + { + Assert.Equal(cts.Token, ex.CancellationToken); + Assert.InRange(rows, 0, 100); } } [SkippableFact(ServerFeatures.Timeout)] public async Task CancelSlowQueryBatchWithTokenAfterNextResult() { - using (var batch = new MySqlBatch(m_database.Connection) + using var batch = new MySqlBatch(m_database.Connection) { BatchCommands = { new MySqlBatchCommand("SELECT 1;"), new MySqlBatchCommand(c_slowQuery), }, - }) - using (var reader = await batch.ExecuteReaderAsync()) + }; + using var reader = await batch.ExecuteReaderAsync(); + + // first resultset should be available immediately + Assert.True(reader.Read()); + Assert.Equal(1, reader.GetInt32(0)); + Assert.False(reader.Read()); + + using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(0.5))) { - // first resultset should be available immediately - Assert.True(reader.Read()); - Assert.Equal(1, reader.GetInt32(0)); - Assert.False(reader.Read()); + // the call to NextResult should block until the token is cancelled + var stopwatch = Stopwatch.StartNew(); + Assert.True(await reader.NextResultAsync(cts.Token)); + TestUtilities.AssertDuration(stopwatch, 450, 1500); - using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(0.5))) + int rows = 0; + try { - // the call to NextResult should block until the token is cancelled - var stopwatch = Stopwatch.StartNew(); - Assert.True(await reader.NextResultAsync(cts.Token)); - TestUtilities.AssertDuration(stopwatch, 450, 1500); - - int rows = 0; - try - { - // the OperationCanceledException is thrown later, from ReadAsync - while (await reader.ReadAsync(cts.Token)) - rows++; - } - catch (OperationCanceledException ex) - { - Assert.Equal(cts.Token, ex.CancellationToken); - Assert.InRange(rows, 0, 100); - } + // the OperationCanceledException is thrown later, from ReadAsync + while (await reader.ReadAsync(cts.Token)) + rows++; + } + catch (OperationCanceledException ex) + { + Assert.Equal(cts.Token, ex.CancellationToken); + Assert.InRange(rows, 0, 100); } - - Assert.False(await reader.NextResultAsync()); } + + Assert.False(await reader.NextResultAsync()); } [SkippableFact(ServerFeatures.Timeout, Skip = "COM_MULTI")] public async Task CancelMultiStatementBatchInRead() { - using (var batch = new MySqlBatch(m_database.Connection) + using var batch = new MySqlBatch(m_database.Connection) { BatchCommands = { @@ -821,28 +771,26 @@ public async Task CancelMultiStatementBatchInRead() new MySqlBatchCommand(c_hugeQuery), new MySqlBatchCommand(c_hugeQuery), }, - }) - using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(0.5))) - using (var reader = await batch.ExecuteReaderAsync()) + }; + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(0.5)); + using var reader = await batch.ExecuteReaderAsync(); + var rows = 0; + try { - var rows = 0; - try - { - while (await reader.ReadAsync(cts.Token)) - rows++; + while (await reader.ReadAsync(cts.Token)) + rows++; - Assert.True(false); - } - catch (OperationCanceledException ex) - { - Assert.Equal(cts.Token, ex.CancellationToken); - Assert.InRange(rows, 0, 10000000); - } - - // no more result sets; the whole command was cancelled - Assert.False(reader.Read()); - Assert.False(reader.NextResult()); + Assert.True(false); } + catch (OperationCanceledException ex) + { + Assert.Equal(cts.Token, ex.CancellationToken); + Assert.InRange(rows, 0, 10000000); + } + + // no more result sets; the whole command was cancelled + Assert.False(reader.Read()); + Assert.False(reader.NextResult()); } #endif diff --git a/tests/SideBySide/CharacterSetTests.cs b/tests/SideBySide/CharacterSetTests.cs index 8da8ade09..dee9a5730 100644 --- a/tests/SideBySide/CharacterSetTests.cs +++ b/tests/SideBySide/CharacterSetTests.cs @@ -20,15 +20,13 @@ public CharacterSetTests(DatabaseFixture database) [Fact] public void MaxLength() { - using (var reader = m_database.Connection.ExecuteReader(@"select coll.ID, cs.MAXLEN from information_schema.collations coll inner join information_schema.character_sets cs using(CHARACTER_SET_NAME);")) + using var reader = m_database.Connection.ExecuteReader(@"select coll.ID, cs.MAXLEN from information_schema.collations coll inner join information_schema.character_sets cs using(CHARACTER_SET_NAME);"); + while (reader.Read()) { - while (reader.Read()) - { - var characterSet = (CharacterSet) reader.GetInt32(0); - var maxLength = reader.GetInt32(1); + var characterSet = (CharacterSet) reader.GetInt32(0); + var maxLength = reader.GetInt32(1); - Assert.Equal(maxLength, ProtocolUtility.GetBytesPerCharacter(characterSet)); - } + Assert.Equal(maxLength, ProtocolUtility.GetBytesPerCharacter(characterSet)); } } #endif @@ -40,33 +38,29 @@ public void IllegalMixOfCollations(bool reopenConnection) { var csb = AppConfig.CreateConnectionStringBuilder(); csb.AllowUserVariables = true; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); - connection.Execute(@" + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); + connection.Execute(@" DROP TABLE IF EXISTS mix_collations; CREATE TABLE mix_collations ( - id int(11) NOT NULL AUTO_INCREMENT, - test_col varchar(10) DEFAULT NULL, - PRIMARY KEY (id), - KEY ix_test (test_col) +id int(11) NOT NULL AUTO_INCREMENT, +test_col varchar(10) DEFAULT NULL, +PRIMARY KEY (id), +KEY ix_test (test_col) ); INSERT INTO mix_collations (test_col) VALUES ('a'), ('b'), ('c'), ('d'), ('e'), ('f'), ('g'), ('h'), ('i'), ('j');"); - if (reopenConnection) - { - connection.Close(); - connection.Open(); - } - - using (var reader = connection.ExecuteReader(@" - SET @param = 'B'; - SELECT * FROM mix_collations a WHERE a.test_col = @param")) - { - Assert.True(reader.Read()); - } + if (reopenConnection) + { + connection.Close(); + connection.Open(); } + + using var reader = connection.ExecuteReader(@" + SET @param = 'B'; + SELECT * FROM mix_collations a WHERE a.test_col = @param"); + Assert.True(reader.Read()); } [Theory] @@ -78,20 +72,18 @@ public void CollationConnection(bool reopenConnection) #if BASELINE csb.CharacterSet = "utf8mb4"; #endif - using (var connection = new MySqlConnection(csb.ConnectionString)) + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); + + if (reopenConnection) { + connection.Close(); connection.Open(); - - if (reopenConnection) - { - connection.Close(); - connection.Open(); - } - - var collation = connection.Query(@"select @@collation_connection;").Single(); - var expected = connection.ServerVersion.StartsWith("8.0") ? "utf8mb4_0900_ai_ci" : "utf8mb4_general_ci"; - Assert.Equal(expected, collation); } + + var collation = connection.Query(@"select @@collation_connection;").Single(); + var expected = connection.ServerVersion.StartsWith("8.0") ? "utf8mb4_0900_ai_ci" : "utf8mb4_general_ci"; + Assert.Equal(expected, collation); } readonly DatabaseFixture m_database; diff --git a/tests/SideBySide/CommandBuilderTests.cs b/tests/SideBySide/CommandBuilderTests.cs index 29243746f..e16d2ae9a 100644 --- a/tests/SideBySide/CommandBuilderTests.cs +++ b/tests/SideBySide/CommandBuilderTests.cs @@ -28,31 +28,25 @@ public void DeriveParametersNull() [SkippableFact(Baseline = "Throws NullReferenceException")] public void DeriveParametersNoConnection() { - using (var cmd = new MySqlCommand("test")) - { - cmd.CommandType = CommandType.StoredProcedure; - Assert.Throws(() => MySqlCommandBuilder.DeriveParameters(cmd)); - } + using var cmd = new MySqlCommand("test"); + cmd.CommandType = CommandType.StoredProcedure; + Assert.Throws(() => MySqlCommandBuilder.DeriveParameters(cmd)); } [SkippableFact(Baseline = "Throws InvalidOperationException")] public void DeriveParametersText() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "select 1;"; - Assert.Throws(() => MySqlCommandBuilder.DeriveParameters(cmd)); - } + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "select 1;"; + Assert.Throws(() => MySqlCommandBuilder.DeriveParameters(cmd)); } [SkippableFact(Baseline = "Throws MySqlException")] public void DeriveParametersNoCommandText() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandType = CommandType.StoredProcedure; - Assert.Throws(() => MySqlCommandBuilder.DeriveParameters(cmd)); - } + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandType = CommandType.StoredProcedure; + Assert.Throws(() => MySqlCommandBuilder.DeriveParameters(cmd)); } #if !NETCOREAPP1_1_2 diff --git a/tests/SideBySide/CommandTests.cs b/tests/SideBySide/CommandTests.cs index cc538ca52..b49eb5142 100644 --- a/tests/SideBySide/CommandTests.cs +++ b/tests/SideBySide/CommandTests.cs @@ -17,296 +17,236 @@ public CommandTests(DatabaseFixture database) [Fact] public void CreateCommandSetsConnection() { - using (var command = m_database.Connection.CreateCommand()) - { - Assert.Equal(m_database.Connection, command.Connection); - } + using var command = m_database.Connection.CreateCommand(); + Assert.Equal(m_database.Connection, command.Connection); } [Fact] public void CreateCommandDoesNotSetTransaction() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - { - connection.Open(); - using (connection.BeginTransaction()) - using (var cmd = connection.CreateCommand()) - { - Assert.Null(cmd.Transaction); - } - } + using var connection = new MySqlConnection(AppConfig.ConnectionString); + connection.Open(); + using var transaction = connection.BeginTransaction(); + using var cmd = connection.CreateCommand(); + Assert.Null(cmd.Transaction); } [Fact] public void ExecuteReaderRequiresConnection() { - using (var command = new MySqlCommand()) - { - Assert.Throws(() => command.ExecuteReader()); - } + using var command = new MySqlCommand(); + Assert.Throws(() => command.ExecuteReader()); } [Fact] public void ExecuteReaderRequiresOpenConnection() { - using (var connection = new MySqlConnection()) - using (var command = connection.CreateCommand()) - { - Assert.Throws(() => command.ExecuteReader()); - } + using var connection = new MySqlConnection(); + using var command = connection.CreateCommand(); + Assert.Throws(() => command.ExecuteReader()); } [Fact] public void PrepareRequiresConnection() { - using (var command = new MySqlCommand()) - { - Assert.Throws(() => command.Prepare()); - } + using var command = new MySqlCommand(); + Assert.Throws(() => command.Prepare()); } [Fact] public void PrepareRequiresOpenConnection() { - using (var connection = new MySqlConnection()) - using (var command = connection.CreateCommand()) - { - Assert.Throws(() => command.Prepare()); - } + using var connection = new MySqlConnection(); + using var command = connection.CreateCommand(); + Assert.Throws(() => command.Prepare()); } [Fact] public void NewCommandIsNotPrepared() { - using (var command = new MySqlCommand()) - Assert.False(command.IsPrepared); + using var command = new MySqlCommand(); + Assert.False(command.IsPrepared); } [Fact] public void CommandWithoutConnectionIsNotPrepared() { - using (var command = new MySqlCommand()) - { - command.CommandText = "SELECT 1"; - Assert.False(command.IsPrepared); - } + using var command = new MySqlCommand(); + command.CommandText = "SELECT 1"; + Assert.False(command.IsPrepared); } [Fact] public void CommandWithClosedConnectionIsNotPrepared() { - using (var connection = new MySqlConnection()) - using (var command = connection.CreateCommand()) - { - command.CommandText = "SELECT 1"; - Assert.False(command.IsPrepared); - } + using var connection = new MySqlConnection(); + using var command = connection.CreateCommand(); + command.CommandText = "SELECT 1"; + Assert.False(command.IsPrepared); } [Fact] public void ExecuteNonQueryForSelectReturnsNegativeOne() { - using (var connection = new MySqlConnection(m_database.Connection.ConnectionString)) - using (var command = connection.CreateCommand()) - { - connection.Open(); - command.CommandText = "SELECT 1;"; - Assert.Equal(-1, command.ExecuteNonQuery()); - } + using var connection = new MySqlConnection(m_database.Connection.ConnectionString); + using var command = connection.CreateCommand(); + connection.Open(); + command.CommandText = "SELECT 1;"; + Assert.Equal(-1, command.ExecuteNonQuery()); } [Fact] public async Task ExecuteNonQueryReturnValue() { - using (var connection = new MySqlConnection(m_database.Connection.ConnectionString)) - { - await connection.OpenAsync(); - await connection.ExecuteAsync(@"drop table if exists execute_non_query; + using var connection = new MySqlConnection(m_database.Connection.ConnectionString); + await connection.OpenAsync(); + await connection.ExecuteAsync(@"drop table if exists execute_non_query; create table execute_non_query(id integer not null primary key auto_increment, value text null);"); - Assert.Equal(4, await connection.ExecuteAsync("insert into execute_non_query(value) values(null), (null), ('one'), ('two');")); - Assert.Equal(-1, await connection.ExecuteAsync("select value from execute_non_query;")); - Assert.Equal(2, await connection.ExecuteAsync("delete from execute_non_query where value is null;")); - Assert.Equal(1, await connection.ExecuteAsync("update execute_non_query set value = 'three' where value = 'one';")); - } + Assert.Equal(4, await connection.ExecuteAsync("insert into execute_non_query(value) values(null), (null), ('one'), ('two');")); + Assert.Equal(-1, await connection.ExecuteAsync("select value from execute_non_query;")); + Assert.Equal(2, await connection.ExecuteAsync("delete from execute_non_query where value is null;")); + Assert.Equal(1, await connection.ExecuteAsync("update execute_non_query set value = 'three' where value = 'one';")); } [SkippableFact(Baseline = "https://bugs.mysql.com/bug.php?id=88611")] public void CommandTransactionMustBeSet() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - { - connection.Open(); - using (var transaction = connection.BeginTransaction()) - using (var command = connection.CreateCommand()) - { - command.CommandText = "SELECT 1;"; - Assert.Throws(() => command.ExecuteScalar()); - - command.Transaction = transaction; - TestUtilities.AssertIsOne(command.ExecuteScalar()); - } - } + using var connection = new MySqlConnection(AppConfig.ConnectionString); + connection.Open(); + using var transaction = connection.BeginTransaction(); + using var command = connection.CreateCommand(); + command.CommandText = "SELECT 1;"; + Assert.Throws(() => command.ExecuteScalar()); + + command.Transaction = transaction; + TestUtilities.AssertIsOne(command.ExecuteScalar()); } [Fact] public void IgnoreCommandTransactionIgnoresNull() { - using (var connection = new MySqlConnection(GetIgnoreCommandTransactionConnectionString())) - { - connection.Open(); - using (connection.BeginTransaction()) - using (var command = connection.CreateCommand()) - { - command.CommandText = "SELECT 1;"; - TestUtilities.AssertIsOne(command.ExecuteScalar()); - } - } + using var connection = new MySqlConnection(GetIgnoreCommandTransactionConnectionString()); + connection.Open(); + using var _ = connection.BeginTransaction(); + using var command = connection.CreateCommand(); + command.CommandText = "SELECT 1;"; + TestUtilities.AssertIsOne(command.ExecuteScalar()); } [Fact] public void IgnoreCommandTransactionIgnoresDisposedTransaction() { - using (var connection = new MySqlConnection(GetIgnoreCommandTransactionConnectionString())) - { - connection.Open(); - - var transaction = connection.BeginTransaction(); - transaction.Commit(); - transaction.Dispose(); - - using (var command = connection.CreateCommand()) - { - command.CommandText = "SELECT 1;"; - command.Transaction = transaction; - TestUtilities.AssertIsOne(command.ExecuteScalar()); - } - } + using var connection = new MySqlConnection(GetIgnoreCommandTransactionConnectionString()); + connection.Open(); + + var transaction = connection.BeginTransaction(); + transaction.Commit(); + transaction.Dispose(); + + using var command = connection.CreateCommand(); + command.CommandText = "SELECT 1;"; + command.Transaction = transaction; + TestUtilities.AssertIsOne(command.ExecuteScalar()); } [Fact] 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 command2 = connection2.CreateCommand()) - { - command2.Transaction = transaction1; - command2.CommandText = "SELECT 1;"; - TestUtilities.AssertIsOne(command2.ExecuteScalar()); - } - } + using var connection1 = new MySqlConnection(AppConfig.ConnectionString); + using var connection2 = new MySqlConnection(GetIgnoreCommandTransactionConnectionString()); + connection1.Open(); + connection2.Open(); + + using var transaction1 = connection1.BeginTransaction(); + using var command2 = connection2.CreateCommand(); + command2.Transaction = transaction1; + command2.CommandText = "SELECT 1;"; + TestUtilities.AssertIsOne(command2.ExecuteScalar()); } [Fact] public void ThrowsIfNamedParameterUsedButNoParametersDefined() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - { - connection.Open(); - using (var cmd = new MySqlCommand("SELECT @param;", connection)) - { - Assert.Throws(() => cmd.ExecuteScalar()); - } - } + using var connection = new MySqlConnection(AppConfig.ConnectionString); + connection.Open(); + using var cmd = new MySqlCommand("SELECT @param;", connection); + Assert.Throws(() => cmd.ExecuteScalar()); } [Fact] public void ThrowsIfUnnamedParameterUsedButNoParametersDefined() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - { - connection.Open(); - using (var cmd = new MySqlCommand("SELECT ?;", connection)) - { + using var connection = new MySqlConnection(AppConfig.ConnectionString); + connection.Open(); + using var cmd = new MySqlCommand("SELECT ?;", connection); #if BASELINE - Assert.Throws(() => cmd.ExecuteScalar()); + Assert.Throws(() => cmd.ExecuteScalar()); #else - Assert.Throws(() => cmd.ExecuteScalar()); + Assert.Throws(() => cmd.ExecuteScalar()); #endif - } - } } [Fact] public void ThrowsIfUndefinedNamedParameterUsed() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - { - connection.Open(); - using (var cmd = new MySqlCommand("SELECT @param;", connection)) - { - cmd.Parameters.AddWithValue("@name", "test"); - Assert.Throws(() => cmd.ExecuteScalar()); - } - } + using var connection = new MySqlConnection(AppConfig.ConnectionString); + connection.Open(); + using var cmd = new MySqlCommand("SELECT @param;", connection); + cmd.Parameters.AddWithValue("@name", "test"); + Assert.Throws(() => cmd.ExecuteScalar()); } [Fact] public void ThrowsIfTooManyUnnamedParametersUsed() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - { - connection.Open(); - using (var cmd = new MySqlCommand("SELECT ?, ?;", connection)) - { - cmd.Parameters.Add(new MySqlParameter { Value = 1 }); + using var connection = new MySqlConnection(AppConfig.ConnectionString); + connection.Open(); + using var cmd = new MySqlCommand("SELECT ?, ?;", connection); + cmd.Parameters.Add(new MySqlParameter { Value = 1 }); #if BASELINE - Assert.Throws(() => cmd.ExecuteScalar()); + Assert.Throws(() => cmd.ExecuteScalar()); #else - Assert.Throws(() => cmd.ExecuteScalar()); + Assert.Throws(() => cmd.ExecuteScalar()); #endif - } - } } [Fact] public void CloneCommand() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) + using var connection = new MySqlConnection(AppConfig.ConnectionString); + connection.Open(); + using var transaction = connection.BeginTransaction(); + var param = new MySqlParameter("@param", MySqlDbType.Decimal) { Value = 12.3m }; + using var cmd = new MySqlCommand("SELECT @param;", connection, transaction) { - connection.Open(); - using (var transaction = connection.BeginTransaction()) - { - var param = new MySqlParameter("@param", MySqlDbType.Decimal) { Value = 12.3m }; - using (var cmd = new MySqlCommand("SELECT @param;", connection, transaction) - { - CommandType = CommandType.StoredProcedure, - Parameters = { param }, - }) - { - using (var cmd2 = (MySqlCommand) cmd.Clone()) - { - Assert.Equal(cmd.Connection, cmd2.Connection); - Assert.Equal(cmd.Transaction, cmd2.Transaction); - Assert.Equal(cmd.CommandText, cmd2.CommandText); - Assert.Equal(cmd.CommandType, cmd2.CommandType); - Assert.Single(cmd2.Parameters); - - var param2 = cmd2.Parameters[0]; - Assert.Equal(param.ParameterName, param2.ParameterName); - Assert.Equal(param.MySqlDbType, param2.MySqlDbType); - Assert.Equal(param.Value, param2.Value); - - cmd.CommandText = "New text"; - Assert.NotEqual(cmd.CommandText, cmd2.CommandText); - - param.Value = 0m; - Assert.NotEqual(0m, cmd2.Parameters[0].Value); - } - } - } - } + CommandType = CommandType.StoredProcedure, + Parameters = { param }, + }; + using var cmd2 = (MySqlCommand) cmd.Clone(); + + Assert.Equal(cmd.Connection, cmd2.Connection); + Assert.Equal(cmd.Transaction, cmd2.Transaction); + Assert.Equal(cmd.CommandText, cmd2.CommandText); + Assert.Equal(cmd.CommandType, cmd2.CommandType); + Assert.Single(cmd2.Parameters); + + var param2 = cmd2.Parameters[0]; + Assert.Equal(param.ParameterName, param2.ParameterName); + Assert.Equal(param.MySqlDbType, param2.MySqlDbType); + Assert.Equal(param.Value, param2.Value); + + cmd.CommandText = "New text"; + Assert.NotEqual(cmd.CommandText, cmd2.CommandText); + + param.Value = 0m; + Assert.NotEqual(0m, cmd2.Parameters[0].Value); } [SkippableFact(Baseline = "https://bugs.mysql.com/bug.php?id=94075")] public void CancelEmptyCommandIsNoop() { - using (var cmd = new MySqlCommand()) - cmd.Cancel(); + using var cmd = new MySqlCommand(); + cmd.Cancel(); } private static string GetIgnoreCommandTransactionConnectionString() diff --git a/tests/SideBySide/CommandTimeoutTests.cs b/tests/SideBySide/CommandTimeoutTests.cs index 7e2bb8a4e..f07befb57 100644 --- a/tests/SideBySide/CommandTimeoutTests.cs +++ b/tests/SideBySide/CommandTimeoutTests.cs @@ -35,30 +35,24 @@ public void DefaultCommandTimeoutIsInherited(int defaultCommandTimeout) var csb = AppConfig.CreateConnectionStringBuilder(); csb.DefaultCommandTimeout = (uint) defaultCommandTimeout; - using (var connection = new MySqlConnection(csb.ConnectionString)) - using (var command = connection.CreateCommand()) - { - Assert.Equal(defaultCommandTimeout, command.CommandTimeout); - } + using var connection = new MySqlConnection(csb.ConnectionString); + using var command = connection.CreateCommand(); + Assert.Equal(defaultCommandTimeout, command.CommandTimeout); } [SkippableFact(Baseline = "https://bugs.mysql.com/bug.php?id=87316")] public void NegativeCommandTimeout() { - using (var command = m_connection.CreateCommand()) - { - Assert.Throws(() => command.CommandTimeout = -1); - } + using var command = m_connection.CreateCommand(); + Assert.Throws(() => command.CommandTimeout = -1); } [Fact] public void LargeCommandTimeoutIsCoerced() { - using (var command = m_connection.CreateCommand()) - { - command.CommandTimeout = 2_000_000_000; - Assert.Equal(2_147_483, command.CommandTimeout); - } + using var command = m_connection.CreateCommand(); + command.CommandTimeout = 2_000_000_000; + Assert.Equal(2_147_483, command.CommandTimeout); } [SkippableFact(ServerFeatures.Timeout)] @@ -70,11 +64,10 @@ public void CommandTimeoutWithSleepSync() var sw = Stopwatch.StartNew(); try { - using (var reader = cmd.ExecuteReader()) - { - // shouldn't get here - Assert.True(false); - } + using var reader = cmd.ExecuteReader(); + + // shouldn't get here + Assert.True(false); } catch (MySqlException ex) { @@ -96,11 +89,10 @@ public async Task CommandTimeoutWithSleepAsync() var sw = Stopwatch.StartNew(); try { - using (var reader = await cmd.ExecuteReaderAsync()) - { - // shouldn't get here - Assert.True(false); - } + using var reader = await cmd.ExecuteReaderAsync(); + + // shouldn't get here + Assert.True(false); } catch (MySqlException ex) { @@ -118,40 +110,37 @@ public async Task CommandTimeoutWithSleepAsync() [InlineData(false)] public void CommandTimeoutWithStoredProcedureSleepSync(bool pooling) { - using (var cmd = new MySqlCommand(@"drop procedure if exists sleep_sproc; + using (var setupCmd = new MySqlCommand(@"drop procedure if exists sleep_sproc; create procedure sleep_sproc(IN seconds INT) begin select sleep(seconds); end;", m_connection)) { - cmd.ExecuteNonQuery(); + setupCmd.ExecuteNonQuery(); } var csb = AppConfig.CreateConnectionStringBuilder(); csb.Pooling = pooling; - using (var connection = new MySqlConnection(csb.ConnectionString)) - using (var cmd = new MySqlCommand("sleep_sproc", connection)) + using var connection = new MySqlConnection(csb.ConnectionString); + using var cmd = new MySqlCommand("sleep_sproc", connection); + connection.Open(); + cmd.CommandType = CommandType.StoredProcedure; + cmd.Parameters.AddWithValue("seconds", 10); + cmd.CommandTimeout = 2; + + var sw = Stopwatch.StartNew(); + try { - connection.Open(); - cmd.CommandType = CommandType.StoredProcedure; - cmd.Parameters.AddWithValue("seconds", 10); - cmd.CommandTimeout = 2; + using var reader = cmd.ExecuteReader(); - var sw = Stopwatch.StartNew(); - try - { - using (var reader = cmd.ExecuteReader()) - { - // shouldn't get here - Assert.True(false); - } - } - catch (MySqlException ex) - { - sw.Stop(); - Assert.Contains(c_timeoutMessage, ex.Message, StringComparison.OrdinalIgnoreCase); - TestUtilities.AssertDuration(sw, ((int) cmd.CommandTimeout) * 1000 - 100, 500); - } + // shouldn't get here + Assert.True(false); + } + catch (MySqlException ex) + { + sw.Stop(); + Assert.Contains(c_timeoutMessage, ex.Message, StringComparison.OrdinalIgnoreCase); + TestUtilities.AssertDuration(sw, ((int) cmd.CommandTimeout) * 1000 - 100, 500); } } @@ -166,22 +155,20 @@ public void MultipleCommandTimeoutWithSleepSync() var sw = Stopwatch.StartNew(); try { - using (var reader = cmd.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Equal(1, reader.GetInt32(0)); - Assert.False(reader.Read()); - readFirstResultSet = true; - - // the following call to a public API resets the internal timer - sw.Restart(); - - reader.NextResult(); - - // shouldn't get here - TestUtilities.AssertDuration(sw, cmd.CommandTimeout * 1000 - 100, 500); - Assert.True(false); - } + using var reader = cmd.ExecuteReader(); + Assert.True(reader.Read()); + Assert.Equal(1, reader.GetInt32(0)); + Assert.False(reader.Read()); + readFirstResultSet = true; + + // the following call to a public API resets the internal timer + sw.Restart(); + + reader.NextResult(); + + // shouldn't get here + TestUtilities.AssertDuration(sw, cmd.CommandTimeout * 1000 - 100, 500); + Assert.True(false); } catch (MySqlException ex) { @@ -206,21 +193,19 @@ public async Task MultipleCommandTimeoutWithSleepAsync() var sw = Stopwatch.StartNew(); try { - using (var reader = await cmd.ExecuteReaderAsync()) - { - Assert.True(await reader.ReadAsync()); - Assert.Equal(1, reader.GetInt32(0)); - Assert.False(await reader.ReadAsync()); - readFirstResultSet = true; + using var reader = await cmd.ExecuteReaderAsync(); + Assert.True(await reader.ReadAsync()); + Assert.Equal(1, reader.GetInt32(0)); + Assert.False(await reader.ReadAsync()); + readFirstResultSet = true; - // the following call to a public API resets the internal timer - sw.Restart(); + // the following call to a public API resets the internal timer + sw.Restart(); - await reader.NextResultAsync(); + await reader.NextResultAsync(); - // shouldn't get here - Assert.True(false); - } + // shouldn't get here + Assert.True(false); } catch (MySqlException ex) { @@ -241,15 +226,14 @@ public void CommandTimeoutResetsOnReadSync() using (var cmd = new MySqlCommand("SELECT SLEEP(1); SELECT SLEEP(1); SELECT SLEEP(1); SELECT SLEEP(1); SELECT SLEEP(1);", m_connection)) { cmd.CommandTimeout = 3; - using (var reader = cmd.ExecuteReader()) + using var reader = cmd.ExecuteReader(); + + for (int i = 0; i < 5; i++) { - for (int i = 0; i < 5; i++) - { - Assert.True(reader.Read()); - Assert.Equal(0, reader.GetInt32(0)); - Assert.False(reader.Read()); - Assert.Equal(i < 4, reader.NextResult()); - } + Assert.True(reader.Read()); + Assert.Equal(0, reader.GetInt32(0)); + Assert.False(reader.Read()); + Assert.Equal(i < 4, reader.NextResult()); } } @@ -263,15 +247,14 @@ public async Task CommandTimeoutResetsOnReadAsync() using (var cmd = new MySqlCommand("SELECT SLEEP(1); SELECT SLEEP(1); SELECT SLEEP(1); SELECT SLEEP(1); SELECT SLEEP(1);", m_connection)) { cmd.CommandTimeout = 3; - using (var reader = await cmd.ExecuteReaderAsync()) + using var reader = await cmd.ExecuteReaderAsync(); + + for (int i = 0; i < 5; i++) { - for (int i = 0; i < 5; i++) - { - Assert.True(await reader.ReadAsync()); - Assert.Equal(0, reader.GetInt32(0)); - Assert.False(await reader.ReadAsync()); - Assert.Equal(i < 4, await reader.NextResultAsync()); - } + Assert.True(await reader.ReadAsync()); + Assert.Equal(0, reader.GetInt32(0)); + Assert.False(await reader.ReadAsync()); + Assert.Equal(i < 4, await reader.NextResultAsync()); } } @@ -289,11 +272,10 @@ public void TransactionCommandTimeoutWithSleepSync() var sw = Stopwatch.StartNew(); try { - using (var reader = cmd.ExecuteReader()) - { - // shouldn't get here - Assert.True(false); - } + using var reader = cmd.ExecuteReader(); + + // shouldn't get here + Assert.True(false); } catch (MySqlException ex) { @@ -316,11 +298,10 @@ public async Task TransactionCommandTimeoutWithSleepAsync() var sw = Stopwatch.StartNew(); try { - using (var reader = await cmd.ExecuteReaderAsync()) - { - // shouldn't get here - Assert.True(false); - } + using var reader = await cmd.ExecuteReaderAsync(); + + // shouldn't get here + Assert.True(false); } catch (MySqlException ex) { diff --git a/tests/SideBySide/ConnectAsync.cs b/tests/SideBySide/ConnectAsync.cs index 104c946c5..70ba7d241 100644 --- a/tests/SideBySide/ConnectAsync.cs +++ b/tests/SideBySide/ConnectAsync.cs @@ -26,21 +26,19 @@ public async Task ConnectBadHost() { Server = "invalid.example.com", }; - using (var connection = new MySqlConnection(csb.ConnectionString)) + using var connection = new MySqlConnection(csb.ConnectionString); + Assert.Equal(ConnectionState.Closed, connection.State); + try + { + await connection.OpenAsync(); + Assert.True(false, "Exception not thrown"); + } + catch (MySqlException ex) { - Assert.Equal(ConnectionState.Closed, connection.State); - try - { - await connection.OpenAsync(); - Assert.True(false, "Exception not thrown"); - } - catch (MySqlException ex) - { - Assert.Equal((int) MySqlErrorCode.UnableToConnectToHost, ex.Number); - Assert.Equal((int) MySqlErrorCode.UnableToConnectToHost, ex.Data["Server Error Code"]); - } - Assert.Equal(ConnectionState.Closed, connection.State); + Assert.Equal((int) MySqlErrorCode.UnableToConnectToHost, ex.Number); + Assert.Equal((int) MySqlErrorCode.UnableToConnectToHost, ex.Data["Server Error Code"]); } + Assert.Equal(ConnectionState.Closed, connection.State); } [Fact] @@ -51,12 +49,10 @@ public async Task ConnectBadPort() Server = "localhost", Port = 65000, }; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - Assert.Equal(ConnectionState.Closed, connection.State); - await Assert.ThrowsAsync(() => connection.OpenAsync()); - Assert.Equal(ConnectionState.Closed, connection.State); - } + using var connection = new MySqlConnection(csb.ConnectionString); + Assert.Equal(ConnectionState.Closed, connection.State); + await Assert.ThrowsAsync(() => connection.OpenAsync()); + Assert.Equal(ConnectionState.Closed, connection.State); } [Fact] @@ -64,24 +60,20 @@ public async Task ConnectBadPassword() { var csb = AppConfig.CreateConnectionStringBuilder(); csb.Password = "wrong"; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - await Assert.ThrowsAsync(() => connection.OpenAsync()); - Assert.Equal(ConnectionState.Closed, connection.State); - } + using var connection = new MySqlConnection(csb.ConnectionString); + await Assert.ThrowsAsync(() => connection.OpenAsync()); + Assert.Equal(ConnectionState.Closed, connection.State); } [Fact] public async Task State() { - using (var connection = new MySqlConnection(m_database.Connection.ConnectionString)) - { - Assert.Equal(ConnectionState.Closed, connection.State); - await connection.OpenAsync(); - Assert.Equal(ConnectionState.Open, connection.State); - await connection.CloseAsync(); - Assert.Equal(ConnectionState.Closed, connection.State); - } + using var connection = new MySqlConnection(m_database.Connection.ConnectionString); + Assert.Equal(ConnectionState.Closed, connection.State); + await connection.OpenAsync(); + Assert.Equal(ConnectionState.Open, connection.State); + await connection.CloseAsync(); + Assert.Equal(ConnectionState.Closed, connection.State); } [SkippableFact(ConfigSettings.TcpConnection, Baseline = "https://bugs.mysql.com/bug.php?id=81650")] @@ -90,12 +82,10 @@ public async Task ConnectMultipleHostNames() var csb = AppConfig.CreateConnectionStringBuilder(); csb.Server = "invalid.example.net," + csb.Server; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - Assert.Equal(ConnectionState.Closed, connection.State); - await connection.OpenAsync(); - Assert.Equal(ConnectionState.Open, connection.State); - } + using var connection = new MySqlConnection(csb.ConnectionString); + Assert.Equal(ConnectionState.Closed, connection.State); + await connection.OpenAsync(); + Assert.Equal(ConnectionState.Open, connection.State); } [SkippableFact(ConfigSettings.PasswordlessUser)] @@ -106,12 +96,10 @@ public async Task ConnectNoPassword() csb.Password = ""; csb.Database = ""; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - Assert.Equal(ConnectionState.Closed, connection.State); - await connection.OpenAsync().ConfigureAwait(false); - Assert.Equal(ConnectionState.Open, connection.State); - } + using var connection = new MySqlConnection(csb.ConnectionString); + Assert.Equal(ConnectionState.Closed, connection.State); + await connection.OpenAsync().ConfigureAwait(false); + Assert.Equal(ConnectionState.Open, connection.State); } [Fact] @@ -120,11 +108,9 @@ public async Task ConnectKeepAlive() // the goal of this test is to ensure that no exceptions are thrown var csb = AppConfig.CreateConnectionStringBuilder(); csb.Keepalive = 1; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - await connection.OpenAsync(); - await Task.Delay(3000); - } + using var connection = new MySqlConnection(csb.ConnectionString); + await connection.OpenAsync(); + await Task.Delay(3000); } [SkippableFact(ServerFeatures.Timeout)] @@ -137,21 +123,19 @@ public async Task ConnectTimeoutAsync() ConnectionTimeout = 2, }; - using (var connection = new MySqlConnection(csb.ConnectionString)) + using var connection = new MySqlConnection(csb.ConnectionString); + var stopwatch = Stopwatch.StartNew(); + try + { + await connection.OpenAsync(); + Assert.True(false); + } + catch (MySqlException ex) { - var stopwatch = Stopwatch.StartNew(); - try - { - await connection.OpenAsync(); - Assert.True(false); - } - catch (MySqlException ex) - { - Assert.Equal((int) MySqlErrorCode.UnableToConnectToHost, ex.Number); - } - stopwatch.Stop(); - TestUtilities.AssertDuration(stopwatch, 1900, 1500); + Assert.Equal((int) MySqlErrorCode.UnableToConnectToHost, ex.Number); } + stopwatch.Stop(); + TestUtilities.AssertDuration(stopwatch, 1900, 1500); } @@ -168,92 +152,80 @@ public async Task ConnectTimeoutAsyncCancellationToken() Pooling = false, }; - using (var connection = new MySqlConnection(csb.ConnectionString)) + using var connection = new MySqlConnection(csb.ConnectionString); + var stopwatch = Stopwatch.StartNew(); + try + { + using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2))) + await connection.OpenAsync(cts.Token); + Assert.True(false); + } + catch (MySqlException ex) { - var stopwatch = Stopwatch.StartNew(); - try - { - using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2))) - await connection.OpenAsync(cts.Token); - Assert.True(false); - } - catch (MySqlException ex) - { - Assert.Equal((int) MySqlErrorCode.UnableToConnectToHost, ex.Number); - } - stopwatch.Stop(); - TestUtilities.AssertDuration(stopwatch, 1900, 1500); + Assert.Equal((int) MySqlErrorCode.UnableToConnectToHost, ex.Number); } + stopwatch.Stop(); + TestUtilities.AssertDuration(stopwatch, 1900, 1500); } [Fact] public async Task ConnectionDatabase() { var csb = AppConfig.CreateConnectionStringBuilder(); - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - Assert.Equal(csb.Database, connection.Database); + using var connection = new MySqlConnection(csb.ConnectionString); + Assert.Equal(csb.Database, connection.Database); - await connection.OpenAsync(); + await connection.OpenAsync(); - Assert.Equal(csb.Database, connection.Database); - Assert.Equal(csb.Database, await QueryCurrentDatabaseAsync(connection)); - } + Assert.Equal(csb.Database, connection.Database); + Assert.Equal(csb.Database, await QueryCurrentDatabaseAsync(connection)); } [SkippableFact(ConfigSettings.SecondaryDatabase)] public async Task ChangeDatabase() { var csb = AppConfig.CreateConnectionStringBuilder(); - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - await connection.OpenAsync(); + using var connection = new MySqlConnection(csb.ConnectionString); + await connection.OpenAsync(); - Assert.Equal(csb.Database, connection.Database); - Assert.Equal(csb.Database, await QueryCurrentDatabaseAsync(connection)); + Assert.Equal(csb.Database, connection.Database); + Assert.Equal(csb.Database, await QueryCurrentDatabaseAsync(connection)); - await connection.ChangeDatabaseAsync(AppConfig.SecondaryDatabase); + await connection.ChangeDatabaseAsync(AppConfig.SecondaryDatabase); - Assert.Equal(AppConfig.SecondaryDatabase, connection.Database); - Assert.Equal(AppConfig.SecondaryDatabase, await QueryCurrentDatabaseAsync(connection)); - } + Assert.Equal(AppConfig.SecondaryDatabase, connection.Database); + Assert.Equal(AppConfig.SecondaryDatabase, await QueryCurrentDatabaseAsync(connection)); } [SkippableFact(ConfigSettings.SecondaryDatabase)] public async Task ChangeDatabaseNotOpen() { var csb = AppConfig.CreateConnectionStringBuilder(); - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - await Assert.ThrowsAsync(() => connection.ChangeDatabaseAsync(AppConfig.SecondaryDatabase)); - } + using var connection = new MySqlConnection(csb.ConnectionString); + await Assert.ThrowsAsync(() => connection.ChangeDatabaseAsync(AppConfig.SecondaryDatabase)); } [SkippableFact(ConfigSettings.SecondaryDatabase)] public async Task ChangeDatabaseNull() { var csb = AppConfig.CreateConnectionStringBuilder(); - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - await Assert.ThrowsAsync(() => connection.ChangeDatabaseAsync(null)); - await Assert.ThrowsAsync(() => connection.ChangeDatabaseAsync("")); - } + using var connection = new MySqlConnection(csb.ConnectionString); + await Assert.ThrowsAsync(() => connection.ChangeDatabaseAsync(null)); + await Assert.ThrowsAsync(() => connection.ChangeDatabaseAsync("")); } [SkippableFact(ConfigSettings.SecondaryDatabase)] public async Task ChangeDatabaseInvalidName() { var csb = AppConfig.CreateConnectionStringBuilder(); - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); - await Assert.ThrowsAsync(() => connection.ChangeDatabaseAsync($"not_a_real_database_1234")); + await Assert.ThrowsAsync(() => connection.ChangeDatabaseAsync($"not_a_real_database_1234")); - Assert.Equal(ConnectionState.Open, connection.State); - Assert.Equal(csb.Database, connection.Database); - Assert.Equal(csb.Database, await QueryCurrentDatabaseAsync(connection)); - } + Assert.Equal(ConnectionState.Open, connection.State); + Assert.Equal(csb.Database, connection.Database); + Assert.Equal(csb.Database, await QueryCurrentDatabaseAsync(connection)); } [SkippableFact(ConfigSettings.SecondaryDatabase)] @@ -266,18 +238,16 @@ public async Task ChangeDatabaseConnectionPooling() for (int i = 0; i < csb.MaximumPoolSize * 2; i++) { - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - await connection.OpenAsync(); + using var connection = new MySqlConnection(csb.ConnectionString); + await connection.OpenAsync(); - Assert.Equal(csb.Database, connection.Database); - Assert.Equal(csb.Database, await QueryCurrentDatabaseAsync(connection)); + Assert.Equal(csb.Database, connection.Database); + Assert.Equal(csb.Database, await QueryCurrentDatabaseAsync(connection)); - await connection.ChangeDatabaseAsync(AppConfig.SecondaryDatabase); + await connection.ChangeDatabaseAsync(AppConfig.SecondaryDatabase); - Assert.Equal(AppConfig.SecondaryDatabase, connection.Database); - Assert.Equal(AppConfig.SecondaryDatabase, await QueryCurrentDatabaseAsync(connection)); - } + Assert.Equal(AppConfig.SecondaryDatabase, connection.Database); + Assert.Equal(AppConfig.SecondaryDatabase, await QueryCurrentDatabaseAsync(connection)); } } @@ -285,39 +255,35 @@ public async Task ChangeDatabaseConnectionPooling() public async Task UseDatabase() { var csb = AppConfig.CreateConnectionStringBuilder(); - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); - Assert.Equal(csb.Database, connection.Database); - Assert.Equal(csb.Database, await QueryCurrentDatabaseAsync(connection)); - - using (var cmd = connection.CreateCommand()) - { - cmd.CommandText = $"USE {AppConfig.SecondaryDatabase};"; - await cmd.ExecuteNonQueryAsync(); - } + Assert.Equal(csb.Database, connection.Database); + Assert.Equal(csb.Database, await QueryCurrentDatabaseAsync(connection)); - Assert.Equal(AppConfig.SecondaryDatabase, connection.Database); - Assert.Equal(AppConfig.SecondaryDatabase, await QueryCurrentDatabaseAsync(connection)); + using (var cmd = connection.CreateCommand()) + { + cmd.CommandText = $"USE {AppConfig.SecondaryDatabase};"; + await cmd.ExecuteNonQueryAsync(); } + + Assert.Equal(AppConfig.SecondaryDatabase, connection.Database); + Assert.Equal(AppConfig.SecondaryDatabase, await QueryCurrentDatabaseAsync(connection)); } private static async Task QueryCurrentDatabaseAsync(MySqlConnection connection) { - using (var cmd = connection.CreateCommand()) - { - cmd.CommandText = "SELECT DATABASE()"; - return (string) await cmd.ExecuteScalarAsync(); - } + using var cmd = connection.CreateCommand(); + cmd.CommandText = "SELECT DATABASE()"; + return (string) await cmd.ExecuteScalarAsync(); } [SkippableFact(ServerFeatures.Sha256Password, ConfigSettings.RequiresSsl)] public async Task Sha256WithSecureConnection() { var csb = AppConfig.CreateSha256ConnectionStringBuilder(); - using (var connection = new MySqlConnection(csb.ConnectionString)) - await connection.OpenAsync(); + using var connection = new MySqlConnection(csb.ConnectionString); + await connection.OpenAsync(); } [SkippableFact(ServerFeatures.Sha256Password)] @@ -326,21 +292,19 @@ public async Task Sha256WithoutSecureConnection() var csb = AppConfig.CreateSha256ConnectionStringBuilder(); csb.SslMode = MySqlSslMode.None; csb.AllowPublicKeyRetrieval = true; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - if (AppConfig.SupportedFeatures.HasFlag(ServerFeatures.RsaEncryption)) - await connection.OpenAsync(); - else - await Assert.ThrowsAsync(() => connection.OpenAsync()); - } + using var connection = new MySqlConnection(csb.ConnectionString); + if (AppConfig.SupportedFeatures.HasFlag(ServerFeatures.RsaEncryption)) + await connection.OpenAsync(); + else + await Assert.ThrowsAsync(() => connection.OpenAsync()); } [SkippableFact(ServerFeatures.CachingSha2Password, ConfigSettings.RequiresSsl)] public async Task CachingSha2WithSecureConnection() { var csb = AppConfig.CreateCachingSha2ConnectionStringBuilder(); - using (var connection = new MySqlConnection(csb.ConnectionString)) - await connection.OpenAsync(); + using var connection = new MySqlConnection(csb.ConnectionString); + await connection.OpenAsync(); } [SkippableFact(ServerFeatures.CachingSha2Password)] @@ -349,10 +313,8 @@ public async Task CachingSha2WithoutSecureConnection() var csb = AppConfig.CreateCachingSha2ConnectionStringBuilder(); csb.SslMode = MySqlSslMode.None; csb.AllowPublicKeyRetrieval = true; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - await connection.OpenAsync(); - } + using var connection = new MySqlConnection(csb.ConnectionString); + await connection.OpenAsync(); } #if !BASELINE @@ -366,8 +328,8 @@ public async Task Ed25519Authentication() csb.UserID = "ed25519user"; csb.Password = "Ed255!9"; csb.Database = null; - using (var connection = new MySqlConnection(csb.ConnectionString)) - await connection.OpenAsync(); + using var connection = new MySqlConnection(csb.ConnectionString); + await connection.OpenAsync(); } #endif #endif @@ -387,10 +349,8 @@ public async Task Ed25519Authentication() public async Task AuthGSSAPI() { var csb = AppConfig.CreateGSSAPIConnectionStringBuilder(); - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - await connection.OpenAsync(); - } + using var connection = new MySqlConnection(csb.ConnectionString); + await connection.OpenAsync(); } #if !BASELINE @@ -403,11 +363,9 @@ public async Task GoodServerSPN() using (var connection = new MySqlConnection(csb.ConnectionString)) { await connection.OpenAsync(); - using (var cmd = connection.CreateCommand()) - { - cmd.CommandText = "select @@gssapi_principal_name"; - serverSPN = (string) await cmd.ExecuteScalarAsync(); - } + using var cmd = connection.CreateCommand(); + cmd.CommandText = "select @@gssapi_principal_name"; + serverSPN = (string) await cmd.ExecuteScalarAsync(); } csb.ServerSPN = serverSPN; using (var connection = new MySqlConnection(csb.ConnectionString)) @@ -421,34 +379,30 @@ public async Task BadServerSPN() { var csb = AppConfig.CreateGSSAPIConnectionStringBuilder(); csb.ServerSPN = "BadServerSPN"; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - await Assert.ThrowsAsync(() => connection.OpenAsync()); - } + using var connection = new MySqlConnection(csb.ConnectionString); + await Assert.ThrowsAsync(() => connection.OpenAsync()); } [Fact] public async Task PingNoConnection() { - using (var connection = new MySqlConnection()) - Assert.False(await connection.PingAsync()); + using var connection = new MySqlConnection(); + Assert.False(await connection.PingAsync()); } [Fact] public async Task PingBeforeConnecting() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - Assert.False(await connection.PingAsync()); + using var connection = new MySqlConnection(AppConfig.ConnectionString); + Assert.False(await connection.PingAsync()); } [Fact] public async Task PingConnection() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - { - await connection.OpenAsync(); - Assert.True(await connection.PingAsync()); - } + using var connection = new MySqlConnection(AppConfig.ConnectionString); + await connection.OpenAsync(); + Assert.True(await connection.PingAsync()); } #endif diff --git a/tests/SideBySide/ConnectSync.cs b/tests/SideBySide/ConnectSync.cs index 5a80da869..315b76501 100644 --- a/tests/SideBySide/ConnectSync.cs +++ b/tests/SideBySide/ConnectSync.cs @@ -21,21 +21,19 @@ public void ConnectBadHost() { Server = "invalid.example.com", }; - using (var connection = new MySqlConnection(csb.ConnectionString)) + using var connection = new MySqlConnection(csb.ConnectionString); + Assert.Equal(ConnectionState.Closed, connection.State); + try { - Assert.Equal(ConnectionState.Closed, connection.State); - try - { - connection.Open(); - Assert.True(false, "Exception not thrown"); - } - catch (MySqlException ex) - { - Assert.Equal((int) MySqlErrorCode.UnableToConnectToHost, ex.Number); - Assert.Equal((int) MySqlErrorCode.UnableToConnectToHost, ex.Data["Server Error Code"]); - } - Assert.Equal(ConnectionState.Closed, connection.State); + connection.Open(); + Assert.True(false, "Exception not thrown"); + } + catch (MySqlException ex) + { + Assert.Equal((int) MySqlErrorCode.UnableToConnectToHost, ex.Number); + Assert.Equal((int) MySqlErrorCode.UnableToConnectToHost, ex.Data["Server Error Code"]); } + Assert.Equal(ConnectionState.Closed, connection.State); } [Fact] @@ -46,12 +44,10 @@ public void ConnectBadPort() Server = "localhost", Port = 65000, }; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - Assert.Equal(ConnectionState.Closed, connection.State); - Assert.Throws(() => connection.Open()); - Assert.Equal(ConnectionState.Closed, connection.State); - } + using var connection = new MySqlConnection(csb.ConnectionString); + Assert.Equal(ConnectionState.Closed, connection.State); + Assert.Throws(() => connection.Open()); + Assert.Equal(ConnectionState.Closed, connection.State); } [Fact] @@ -62,10 +58,8 @@ public void ConnectInvalidPort() Server = "localhost", Port = 1000000, }; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - Assert.Throws(() => connection.Open()); - } + using var connection = new MySqlConnection(csb.ConnectionString); + Assert.Throws(() => connection.Open()); } [Fact] @@ -73,25 +67,23 @@ public void ConnectBadDatabase() { var csb = AppConfig.CreateConnectionStringBuilder(); csb.Database = "wrong_database"; - using (var connection = new MySqlConnection(csb.ConnectionString)) + using var connection = new MySqlConnection(csb.ConnectionString); + try + { + connection.Open(); + Assert.True(false); + } + catch (MySqlException ex) { - try - { - connection.Open(); - Assert.True(false); - } - catch (MySqlException ex) - { #if BASELINE - // https://bugs.mysql.com/bug.php?id=78426 - Assert.NotNull(ex); + // https://bugs.mysql.com/bug.php?id=78426 + Assert.NotNull(ex); #else - if (AppConfig.SupportedFeatures.HasFlag(ServerFeatures.ErrorCodes) || ex.Number != 0) - Assert.Equal((int) MySqlErrorCode.UnknownDatabase, ex.Number); + if (AppConfig.SupportedFeatures.HasFlag(ServerFeatures.ErrorCodes) || ex.Number != 0) + Assert.Equal((int) MySqlErrorCode.UnknownDatabase, ex.Number); #endif - } - Assert.Equal(ConnectionState.Closed, connection.State); } + Assert.Equal(ConnectionState.Closed, connection.State); } [Fact] @@ -99,25 +91,23 @@ public void ConnectBadPassword() { var csb = AppConfig.CreateConnectionStringBuilder(); csb.Password = "wrong"; - using (var connection = new MySqlConnection(csb.ConnectionString)) + using var connection = new MySqlConnection(csb.ConnectionString); + try + { + connection.Open(); + Assert.True(false); + } + catch (MySqlException ex) { - try - { - connection.Open(); - Assert.True(false); - } - catch (MySqlException ex) - { #if BASELINE - // https://bugs.mysql.com/bug.php?id=73610 - Assert.NotNull(ex); + // https://bugs.mysql.com/bug.php?id=73610 + Assert.NotNull(ex); #else - if (AppConfig.SupportedFeatures.HasFlag(ServerFeatures.ErrorCodes) || ex.Number != 0) - Assert.Equal((int) MySqlErrorCode.AccessDenied, ex.Number); + if (AppConfig.SupportedFeatures.HasFlag(ServerFeatures.ErrorCodes) || ex.Number != 0) + Assert.Equal((int) MySqlErrorCode.AccessDenied, ex.Number); #endif - } - Assert.Equal(ConnectionState.Closed, connection.State); } + Assert.Equal(ConnectionState.Closed, connection.State); } #if !BASELINE @@ -126,10 +116,8 @@ public void ConnectBadPassword() [InlineData("server=pipename;Protocol=Pipe;LoadBalance=Failover")] public void LoadBalanceNotSupported(string connectionString) { - using (var connection = new MySqlConnection(connectionString)) - { - Assert.Throws(() => connection.Open()); - } + using var connection = new MySqlConnection(connectionString); + Assert.Throws(() => connection.Open()); } #endif @@ -144,37 +132,33 @@ public void PersistSecurityInfo(bool persistSecurityInfo, bool closeConnection) csb.PersistSecurityInfo = persistSecurityInfo; var connectionStringWithoutPassword = Regex.Replace(csb.ConnectionString, @"(?i)password='?" + Regex.Escape(csb.Password) + "'?;?", ""); - using (var connection = new MySqlConnection(csb.ConnectionString)) - { + using var connection = new MySqlConnection(csb.ConnectionString); + Assert.Equal(csb.ConnectionString, connection.ConnectionString); + connection.Open(); + if (persistSecurityInfo) Assert.Equal(csb.ConnectionString, connection.ConnectionString); - connection.Open(); + else + Assert.Equal(connectionStringWithoutPassword, connection.ConnectionString); + + if (closeConnection) + { + connection.Close(); if (persistSecurityInfo) Assert.Equal(csb.ConnectionString, connection.ConnectionString); else Assert.Equal(connectionStringWithoutPassword, connection.ConnectionString); - - if (closeConnection) - { - connection.Close(); - if (persistSecurityInfo) - Assert.Equal(csb.ConnectionString, connection.ConnectionString); - else - Assert.Equal(connectionStringWithoutPassword, connection.ConnectionString); - } } } [Fact] public void State() { - using (var connection = new MySqlConnection(m_database.Connection.ConnectionString)) - { - Assert.Equal(ConnectionState.Closed, connection.State); - connection.Open(); - Assert.Equal(ConnectionState.Open, connection.State); - connection.Close(); - Assert.Equal(ConnectionState.Closed, connection.State); - } + using var connection = new MySqlConnection(m_database.Connection.ConnectionString); + Assert.Equal(ConnectionState.Closed, connection.State); + connection.Open(); + Assert.Equal(ConnectionState.Open, connection.State); + connection.Close(); + Assert.Equal(ConnectionState.Closed, connection.State); } [Fact] @@ -196,12 +180,10 @@ public void ConnectMultipleHostNames() var csb = AppConfig.CreateConnectionStringBuilder(); csb.Server = "invalid.example.net," + csb.Server; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - Assert.Equal(ConnectionState.Closed, connection.State); - connection.Open(); - Assert.Equal(ConnectionState.Open, connection.State); - } + using var connection = new MySqlConnection(csb.ConnectionString); + Assert.Equal(ConnectionState.Closed, connection.State); + connection.Open(); + Assert.Equal(ConnectionState.Open, connection.State); } [SkippableFact(ConfigSettings.PasswordlessUser)] @@ -212,12 +194,10 @@ public void ConnectNoPassword() csb.Password = ""; csb.Database = ""; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - Assert.Equal(ConnectionState.Closed, connection.State); - connection.Open(); - Assert.Equal(ConnectionState.Open, connection.State); - } + using var connection = new MySqlConnection(csb.ConnectionString); + Assert.Equal(ConnectionState.Closed, connection.State); + connection.Open(); + Assert.Equal(ConnectionState.Open, connection.State); } [SkippableFact(ConfigSettings.PasswordlessUser)] @@ -233,12 +213,10 @@ public void ConnectionPoolNoPassword() for (int i = 0; i < 3; i++) { - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - Assert.Equal(ConnectionState.Closed, connection.State); - connection.Open(); - Assert.Equal(ConnectionState.Open, connection.State); - } + using var connection = new MySqlConnection(csb.ConnectionString); + Assert.Equal(ConnectionState.Closed, connection.State); + connection.Open(); + Assert.Equal(ConnectionState.Open, connection.State); } } @@ -252,83 +230,71 @@ public void ConnectTimeout() ConnectionTimeout = 3, }; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - var stopwatch = Stopwatch.StartNew(); - Assert.Throws(() => connection.Open()); - stopwatch.Stop(); - TestUtilities.AssertDuration(stopwatch, 2900, 1500); - } + using var connection = new MySqlConnection(csb.ConnectionString); + var stopwatch = Stopwatch.StartNew(); + Assert.Throws(() => connection.Open()); + stopwatch.Stop(); + TestUtilities.AssertDuration(stopwatch, 2900, 1500); } [Fact] public void ConnectionDatabase() { var csb = AppConfig.CreateConnectionStringBuilder(); - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - Assert.Equal(csb.Database, connection.Database); + using var connection = new MySqlConnection(csb.ConnectionString); + Assert.Equal(csb.Database, connection.Database); - connection.Open(); + connection.Open(); - Assert.Equal(csb.Database, connection.Database); - Assert.Equal(csb.Database, QueryCurrentDatabase(connection)); - } + Assert.Equal(csb.Database, connection.Database); + Assert.Equal(csb.Database, QueryCurrentDatabase(connection)); } [SkippableFact(ConfigSettings.SecondaryDatabase)] public void ChangeDatabase() { var csb = AppConfig.CreateConnectionStringBuilder(); - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); - Assert.Equal(csb.Database, connection.Database); - Assert.Equal(csb.Database, QueryCurrentDatabase(connection)); + Assert.Equal(csb.Database, connection.Database); + Assert.Equal(csb.Database, QueryCurrentDatabase(connection)); - connection.ChangeDatabase(AppConfig.SecondaryDatabase); + connection.ChangeDatabase(AppConfig.SecondaryDatabase); - Assert.Equal(AppConfig.SecondaryDatabase, connection.Database); - Assert.Equal(AppConfig.SecondaryDatabase, QueryCurrentDatabase(connection)); - } + Assert.Equal(AppConfig.SecondaryDatabase, connection.Database); + Assert.Equal(AppConfig.SecondaryDatabase, QueryCurrentDatabase(connection)); } [SkippableFact(ConfigSettings.SecondaryDatabase)] public void ChangeDatabaseNotOpen() { var csb = AppConfig.CreateConnectionStringBuilder(); - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - Assert.Throws(() => connection.ChangeDatabase(AppConfig.SecondaryDatabase)); - } + using var connection = new MySqlConnection(csb.ConnectionString); + Assert.Throws(() => connection.ChangeDatabase(AppConfig.SecondaryDatabase)); } [SkippableFact(ConfigSettings.SecondaryDatabase)] public void ChangeDatabaseNull() { var csb = AppConfig.CreateConnectionStringBuilder(); - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - Assert.Throws(() => connection.ChangeDatabase(null)); - Assert.Throws(() => connection.ChangeDatabase("")); - } + using var connection = new MySqlConnection(csb.ConnectionString); + Assert.Throws(() => connection.ChangeDatabase(null)); + Assert.Throws(() => connection.ChangeDatabase("")); } [SkippableFact(ConfigSettings.SecondaryDatabase)] public void ChangeDatabaseInvalidName() { var csb = AppConfig.CreateConnectionStringBuilder(); - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); - Assert.Throws(() => connection.ChangeDatabase($"not_a_real_database_1234")); + Assert.Throws(() => connection.ChangeDatabase($"not_a_real_database_1234")); - Assert.Equal(ConnectionState.Open, connection.State); - Assert.Equal(csb.Database, connection.Database); - Assert.Equal(csb.Database, QueryCurrentDatabase(connection)); - } + Assert.Equal(ConnectionState.Open, connection.State); + Assert.Equal(csb.Database, connection.Database); + Assert.Equal(csb.Database, QueryCurrentDatabase(connection)); } [SkippableFact(ConfigSettings.SecondaryDatabase)] @@ -341,18 +307,16 @@ public void ChangeDatabaseConnectionPooling() for (int i = 0; i < csb.MaximumPoolSize * 2; i++) { - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); - Assert.Equal(csb.Database, connection.Database); - Assert.Equal(csb.Database, QueryCurrentDatabase(connection)); + Assert.Equal(csb.Database, connection.Database); + Assert.Equal(csb.Database, QueryCurrentDatabase(connection)); - connection.ChangeDatabase(AppConfig.SecondaryDatabase); + connection.ChangeDatabase(AppConfig.SecondaryDatabase); - Assert.Equal(AppConfig.SecondaryDatabase, connection.Database); - Assert.Equal(AppConfig.SecondaryDatabase, QueryCurrentDatabase(connection)); - } + Assert.Equal(AppConfig.SecondaryDatabase, connection.Database); + Assert.Equal(AppConfig.SecondaryDatabase, QueryCurrentDatabase(connection)); } } @@ -360,79 +324,71 @@ public void ChangeDatabaseConnectionPooling() public void UseDatabase() { var csb = AppConfig.CreateConnectionStringBuilder(); - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); - - Assert.Equal(csb.Database, connection.Database); - Assert.Equal(csb.Database, QueryCurrentDatabase(connection)); + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); - using (var cmd = connection.CreateCommand()) - { - cmd.CommandText = $"USE {AppConfig.SecondaryDatabase};"; - cmd.ExecuteNonQuery(); - } + Assert.Equal(csb.Database, connection.Database); + Assert.Equal(csb.Database, QueryCurrentDatabase(connection)); - Assert.Equal(AppConfig.SecondaryDatabase, connection.Database); - Assert.Equal(AppConfig.SecondaryDatabase, QueryCurrentDatabase(connection)); + using (var cmd = connection.CreateCommand()) + { + cmd.CommandText = $"USE {AppConfig.SecondaryDatabase};"; + cmd.ExecuteNonQuery(); } + + Assert.Equal(AppConfig.SecondaryDatabase, connection.Database); + Assert.Equal(AppConfig.SecondaryDatabase, QueryCurrentDatabase(connection)); } private static string QueryCurrentDatabase(MySqlConnection connection) { - using (var cmd = connection.CreateCommand()) - { - cmd.CommandText = "SELECT DATABASE()"; - return (string) cmd.ExecuteScalar(); - } + using var cmd = connection.CreateCommand(); + cmd.CommandText = "SELECT DATABASE()"; + return (string) cmd.ExecuteScalar(); } [SkippableFact(ConfigSettings.SecondaryDatabase)] public void ChangeConnectionStringWhenOpen() { var csb = AppConfig.CreateConnectionStringBuilder(); - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); - Assert.Equal(csb.Database, connection.Database); + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); + Assert.Equal(csb.Database, connection.Database); - csb.Database = AppConfig.SecondaryDatabase; + csb.Database = AppConfig.SecondaryDatabase; #if BASELINE - Assert.Throws(() => + Assert.Throws(() => #else - Assert.Throws(() => + Assert.Throws(() => #endif - { - connection.ConnectionString = csb.ConnectionString; - }); - } + { + connection.ConnectionString = csb.ConnectionString; + }); } [SkippableFact(ConfigSettings.SecondaryDatabase)] public void ChangeConnectionStringAfterClose() { var csb = AppConfig.CreateConnectionStringBuilder(); - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); - Assert.Equal(csb.Database, connection.Database); - connection.Close(); + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); + Assert.Equal(csb.Database, connection.Database); + connection.Close(); - csb.Database = AppConfig.SecondaryDatabase; - connection.ConnectionString = csb.ConnectionString; + csb.Database = AppConfig.SecondaryDatabase; + connection.ConnectionString = csb.ConnectionString; - connection.Open(); - Assert.Equal(csb.Database, connection.Database); - connection.Close(); - } + connection.Open(); + Assert.Equal(csb.Database, connection.Database); + connection.Close(); } [SkippableFact(ServerFeatures.Sha256Password, ConfigSettings.RequiresSsl)] public void Sha256WithSecureConnection() { var csb = AppConfig.CreateSha256ConnectionStringBuilder(); - using (var connection = new MySqlConnection(csb.ConnectionString)) - connection.Open(); + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); } [SkippableFact(ServerFeatures.Sha256Password)] @@ -441,41 +397,37 @@ public void Sha256WithoutSecureConnection() var csb = AppConfig.CreateSha256ConnectionStringBuilder(); csb.SslMode = MySqlSslMode.None; csb.AllowPublicKeyRetrieval = true; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { + using var connection = new MySqlConnection(csb.ConnectionString); #if NET45 - Assert.Throws(() => connection.Open()); + Assert.Throws(() => connection.Open()); #else - if (AppConfig.SupportedFeatures.HasFlag(ServerFeatures.RsaEncryption)) - connection.Open(); - else - Assert.Throws(() => connection.Open()); + if (AppConfig.SupportedFeatures.HasFlag(ServerFeatures.RsaEncryption)) + connection.Open(); + else + Assert.Throws(() => connection.Open()); #endif - } } [Fact] public void PingNoConnection() { - using (var connection = new MySqlConnection()) - Assert.False(connection.Ping()); + using var connection = new MySqlConnection(); + Assert.False(connection.Ping()); } [Fact] public void PingBeforeConnecting() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - Assert.False(connection.Ping()); + using var connection = new MySqlConnection(AppConfig.ConnectionString); + Assert.False(connection.Ping()); } [Fact] public void PingConnection() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - { - connection.Open(); - Assert.True(connection.Ping()); - } + using var connection = new MySqlConnection(AppConfig.ConnectionString); + connection.Open(); + Assert.True(connection.Ping()); } readonly DatabaseFixture m_database; diff --git a/tests/SideBySide/ConnectionPool.cs b/tests/SideBySide/ConnectionPool.cs index 95c1275a7..c6df95ab5 100644 --- a/tests/SideBySide/ConnectionPool.cs +++ b/tests/SideBySide/ConnectionPool.cs @@ -33,31 +33,25 @@ public void ResetConnection(object connectionReset, int poolSize, long expected) using (var connection = new MySqlConnection(csb.ConnectionString)) { connection.Open(); - using (var command = connection.CreateCommand()) - { - command.CommandText = "select @@autocommit;"; - Assert.Equal(1L, command.ExecuteScalar()); - } + using var command = connection.CreateCommand(); + command.CommandText = "select @@autocommit;"; + Assert.Equal(1L, command.ExecuteScalar()); } using (var connection = new MySqlConnection(csb.ConnectionString)) { connection.Open(); - using (var command = connection.CreateCommand()) - { - command.CommandText = "SET autocommit=0;"; - command.ExecuteNonQuery(); - } + using var command = connection.CreateCommand(); + command.CommandText = "SET autocommit=0;"; + command.ExecuteNonQuery(); } using (var connection = new MySqlConnection(csb.ConnectionString)) { connection.Open(); - using (var command = connection.CreateCommand()) - { - command.CommandText = "select @@autocommit;"; - Assert.Equal(expected, command.ExecuteScalar()); - } + using var command = connection.CreateCommand(); + command.CommandText = "select @@autocommit;"; + Assert.Equal(expected, command.ExecuteScalar()); } } @@ -198,21 +192,15 @@ public async Task CharacterSet() private async Task CheckCharacterSetAsync(string connectionString) { - using (var connection = new MySqlConnection(connectionString)) - { - await connection.OpenAsync().ConfigureAwait(false); - using (var cmd = connection.CreateCommand()) - { - cmd.CommandText = @"select @@character_set_client, @@character_set_connection"; - using (var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false)) - { - Assert.True(await reader.ReadAsync().ConfigureAwait(false)); - Assert.Equal("utf8mb4", reader.GetString(0)); - Assert.Equal("utf8mb4", reader.GetString(1)); - Assert.False(await reader.ReadAsync().ConfigureAwait(false)); - } - } - } + using var connection = new MySqlConnection(connectionString); + await connection.OpenAsync().ConfigureAwait(false); + using var cmd = connection.CreateCommand(); + cmd.CommandText = @"select @@character_set_client, @@character_set_connection"; + using var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false); + Assert.True(await reader.ReadAsync().ConfigureAwait(false)); + Assert.Equal("utf8mb4", reader.GetString(0)); + Assert.Equal("utf8mb4", reader.GetString(1)); + Assert.False(await reader.ReadAsync().ConfigureAwait(false)); } [Fact] @@ -299,14 +287,12 @@ public async Task ConnectionLifeTime(uint idleTimeout, uint delaySeconds, uint m async Task OpenConnections(uint numConnections, HashSet serverIdSet) { - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - await connection.OpenAsync(); - serverIdSet.Add(connection.ServerThread); - if (--numConnections <= 0) - return; - await OpenConnections(numConnections, serverIdSet); - } + using var connection = new MySqlConnection(csb.ConnectionString); + await connection.OpenAsync(); + serverIdSet.Add(connection.ServerThread); + if (--numConnections <= 0) + return; + await OpenConnections(numConnections, serverIdSet); } await OpenConnections(maxPoolSize, serverThreadIdsBegin); diff --git a/tests/SideBySide/ConnectionTests.cs b/tests/SideBySide/ConnectionTests.cs index 508e8b76e..08e5b6dc5 100644 --- a/tests/SideBySide/ConnectionTests.cs +++ b/tests/SideBySide/ConnectionTests.cs @@ -14,144 +14,122 @@ public ConnectionTests(DatabaseFixture database) [Fact] public void GotInfoMessageForNonExistentTable() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) + using var connection = new MySqlConnection(AppConfig.ConnectionString); + connection.Open(); + + var gotEvent = false; + connection.InfoMessage += (s, a) => { - connection.Open(); - - var gotEvent = false; - connection.InfoMessage += (s, a) => - { - gotEvent = true; - Assert.Single(a.errors); - Assert.Equal((int) MySqlErrorCode.BadTable, a.errors[0].Code); - }; - - connection.Execute(@"drop table if exists table_does_not_exist;"); - Assert.True(gotEvent); - } + gotEvent = true; + Assert.Single(a.errors); + Assert.Equal((int) MySqlErrorCode.BadTable, a.errors[0].Code); + }; + + connection.Execute(@"drop table if exists table_does_not_exist;"); + Assert.True(gotEvent); } [Fact] public void NoInfoMessageWhenNotLastStatementInBatch() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - { - connection.Open(); + using var connection = new MySqlConnection(AppConfig.ConnectionString); + connection.Open(); - var gotEvent = false; - connection.InfoMessage += (s, a) => - { - gotEvent = true; + var gotEvent = false; + connection.InfoMessage += (s, a) => + { + gotEvent = true; - // seeming bug in Connector/NET raises an event with no errors - Assert.Empty(a.errors); - }; + // seeming bug in Connector/NET raises an event with no errors + Assert.Empty(a.errors); + }; - connection.Execute(@"drop table if exists table_does_not_exist; select 1;"); + connection.Execute(@"drop table if exists table_does_not_exist; select 1;"); #if BASELINE - Assert.True(gotEvent); + Assert.True(gotEvent); #else - Assert.False(gotEvent); + Assert.False(gotEvent); #endif - } } [Fact] public void DefaultConnectionStringIsEmpty() { - using (var connection = new MySqlConnection()) - Assert.Equal("", connection.ConnectionString); + using var connection = new MySqlConnection(); + Assert.Equal("", connection.ConnectionString); } [Fact] public void InitializeWithNullConnectionString() { - using (var connection = new MySqlConnection(default(string))) - Assert.Equal("", connection.ConnectionString); + using var connection = new MySqlConnection(default(string)); + Assert.Equal("", connection.ConnectionString); } [Fact] public void SetConnectionStringToNull() { - using (var connection = new MySqlConnection()) - { - connection.ConnectionString = null; - Assert.Equal("", connection.ConnectionString); - } + using var connection = new MySqlConnection(); + connection.ConnectionString = null; + Assert.Equal("", connection.ConnectionString); } [Fact] public void SetConnectionStringToEmptyString() { - using (var connection = new MySqlConnection()) - { - connection.ConnectionString = ""; - Assert.Equal("", connection.ConnectionString); - } + using var connection = new MySqlConnection(); + connection.ConnectionString = ""; + Assert.Equal("", connection.ConnectionString); } [SkippableFact(Baseline = "Throws NullReferenceException")] public void ServerVersionThrows() { - using (var connection = new MySqlConnection()) - { - Assert.Throws(() => connection.ServerVersion); - } + using var connection = new MySqlConnection(); + Assert.Throws(() => connection.ServerVersion); } [SkippableFact(Baseline = "Throws NullReferenceException")] public void ServerThreadThrows() { - using (var connection = new MySqlConnection()) - { - Assert.Throws(() => connection.ServerThread); - } + using var connection = new MySqlConnection(); + Assert.Throws(() => connection.ServerThread); } [Fact] public void DatabaseIsEmptyString() { - using (var connection = new MySqlConnection()) - { - Assert.Equal("", connection.Database); - } + using var connection = new MySqlConnection(); + Assert.Equal("", connection.Database); } [Fact] public void DataSourceIsEmptyString() { - using (var connection = new MySqlConnection()) - { - Assert.Equal("", connection.DataSource); - } + using var connection = new MySqlConnection(); + Assert.Equal("", connection.DataSource); } [Fact] public void ConnectionTimeoutDefaultValue() { - using (var connection = new MySqlConnection()) - { - Assert.Equal(15, connection.ConnectionTimeout); - } + using var connection = new MySqlConnection(); + Assert.Equal(15, connection.ConnectionTimeout); } [Fact] public void ConnectionTimeoutDefaultValueAfterOpen() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - { - connection.Open(); - Assert.Equal(15, connection.ConnectionTimeout); - } + using var connection = new MySqlConnection(AppConfig.ConnectionString); + connection.Open(); + Assert.Equal(15, connection.ConnectionTimeout); } [Fact] public void ConnectionTimeoutExplicitValue() { - using (var connection = new MySqlConnection("Connection Timeout=30")) - { - Assert.Equal(30, connection.ConnectionTimeout); - } + using var connection = new MySqlConnection("Connection Timeout=30"); + Assert.Equal(30, connection.ConnectionTimeout); } [Fact] @@ -159,11 +137,9 @@ public void ConnectionTimeoutExplicitValueAfterOpen() { var csb = AppConfig.CreateConnectionStringBuilder(); csb.ConnectionTimeout = 30; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); - Assert.Equal(30, connection.ConnectionTimeout); - } + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); + Assert.Equal(30, connection.ConnectionTimeout); } } } diff --git a/tests/SideBySide/DataAdapterTests.cs b/tests/SideBySide/DataAdapterTests.cs index ef3c5d4f3..2015ec59a 100644 --- a/tests/SideBySide/DataAdapterTests.cs +++ b/tests/SideBySide/DataAdapterTests.cs @@ -40,102 +40,90 @@ public void Dispose() [Fact] public void UseDataAdapter() { - using (var command = new MySqlCommand("SELECT 1", m_connection)) - using (var da = new MySqlDataAdapter()) - using (var ds = new DataSet()) - { - da.SelectCommand = command; - da.Fill(ds); - Assert.Single(ds.Tables); - Assert.Single(ds.Tables[0].Rows); - Assert.Single(ds.Tables[0].Rows[0].ItemArray); - TestUtilities.AssertIsOne(ds.Tables[0].Rows[0][0]); - } + using var command = new MySqlCommand("SELECT 1", m_connection); + using var da = new MySqlDataAdapter(); + using var ds = new DataSet(); + da.SelectCommand = command; + da.Fill(ds); + Assert.Single(ds.Tables); + Assert.Single(ds.Tables[0].Rows); + Assert.Single(ds.Tables[0].Rows[0].ItemArray); + TestUtilities.AssertIsOne(ds.Tables[0].Rows[0][0]); } [Fact] public void UseDataAdapterMySqlConnectionConstructor() { - using (var command = new MySqlCommand("SELECT 1", m_connection)) - using (var da = new MySqlDataAdapter(command)) - using (var ds = new DataSet()) - { - da.Fill(ds); - TestUtilities.AssertIsOne(ds.Tables[0].Rows[0][0]); - } + using var command = new MySqlCommand("SELECT 1", m_connection); + using var da = new MySqlDataAdapter(command); + using var ds = new DataSet(); + da.Fill(ds); + TestUtilities.AssertIsOne(ds.Tables[0].Rows[0][0]); } [Fact] public void UseDataAdapterStringMySqlConnectionConstructor() { - using (var da = new MySqlDataAdapter("SELECT 1", m_connection)) - using (var ds = new DataSet()) - { - da.Fill(ds); - TestUtilities.AssertIsOne(ds.Tables[0].Rows[0][0]); - } + using var da = new MySqlDataAdapter("SELECT 1", m_connection); + using var ds = new DataSet(); + da.Fill(ds); + TestUtilities.AssertIsOne(ds.Tables[0].Rows[0][0]); } [Fact] public void UseDataAdapterStringStringConstructor() { - using (var da = new MySqlDataAdapter("SELECT 1", AppConfig.ConnectionString)) - using (var ds = new DataSet()) - { - da.Fill(ds); - TestUtilities.AssertIsOne(ds.Tables[0].Rows[0][0]); - } + using var da = new MySqlDataAdapter("SELECT 1", AppConfig.ConnectionString); + using var ds = new DataSet(); + da.Fill(ds); + TestUtilities.AssertIsOne(ds.Tables[0].Rows[0][0]); } [Fact] public void Fill() { - using (var da = new MySqlDataAdapter("select * from data_adapter", m_connection)) - using (var ds = new DataSet()) - { - da.Fill(ds, "data_adapter"); + using var da = new MySqlDataAdapter("select * from data_adapter", m_connection); + using var ds = new DataSet(); + da.Fill(ds, "data_adapter"); - Assert.Single(ds.Tables); - Assert.Equal(3, ds.Tables[0].Rows.Count); + Assert.Single(ds.Tables); + Assert.Equal(3, ds.Tables[0].Rows.Count); - Assert.Equal(1L, ds.Tables[0].Rows[0]["id"]); - Assert.Equal(2L, ds.Tables[0].Rows[1]["id"]); - Assert.Equal(3L, ds.Tables[0].Rows[2]["id"]); + Assert.Equal(1L, ds.Tables[0].Rows[0]["id"]); + Assert.Equal(2L, ds.Tables[0].Rows[1]["id"]); + Assert.Equal(3L, ds.Tables[0].Rows[2]["id"]); - Assert.Equal(DBNull.Value, ds.Tables[0].Rows[0]["int_value"]); - Assert.Equal(0, ds.Tables[0].Rows[1]["int_value"]); - Assert.Equal(1, ds.Tables[0].Rows[2]["int_value"]); + Assert.Equal(DBNull.Value, ds.Tables[0].Rows[0]["int_value"]); + Assert.Equal(0, ds.Tables[0].Rows[1]["int_value"]); + Assert.Equal(1, ds.Tables[0].Rows[2]["int_value"]); - Assert.Equal(DBNull.Value, ds.Tables[0].Rows[0]["text_value"]); - Assert.Equal("", ds.Tables[0].Rows[1]["text_value"]); - Assert.Equal("one", ds.Tables[0].Rows[2]["text_value"]); - } + Assert.Equal(DBNull.Value, ds.Tables[0].Rows[0]["text_value"]); + Assert.Equal("", ds.Tables[0].Rows[1]["text_value"]); + Assert.Equal("one", ds.Tables[0].Rows[2]["text_value"]); } [Fact] public void LoadDataTable() { - using (var command = new MySqlCommand("SELECT * FROM data_adapter", m_connection)) - using (var dr = command.ExecuteReader()) - { - var dt = new DataTable(); - dt.Load(dr); - dr.Close(); + using var command = new MySqlCommand("SELECT * FROM data_adapter", m_connection); + using var dr = command.ExecuteReader(); + var dt = new DataTable(); + dt.Load(dr); + dr.Close(); - Assert.Equal(3, dt.Rows.Count); + Assert.Equal(3, dt.Rows.Count); - Assert.Equal(1L, dt.Rows[0]["id"]); - Assert.Equal(2L, dt.Rows[1]["id"]); - Assert.Equal(3L, dt.Rows[2]["id"]); + Assert.Equal(1L, dt.Rows[0]["id"]); + Assert.Equal(2L, dt.Rows[1]["id"]); + Assert.Equal(3L, dt.Rows[2]["id"]); - Assert.Equal(DBNull.Value, dt.Rows[0]["int_value"]); - Assert.Equal(0, dt.Rows[1]["int_value"]); - Assert.Equal(1, dt.Rows[2]["int_value"]); + Assert.Equal(DBNull.Value, dt.Rows[0]["int_value"]); + Assert.Equal(0, dt.Rows[1]["int_value"]); + Assert.Equal(1, dt.Rows[2]["int_value"]); - Assert.Equal(DBNull.Value, dt.Rows[0]["text_value"]); - Assert.Equal("", dt.Rows[1]["text_value"]); - Assert.Equal("one", dt.Rows[2]["text_value"]); - } + Assert.Equal(DBNull.Value, dt.Rows[0]["text_value"]); + Assert.Equal("", dt.Rows[1]["text_value"]); + Assert.Equal("one", dt.Rows[2]["text_value"]); } [SkippableFact(Baseline = "Throws FormatException: Input string was not in a correct format")] @@ -163,32 +151,28 @@ public void InsertWithDataSet() dr["text_value"] = "four"; dt.Rows.Add(dr); - using (var ds2 = ds.GetChanges()) - { - da.Update(ds2); + using var ds2 = ds.GetChanges(); + da.Update(ds2); - ds.Merge(ds2); - ds.AcceptChanges(); - } + ds.Merge(ds2); + ds.AcceptChanges(); } - using (var cmd2 = new MySqlCommand("SELECT id, int_value, text_value FROM data_adapter", m_connection)) - using (var dr2 = cmd2.ExecuteReader()) - { - Assert.True(dr2.Read()); - Assert.Equal(1L, dr2[0]); + using var cmd2 = new MySqlCommand("SELECT id, int_value, text_value FROM data_adapter", m_connection); + using var dr2 = cmd2.ExecuteReader(); + Assert.True(dr2.Read()); + Assert.Equal(1L, dr2[0]); - Assert.True(dr2.Read()); - Assert.Equal(2L, dr2[0]); + Assert.True(dr2.Read()); + Assert.Equal(2L, dr2[0]); - Assert.True(dr2.Read()); - Assert.Equal(3L, dr2[0]); + Assert.True(dr2.Read()); + Assert.Equal(3L, dr2[0]); - Assert.True(dr2.Read()); - Assert.Equal(4L, dr2[0]); - Assert.Equal(4, dr2[1]); - Assert.Equal("four", dr2[2]); - } + Assert.True(dr2.Read()); + Assert.Equal(4L, dr2[0]); + Assert.Equal(4, dr2[1]); + Assert.Equal("four", dr2[2]); } [Fact] diff --git a/tests/SideBySide/DataTypes.cs b/tests/SideBySide/DataTypes.cs index 05da1188d..10f996b2a 100644 --- a/tests/SideBySide/DataTypes.cs +++ b/tests/SideBySide/DataTypes.cs @@ -153,36 +153,32 @@ public async Task GetUInt64(string column, int[] flags, ulong[] values) private async Task DoGetValue(string column, Func getInt, Func getIntByName, int[] flags, T[] values) { - using (var cmd = Connection.CreateCommand()) + using var cmd = Connection.CreateCommand(); + cmd.CommandText = $"select {column} from datatypes_integers order by rowid"; + cmd.Prepare(); + using var reader = (MySqlDataReader) await cmd.ExecuteReaderAsync().ConfigureAwait(false); + for (int i = 0; i < flags.Length; i++) { - cmd.CommandText = $"select {column} from datatypes_integers order by rowid"; - cmd.Prepare(); - using (var reader = (MySqlDataReader) await cmd.ExecuteReaderAsync().ConfigureAwait(false)) + Assert.True(await reader.ReadAsync().ConfigureAwait(false)); + switch (flags[i]) { - for (int i = 0; i < flags.Length; i++) - { - Assert.True(await reader.ReadAsync().ConfigureAwait(false)); - switch (flags[i]) - { - case 0: // normal - Assert.Equal(values[i], getInt(reader, 0)); - Assert.Equal(values[i], getIntByName(reader, column)); - break; - - case 1: // null - Assert.True(await reader.IsDBNullAsync(0).ConfigureAwait(false)); - break; - - case 2: // overflow - Assert.Throws(() => getInt(reader, 0)); - Assert.Throws(() => getIntByName(reader, column)); - break; - } - } - Assert.False(await reader.ReadAsync().ConfigureAwait(false)); - Assert.False(await reader.NextResultAsync().ConfigureAwait(false)); + case 0: // normal + Assert.Equal(values[i], getInt(reader, 0)); + Assert.Equal(values[i], getIntByName(reader, column)); + break; + + case 1: // null + Assert.True(await reader.IsDBNullAsync(0).ConfigureAwait(false)); + break; + + case 2: // overflow + Assert.Throws(() => getInt(reader, 0)); + Assert.Throws(() => getIntByName(reader, column)); + break; } } + Assert.False(await reader.ReadAsync().ConfigureAwait(false)); + Assert.False(await reader.NextResultAsync().ConfigureAwait(false)); } [Theory] @@ -227,11 +223,9 @@ public void QueryTinyIntSbyte(string column, string dataTypeName, object[] expec { var csb = CreateConnectionStringBuilder(); csb.TreatTinyAsBoolean = false; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); - DoQuery("bools", column, dataTypeName, expected, reader => reader.GetSByte(0), baselineCoercedNullValue: default(sbyte), connection: connection); - } + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); + DoQuery("bools", column, dataTypeName, expected, reader => reader.GetSByte(0), baselineCoercedNullValue: default(sbyte), connection: connection); } [Theory()] @@ -352,8 +346,8 @@ public void QueryString(string column, string[] expected) #if !BASELINE DoQuery("strings", column, "VARCHAR", expected, reader => reader.GetTextReader(0), matchesDefaultType: false, assertEqual: (e, a) => { - using (var actualReader = (TextReader) a) - Assert.Equal(e, actualReader.ReadToEnd()); + using var actualReader = (TextReader) a; + Assert.Equal(e, actualReader.ReadToEnd()); }, getFieldValueType: typeof(TextReader)); #endif } @@ -375,27 +369,23 @@ public void QueryGuid(string column, string dataTypeName, object[] expected) [InlineData("cp1251", new[] { null, "", "ASCII", "АБВГабвг", c_251ByteString })] public void QueryChar(string column, string[] expected) { - using (var cmd = Connection.CreateCommand()) + using var cmd = Connection.CreateCommand(); + cmd.CommandText = $@"select `{column}` from datatypes_strings order by rowid;"; + cmd.Prepare(); + using var reader = cmd.ExecuteReader(); + for (var i = 0; i < expected.Length; i++) { - cmd.CommandText = $@"select `{column}` from datatypes_strings order by rowid;"; - cmd.Prepare(); - using (var reader = cmd.ExecuteReader()) - { - for (var i = 0; i < expected.Length; i++) - { - Assert.True(reader.Read()); - if (expected[i] is null) - Assert.True(reader.IsDBNull(0)); - else if (expected[i].Length == 0) + Assert.True(reader.Read()); + if (expected[i] is null) + Assert.True(reader.IsDBNull(0)); + else if (expected[i].Length == 0) #if BASELINE - Assert.Throws(() => reader.GetChar(0)); + Assert.Throws(() => reader.GetChar(0)); #else - Assert.Throws(() => reader.GetChar(0)); + Assert.Throws(() => reader.GetChar(0)); #endif - else - Assert.Equal(expected[i][0], reader.GetChar(0)); - } - } + else + Assert.Equal(expected[i][0], reader.GetChar(0)); } } @@ -406,58 +396,54 @@ public void QueryBinaryGuid(bool oldGuids) { var csb = CreateConnectionStringBuilder(); csb.OldGuids = oldGuids; - using (var connection = new MySqlConnection(csb.ConnectionString)) + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); + using var cmd = connection.CreateCommand(); + cmd.CommandText = @"select guidbin from datatypes_blobs order by rowid;"; + cmd.Prepare(); + using (var reader = cmd.ExecuteReader()) { - connection.Open(); - using (var cmd = connection.CreateCommand()) + Assert.True(reader.Read()); + Assert.Equal(DBNull.Value, reader.GetValue(0)); + Assert.True(reader.Read()); + var expectedBytes = new byte[] { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF }; + var expectedGuid = new Guid(expectedBytes); + if (oldGuids) { - cmd.CommandText = @"select guidbin from datatypes_blobs order by rowid;"; - cmd.Prepare(); - using (var reader = cmd.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Equal(DBNull.Value, reader.GetValue(0)); - Assert.True(reader.Read()); - var expectedBytes = new byte[] { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF }; - var expectedGuid = new Guid(expectedBytes); - if (oldGuids) - { - Assert.Equal(typeof(Guid), reader.GetFieldType(0)); - Assert.Equal(expectedGuid, reader.GetValue(0)); - } - else - { - Assert.Equal(typeof(byte[]), reader.GetFieldType(0)); - Assert.Equal(expectedBytes, reader.GetValue(0)); - } - Assert.Equal(expectedGuid, reader.GetGuid(0)); - Assert.Equal(expectedBytes, GetBytes(reader)); + Assert.Equal(typeof(Guid), reader.GetFieldType(0)); + Assert.Equal(expectedGuid, reader.GetValue(0)); + } + else + { + Assert.Equal(typeof(byte[]), reader.GetFieldType(0)); + Assert.Equal(expectedBytes, reader.GetValue(0)); + } + Assert.Equal(expectedGuid, reader.GetGuid(0)); + Assert.Equal(expectedBytes, GetBytes(reader)); #if !BASELINE - Assert.Equal(expectedBytes, GetStreamBytes(reader)); + Assert.Equal(expectedBytes, GetStreamBytes(reader)); #endif - Assert.False(reader.Read()); - } + Assert.False(reader.Read()); + } - cmd.CommandText = @"select guidbin from datatypes_strings order by rowid;"; - using (var reader = cmd.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Equal(DBNull.Value, reader.GetValue(0)); - Assert.True(reader.Read()); - if (oldGuids) - { - Assert.Equal(typeof(string), reader.GetFieldType(0)); - Assert.Equal("00000000-0000-0000-0000-000000000000", reader.GetValue(0)); - Assert.Equal("00000000-0000-0000-0000-000000000000", reader.GetString("guidbin")); - } - else - { - Assert.Equal(typeof(Guid), reader.GetFieldType(0)); - Assert.Equal(Guid.Empty, reader.GetValue(0)); - } - Assert.Equal(Guid.Empty, reader.GetGuid("guidbin")); - } + cmd.CommandText = @"select guidbin from datatypes_strings order by rowid;"; + using (var reader = cmd.ExecuteReader()) + { + Assert.True(reader.Read()); + Assert.Equal(DBNull.Value, reader.GetValue(0)); + Assert.True(reader.Read()); + if (oldGuids) + { + Assert.Equal(typeof(string), reader.GetFieldType(0)); + Assert.Equal("00000000-0000-0000-0000-000000000000", reader.GetValue(0)); + Assert.Equal("00000000-0000-0000-0000-000000000000", reader.GetString("guidbin")); } + else + { + Assert.Equal(typeof(Guid), reader.GetFieldType(0)); + Assert.Equal(Guid.Empty, reader.GetValue(0)); + } + Assert.Equal(Guid.Empty, reader.GetGuid("guidbin")); } } @@ -468,13 +454,11 @@ public async Task QueryWithGuidParameter(bool oldGuids) { var csb = CreateConnectionStringBuilder(); csb.OldGuids = oldGuids; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - await connection.OpenAsync().ConfigureAwait(false); - Assert.Equal(oldGuids ? 0L : 1L, (await connection.QueryAsync(@"select count(*) from datatypes_strings where guid = @guid", new { guid = new Guid("fd24a0e8-c3f2-4821-a456-35da2dc4bb8f") }).ConfigureAwait(false)).SingleOrDefault()); - Assert.Equal(oldGuids ? 0L : 1L, (await connection.QueryAsync(@"select count(*) from datatypes_strings where guidbin = @guid", new { guid = new Guid("fd24a0e8-c3f2-4821-a456-35da2dc4bb8f") }).ConfigureAwait(false)).SingleOrDefault()); - Assert.Equal(oldGuids ? 1L : 0L, (await connection.QueryAsync(@"select count(*) from datatypes_blobs where guidbin = @guid", new { guid = new Guid(0x33221100, 0x5544, 0x7766, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF) }).ConfigureAwait(false)).SingleOrDefault()); - } + using var connection = new MySqlConnection(csb.ConnectionString); + await connection.OpenAsync().ConfigureAwait(false); + Assert.Equal(oldGuids ? 0L : 1L, (await connection.QueryAsync(@"select count(*) from datatypes_strings where guid = @guid", new { guid = new Guid("fd24a0e8-c3f2-4821-a456-35da2dc4bb8f") }).ConfigureAwait(false)).SingleOrDefault()); + Assert.Equal(oldGuids ? 0L : 1L, (await connection.QueryAsync(@"select count(*) from datatypes_strings where guidbin = @guid", new { guid = new Guid("fd24a0e8-c3f2-4821-a456-35da2dc4bb8f") }).ConfigureAwait(false)).SingleOrDefault()); + Assert.Equal(oldGuids ? 1L : 0L, (await connection.QueryAsync(@"select count(*) from datatypes_blobs where guidbin = @guid", new { guid = new Guid(0x33221100, 0x5544, 0x7766, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF) }).ConfigureAwait(false)).SingleOrDefault()); } [Theory] @@ -484,44 +468,40 @@ public async Task QueryWithGuidParameter(bool oldGuids) [InlineData("blob", typeof(byte[]))] public async Task GetGuid(string column, Type fieldType) { - using (var cmd = Connection.CreateCommand()) - { - cmd.CommandText = $"select `{column}` from datatypes_guids order by rowid"; - cmd.Prepare(); - using (var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false)) - { - Assert.Equal(fieldType, reader.GetFieldType(0)); - - Assert.True(await reader.ReadAsync().ConfigureAwait(false)); - Assert.True(reader.IsDBNull(0)); - Assert.Throws(() => reader.GetGuid(0)); - - Assert.True(await reader.ReadAsync().ConfigureAwait(false)); - Assert.False(reader.IsDBNull(0)); - Assert.NotNull(reader.GetValue(0)); - Assert.IsType(fieldType, reader.GetValue(0)); - - Type exceptionType = typeof(GetGuidWhenNullException); + using var cmd = Connection.CreateCommand(); + cmd.CommandText = $"select `{column}` from datatypes_guids order by rowid"; + cmd.Prepare(); + using var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false); + Assert.Equal(fieldType, reader.GetFieldType(0)); + + Assert.True(await reader.ReadAsync().ConfigureAwait(false)); + Assert.True(reader.IsDBNull(0)); + Assert.Throws(() => reader.GetGuid(0)); + + Assert.True(await reader.ReadAsync().ConfigureAwait(false)); + Assert.False(reader.IsDBNull(0)); + Assert.NotNull(reader.GetValue(0)); + Assert.IsType(fieldType, reader.GetValue(0)); + + Type exceptionType = typeof(GetGuidWhenNullException); #if BASELINE - // baseline throws FormatException when conversion from string fails - if (fieldType == typeof(string)) - exceptionType = typeof(FormatException); + // baseline throws FormatException when conversion from string fails + if (fieldType == typeof(string)) + exceptionType = typeof(FormatException); #endif - Assert.Throws(exceptionType, () => reader.GetGuid(0)); + Assert.Throws(exceptionType, () => reader.GetGuid(0)); - Assert.True(await reader.ReadAsync().ConfigureAwait(false)); - Assert.NotNull(reader.GetValue(0)); - Assert.IsType(fieldType, reader.GetValue(0)); - Assert.Equal(new Guid("33221100-5544-7766-8899-aabbccddeeff"), reader.GetGuid(0)); + Assert.True(await reader.ReadAsync().ConfigureAwait(false)); + Assert.NotNull(reader.GetValue(0)); + Assert.IsType(fieldType, reader.GetValue(0)); + Assert.Equal(new Guid("33221100-5544-7766-8899-aabbccddeeff"), reader.GetGuid(0)); - Assert.True(await reader.ReadAsync().ConfigureAwait(false)); - Assert.NotNull(reader.GetValue(0)); - Assert.IsType(fieldType, reader.GetValue(0)); - Assert.Equal(new Guid("33221100-5544-7766-8899-aabbccddeeff"), reader.GetGuid(0)); + Assert.True(await reader.ReadAsync().ConfigureAwait(false)); + Assert.NotNull(reader.GetValue(0)); + Assert.IsType(fieldType, reader.GetValue(0)); + Assert.Equal(new Guid("33221100-5544-7766-8899-aabbccddeeff"), reader.GetGuid(0)); - Assert.False(await reader.ReadAsync().ConfigureAwait(false)); - } - } + Assert.False(await reader.ReadAsync().ConfigureAwait(false)); } #if !BASELINE @@ -575,95 +555,90 @@ insert into guid_format(c36, c32, b16, tsb16, leb16, t, b) values( var csb = CreateConnectionStringBuilder(); csb.GuidFormat = guidFormat; csb.OldGuids = oldGuids; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); - using (var cmd = new MySqlCommand(sql, connection) - { - Parameters = - { - new MySqlParameter { Value = guidAsChar36 }, - new MySqlParameter { Value = guidAsChar32 }, - new MySqlParameter { Value = guidAsBinary16 }, - new MySqlParameter { Value = guidAsTimeSwapBinary16 }, - new MySqlParameter { Value = guidAsLittleEndianBinary16 }, - new MySqlParameter { Value = guidAsChar36 }, - new MySqlParameter { Value = isBinary16 ? guidAsBinary16 : isTimeSwapBinary16 ? guidAsTimeSwapBinary16 : guidAsLittleEndianBinary16 }, - new MySqlParameter { Value = isChar36 ? (object) guid : guidAsChar36 }, - new MySqlParameter { Value = isChar32 ? (object) guid : guidAsChar32 }, - new MySqlParameter { Value = isBinary16 ? (object) guid : guidAsBinary16 }, - new MySqlParameter { Value = isTimeSwapBinary16 ? (object) guid : guidAsTimeSwapBinary16 }, - new MySqlParameter { Value = isLittleEndianBinary16 ? (object) guid : guidAsLittleEndianBinary16 }, - new MySqlParameter { Value = guidAsChar32 }, - new MySqlParameter { Value = isBinary16 ? guidAsBinary16 : isTimeSwapBinary16 ? guidAsTimeSwapBinary16 : guidAsLittleEndianBinary16 }, - } - }) + using var cmd = new MySqlCommand(sql, connection) + { + Parameters = { - cmd.ExecuteNonQuery(); - cmd.CommandText = "select c36, c32, b16, tsb16, leb16, t, b from guid_format;"; - cmd.Prepare(); - using (var reader = cmd.ExecuteReader()) - { - for (int row = 0; row < 3; row++) - { - Assert.True(reader.Read()); - - object c36 = reader.GetValue(0); - if (isChar36) - Assert.Equal(guid, (Guid) c36); - else - Assert.Equal(guidAsChar36, (string) c36); - Assert.Equal(guid, reader.GetGuid(0)); - - object c32 = reader.GetValue(1); - if (isChar32) - Assert.Equal(guid, (Guid) c32); - else - Assert.Equal(guidAsChar32, (string) c32); - Assert.Equal(guid, reader.GetGuid(1)); - - object b16 = reader.GetValue(2); - if (isBinary16) - Assert.Equal(guid, (Guid) b16); - else if (isTimeSwapBinary16 || isLittleEndianBinary16) - Assert.NotEqual(guid, (Guid) b16); - else - Assert.Equal(guidAsBinary16, (byte[]) b16); - if (isBinary16) - Assert.Equal(guid, reader.GetGuid(2)); - - object tsb16 = reader.GetValue(3); - if (isTimeSwapBinary16) - Assert.Equal(guid, (Guid) tsb16); - else if (isBinary16 || isLittleEndianBinary16) - Assert.NotEqual(guid, (Guid) tsb16); - else - Assert.Equal(guidAsTimeSwapBinary16, (byte[]) tsb16); - if (isTimeSwapBinary16) - Assert.Equal(guid, reader.GetGuid(3)); - - object leb16 = reader.GetValue(4); - if (isLittleEndianBinary16) - Assert.Equal(guid, (Guid) leb16); - else if (isBinary16 || isTimeSwapBinary16) - Assert.NotEqual(guid, (Guid) leb16); - else - Assert.Equal(guidAsLittleEndianBinary16, (byte[]) leb16); - if (!isBinary16 && !isTimeSwapBinary16) - Assert.Equal(guid, reader.GetGuid(4)); - - Assert.IsType(reader.GetValue(5)); - Assert.Equal(guid, reader.GetGuid(5)); - - Assert.IsType(reader.GetValue(6)); - Assert.Equal(guid, reader.GetGuid(6)); - } - - Assert.False(reader.Read()); - } + new MySqlParameter { Value = guidAsChar36 }, + new MySqlParameter { Value = guidAsChar32 }, + new MySqlParameter { Value = guidAsBinary16 }, + new MySqlParameter { Value = guidAsTimeSwapBinary16 }, + new MySqlParameter { Value = guidAsLittleEndianBinary16 }, + new MySqlParameter { Value = guidAsChar36 }, + new MySqlParameter { Value = isBinary16 ? guidAsBinary16 : isTimeSwapBinary16 ? guidAsTimeSwapBinary16 : guidAsLittleEndianBinary16 }, + new MySqlParameter { Value = isChar36 ? (object) guid : guidAsChar36 }, + new MySqlParameter { Value = isChar32 ? (object) guid : guidAsChar32 }, + new MySqlParameter { Value = isBinary16 ? (object) guid : guidAsBinary16 }, + new MySqlParameter { Value = isTimeSwapBinary16 ? (object) guid : guidAsTimeSwapBinary16 }, + new MySqlParameter { Value = isLittleEndianBinary16 ? (object) guid : guidAsLittleEndianBinary16 }, + new MySqlParameter { Value = guidAsChar32 }, + new MySqlParameter { Value = isBinary16 ? guidAsBinary16 : isTimeSwapBinary16 ? guidAsTimeSwapBinary16 : guidAsLittleEndianBinary16 }, } + }; + cmd.ExecuteNonQuery(); + cmd.CommandText = "select c36, c32, b16, tsb16, leb16, t, b from guid_format;"; + cmd.Prepare(); + + using var reader = cmd.ExecuteReader(); + for (int row = 0; row < 3; row++) + { + Assert.True(reader.Read()); + + object c36 = reader.GetValue(0); + if (isChar36) + Assert.Equal(guid, (Guid) c36); + else + Assert.Equal(guidAsChar36, (string) c36); + Assert.Equal(guid, reader.GetGuid(0)); + + object c32 = reader.GetValue(1); + if (isChar32) + Assert.Equal(guid, (Guid) c32); + else + Assert.Equal(guidAsChar32, (string) c32); + Assert.Equal(guid, reader.GetGuid(1)); + + object b16 = reader.GetValue(2); + if (isBinary16) + Assert.Equal(guid, (Guid) b16); + else if (isTimeSwapBinary16 || isLittleEndianBinary16) + Assert.NotEqual(guid, (Guid) b16); + else + Assert.Equal(guidAsBinary16, (byte[]) b16); + if (isBinary16) + Assert.Equal(guid, reader.GetGuid(2)); + + object tsb16 = reader.GetValue(3); + if (isTimeSwapBinary16) + Assert.Equal(guid, (Guid) tsb16); + else if (isBinary16 || isLittleEndianBinary16) + Assert.NotEqual(guid, (Guid) tsb16); + else + Assert.Equal(guidAsTimeSwapBinary16, (byte[]) tsb16); + if (isTimeSwapBinary16) + Assert.Equal(guid, reader.GetGuid(3)); + + object leb16 = reader.GetValue(4); + if (isLittleEndianBinary16) + Assert.Equal(guid, (Guid) leb16); + else if (isBinary16 || isTimeSwapBinary16) + Assert.NotEqual(guid, (Guid) leb16); + else + Assert.Equal(guidAsLittleEndianBinary16, (byte[]) leb16); + if (!isBinary16 && !isTimeSwapBinary16) + Assert.Equal(guid, reader.GetGuid(4)); + + Assert.IsType(reader.GetValue(5)); + Assert.Equal(guid, reader.GetGuid(5)); + + Assert.IsType(reader.GetValue(6)); + Assert.Equal(guid, reader.GetGuid(6)); } + + Assert.False(reader.Read()); } #endif @@ -686,39 +661,35 @@ public void QueryZeroDateTime(bool convertZeroDateTime) { var csb = CreateConnectionStringBuilder(); csb.ConvertZeroDateTime = convertZeroDateTime; - using (var connection = new MySqlConnection(csb.ConnectionString)) + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); + + using var cmd = connection.CreateCommand(); + cmd.CommandText = @"select cast(0 as date), cast(0 as datetime);"; + cmd.Prepare(); + + using var reader = (MySqlDataReader) cmd.ExecuteReader(); + Assert.True(reader.Read()); + if (convertZeroDateTime) { - connection.Open(); - using (var cmd = connection.CreateCommand()) - { - cmd.CommandText = @"select cast(0 as date), cast(0 as datetime);"; - cmd.Prepare(); - using (var reader = cmd.ExecuteReader() as MySqlDataReader) - { - Assert.True(reader.Read()); - if (convertZeroDateTime) - { - Assert.Equal(DateTime.MinValue, reader.GetDateTime(0)); - Assert.Equal(DateTime.MinValue, reader.GetDateTime(1)); + Assert.Equal(DateTime.MinValue, reader.GetDateTime(0)); + Assert.Equal(DateTime.MinValue, reader.GetDateTime(1)); #if !BASELINE - Assert.Equal(DateTimeOffset.MinValue, reader.GetDateTimeOffset(0)); - Assert.Equal(DateTimeOffset.MinValue, reader.GetDateTimeOffset(1)); + Assert.Equal(DateTimeOffset.MinValue, reader.GetDateTimeOffset(0)); + Assert.Equal(DateTimeOffset.MinValue, reader.GetDateTimeOffset(1)); #endif - } - else - { + } + else + { #if BASELINE - Assert.Throws(() => reader.GetDateTime(0)); - Assert.Throws(() => reader.GetDateTime(1)); + Assert.Throws(() => reader.GetDateTime(0)); + Assert.Throws(() => reader.GetDateTime(1)); #else - Assert.Throws(() => reader.GetDateTime(0)); - Assert.Throws(() => reader.GetDateTime(1)); - Assert.Throws(() => reader.GetDateTimeOffset(0)); - Assert.Throws(() => reader.GetDateTimeOffset(1)); + Assert.Throws(() => reader.GetDateTime(0)); + Assert.Throws(() => reader.GetDateTime(1)); + Assert.Throws(() => reader.GetDateTimeOffset(0)); + Assert.Throws(() => reader.GetDateTimeOffset(1)); #endif - } - } - } } } @@ -737,12 +708,11 @@ public void QueryDateTimeKind(MySqlDateTimeKind kindOption, DateTimeKind kindIn, { var csb = CreateConnectionStringBuilder(); csb.DateTimeKind = kindOption; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); - var dateTimeIn = new DateTime(2001, 2, 3, 14, 5, 6, 789, kindIn); - using (var cmd = new MySqlCommand(@"drop table if exists date_time_kind; + var dateTimeIn = new DateTime(2001, 2, 3, 14, 5, 6, 789, kindIn); + using var cmd = new MySqlCommand(@"drop table if exists date_time_kind; create table date_time_kind( rowid integer not null primary key auto_increment, d date, @@ -754,46 +724,42 @@ dt4 datetime(4), dt5 datetime(5), dt6 datetime(6)); insert into date_time_kind(d, dt0, dt1, dt2, dt3, dt4, dt5, dt6) values(?, ?, ?, ?, ?, ?, ?, ?)", connection) + { + Parameters = { - Parameters = - { - new MySqlParameter { Value = dateTimeIn }, - new MySqlParameter { Value = dateTimeIn }, - new MySqlParameter { Value = dateTimeIn }, - new MySqlParameter { Value = dateTimeIn }, - new MySqlParameter { Value = dateTimeIn }, - new MySqlParameter { Value = dateTimeIn }, - new MySqlParameter { Value = dateTimeIn }, - new MySqlParameter { Value = dateTimeIn }, - } - }) - { - if (success) - { - cmd.ExecuteNonQuery(); - long lastInsertId = cmd.LastInsertedId; - cmd.CommandText = $"select d, dt0, dt1, dt2, dt3, dt4, dt5, dt6 from date_time_kind where rowid = {lastInsertId};"; - cmd.Prepare(); - using (var reader = cmd.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Equal(new DateTime(2001, 2, 3), reader.GetValue(0)); - Assert.Equal(new DateTime(2001, 2, 3, 14, 5, AppConfig.SupportedFeatures.HasFlag(ServerFeatures.RoundDateTime) ? 7 : 6, kindIn), reader.GetValue(1)); - Assert.Equal(new DateTime(2001, 2, 3, 14, 5, 6, AppConfig.SupportedFeatures.HasFlag(ServerFeatures.RoundDateTime) ? 800 : 700, kindIn), reader.GetValue(2)); - Assert.Equal(new DateTime(2001, 2, 3, 14, 5, 6, AppConfig.SupportedFeatures.HasFlag(ServerFeatures.RoundDateTime) ? 790 : 780, kindIn), reader.GetValue(3)); - Assert.Equal(dateTimeIn, reader.GetValue(4)); - Assert.Equal(dateTimeIn, reader.GetValue(5)); - Assert.Equal(dateTimeIn, reader.GetValue(6)); - Assert.Equal(dateTimeIn, reader.GetValue(7)); - for (int i = 0; i < 7; i++) - Assert.Equal(kindOption, (MySqlDateTimeKind) reader.GetDateTime(i).Kind); - } - } - else - { - Assert.Throws(() => cmd.ExecuteNonQuery()); - } + new MySqlParameter { Value = dateTimeIn }, + new MySqlParameter { Value = dateTimeIn }, + new MySqlParameter { Value = dateTimeIn }, + new MySqlParameter { Value = dateTimeIn }, + new MySqlParameter { Value = dateTimeIn }, + new MySqlParameter { Value = dateTimeIn }, + new MySqlParameter { Value = dateTimeIn }, + new MySqlParameter { Value = dateTimeIn }, } + }; + if (success) + { + cmd.ExecuteNonQuery(); + long lastInsertId = cmd.LastInsertedId; + cmd.CommandText = $"select d, dt0, dt1, dt2, dt3, dt4, dt5, dt6 from date_time_kind where rowid = {lastInsertId};"; + cmd.Prepare(); + + using var reader = cmd.ExecuteReader(); + Assert.True(reader.Read()); + Assert.Equal(new DateTime(2001, 2, 3), reader.GetValue(0)); + Assert.Equal(new DateTime(2001, 2, 3, 14, 5, AppConfig.SupportedFeatures.HasFlag(ServerFeatures.RoundDateTime) ? 7 : 6, kindIn), reader.GetValue(1)); + Assert.Equal(new DateTime(2001, 2, 3, 14, 5, 6, AppConfig.SupportedFeatures.HasFlag(ServerFeatures.RoundDateTime) ? 800 : 700, kindIn), reader.GetValue(2)); + Assert.Equal(new DateTime(2001, 2, 3, 14, 5, 6, AppConfig.SupportedFeatures.HasFlag(ServerFeatures.RoundDateTime) ? 790 : 780, kindIn), reader.GetValue(3)); + Assert.Equal(dateTimeIn, reader.GetValue(4)); + Assert.Equal(dateTimeIn, reader.GetValue(5)); + Assert.Equal(dateTimeIn, reader.GetValue(6)); + Assert.Equal(dateTimeIn, reader.GetValue(7)); + for (int i = 0; i < 7; i++) + Assert.Equal(kindOption, (MySqlDateTimeKind) reader.GetDateTime(i).Kind); + } + else + { + Assert.Throws(() => cmd.ExecuteNonQuery()); } } #endif @@ -834,14 +800,12 @@ public void QueryBlob(string column, int padLength) DoQuery("blobs", "`" + column + "`", "BLOB", new object[] { null, data }, GetStreamBytes); DoQuery("blobs", "`" + column + "`", "BLOB", new object[] { null, data }, reader => reader.GetStream(0), matchesDefaultType: false, assertEqual: (e, a) => { - using (var stream = (Stream) a) - { - Assert.True(stream.CanRead); - Assert.False(stream.CanWrite); - var bytes = new byte[stream.Length]; - Assert.Equal(bytes.Length, stream.Read(bytes, 0, bytes.Length)); - Assert.Equal(e, bytes); - } + using var stream = (Stream) a; + Assert.True(stream.CanRead); + Assert.False(stream.CanWrite); + var bytes = new byte[stream.Length]; + Assert.Equal(bytes.Length, stream.Read(bytes, 0, bytes.Length)); + Assert.Equal(e, bytes); }, getFieldValueType: typeof(Stream)); #endif } @@ -861,41 +825,39 @@ public async Task InsertLargeBlobAsync(string column, int size) #endif // NOTE: MySQL Server will reset the connection when it receives an oversize packet, so we need to create a test-specific connection here - using (var connection = new MySqlConnection(CreateConnectionStringBuilder().ConnectionString)) - { - await connection.OpenAsync(); + using var connection = new MySqlConnection(CreateConnectionStringBuilder().ConnectionString); + await connection.OpenAsync(); - var data = CreateByteArray(size); - var isSupported = size < 1048576 || AppConfig.SupportedFeatures.HasFlag(ServerFeatures.LargePackets); + var data = CreateByteArray(size); + var isSupported = size < 1048576 || AppConfig.SupportedFeatures.HasFlag(ServerFeatures.LargePackets); - long lastInsertId; - using (var cmd = new MySqlCommand($"insert into datatypes_blob_insert(`{column}`) values(@data)", connection)) + long lastInsertId; + using (var cmd = new MySqlCommand($"insert into datatypes_blob_insert(`{column}`) values(@data)", connection)) + { + try { - try - { - cmd.Parameters.AddWithValue("@data", data); - cmd.Prepare(); - await cmd.ExecuteNonQueryAsync().ConfigureAwait(false); - lastInsertId = cmd.LastInsertedId; - Assert.True(isSupported); - } - catch (MySqlException ex) - { - Console.WriteLine(ex.Message); - lastInsertId = -1; - Assert.False(isSupported); - Assert.True(ex.Message.IndexOf("packet") >= 0 || ex.Message.IndexOf("innodb_log_file_size") >= 0); - } + cmd.Parameters.AddWithValue("@data", data); + cmd.Prepare(); + await cmd.ExecuteNonQueryAsync().ConfigureAwait(false); + lastInsertId = cmd.LastInsertedId; + Assert.True(isSupported); } - - if (isSupported) + catch (MySqlException ex) { - var queryResult = (await connection.QueryAsync($"select `{column}` from datatypes_blob_insert where rowid = {lastInsertId}").ConfigureAwait(false)).Single(); - TestUtilities.AssertEqual(data, queryResult); - - await connection.ExecuteAsync($"delete from datatypes_blob_insert where rowid = {lastInsertId}").ConfigureAwait(false); + Console.WriteLine(ex.Message); + lastInsertId = -1; + Assert.False(isSupported); + Assert.True(ex.Message.IndexOf("packet") >= 0 || ex.Message.IndexOf("innodb_log_file_size") >= 0); } } + + if (isSupported) + { + var queryResult = (await connection.QueryAsync($"select `{column}` from datatypes_blob_insert where rowid = {lastInsertId}").ConfigureAwait(false)).Single(); + TestUtilities.AssertEqual(data, queryResult); + + await connection.ExecuteAsync($"delete from datatypes_blob_insert where rowid = {lastInsertId}").ConfigureAwait(false); + } } [Theory] @@ -912,41 +874,39 @@ public void InsertLargeBlobSync(string column, int size) #endif // NOTE: MySQL Server will reset the connection when it receives an oversize packet, so we need to create a test-specific connection here - using (var connection = new MySqlConnection(CreateConnectionStringBuilder().ConnectionString)) - { - connection.Open(); + using var connection = new MySqlConnection(CreateConnectionStringBuilder().ConnectionString); + connection.Open(); - var data = CreateByteArray(size); - var isSupported = size < 1048576 || AppConfig.SupportedFeatures.HasFlag(ServerFeatures.LargePackets); + var data = CreateByteArray(size); + var isSupported = size < 1048576 || AppConfig.SupportedFeatures.HasFlag(ServerFeatures.LargePackets); - long lastInsertId; - using (var cmd = new MySqlCommand($"insert into datatypes_blob_insert(`{column}`) values(@data)", connection)) + long lastInsertId; + using (var cmd = new MySqlCommand($"insert into datatypes_blob_insert(`{column}`) values(@data)", connection)) + { + try { - try - { - cmd.Parameters.AddWithValue("@data", data); - cmd.Prepare(); - cmd.ExecuteNonQuery(); - lastInsertId = cmd.LastInsertedId; - Assert.True(isSupported); - } - catch (MySqlException ex) - { - Console.WriteLine(ex.Message); - lastInsertId = -1; - Assert.False(isSupported); - Assert.True(ex.Message.IndexOf("packet") >= 0 || ex.Message.IndexOf("innodb_log_file_size") >= 0); - } + cmd.Parameters.AddWithValue("@data", data); + cmd.Prepare(); + cmd.ExecuteNonQuery(); + lastInsertId = cmd.LastInsertedId; + Assert.True(isSupported); } - - if (isSupported) + catch (MySqlException ex) { - var queryResult = connection.Query($"select `{column}` from datatypes_blob_insert where rowid = {lastInsertId}").Single(); - TestUtilities.AssertEqual(data, queryResult); - - connection.Execute($"delete from datatypes_blob_insert where rowid = {lastInsertId}"); + Console.WriteLine(ex.Message); + lastInsertId = -1; + Assert.False(isSupported); + Assert.True(ex.Message.IndexOf("packet") >= 0 || ex.Message.IndexOf("innodb_log_file_size") >= 0); } } + + if (isSupported) + { + var queryResult = connection.Query($"select `{column}` from datatypes_blob_insert where rowid = {lastInsertId}").Single(); + TestUtilities.AssertEqual(data, queryResult); + + connection.Execute($"delete from datatypes_blob_insert where rowid = {lastInsertId}"); + } } [Theory] @@ -962,30 +922,25 @@ public void AllowZeroDateTime(bool allowZeroDateTime, string columnName, Type ex { var csb = CreateConnectionStringBuilder(); csb.AllowZeroDateTime = allowZeroDateTime; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); - using (var cmd = new MySqlCommand($"SELECT `{columnName}` FROM datatypes_times WHERE `{columnName}` IS NOT NULL ORDER BY rowid", connection)) - { - cmd.Prepare(); - using (var reader = cmd.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Equal(expectedType, reader.GetFieldType(0)); - Assert.IsType(expectedType, reader.GetValue(0)); + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); + + using var cmd = new MySqlCommand($"SELECT `{columnName}` FROM datatypes_times WHERE `{columnName}` IS NOT NULL ORDER BY rowid", connection); + cmd.Prepare(); + using var reader = cmd.ExecuteReader(); + Assert.True(reader.Read()); + Assert.Equal(expectedType, reader.GetFieldType(0)); + Assert.IsType(expectedType, reader.GetValue(0)); #if !NETCOREAPP1_1_2 - var dt = reader.GetSchemaTable(); - Assert.Equal(expectedType, dt.Rows[0]["DataType"]); + var dt = reader.GetSchemaTable(); + Assert.Equal(expectedType, dt.Rows[0]["DataType"]); #endif - if (expectedDateTime is object) - { - var expected = (DateTime) ConvertToDateTime(new object[] { expectedDateTime }, DateTimeKind.Unspecified)[0]; - Assert.Equal(expected, reader.GetDateTime(0)); - Assert.Equal(new MySqlDateTime(expected), reader.GetMySqlDateTime(0)); - } - } - } + if (expectedDateTime is object) + { + var expected = (DateTime) ConvertToDateTime(new object[] { expectedDateTime }, DateTimeKind.Unspecified)[0]; + Assert.Equal(expected, reader.GetDateTime(0)); + Assert.Equal(new MySqlDateTime(expected), reader.GetMySqlDateTime(0)); } } @@ -995,19 +950,15 @@ public void AllowZeroDateTime(bool allowZeroDateTime, string columnName, Type ex [InlineData("Timestamp")] public void GetMySqlDateTime(string columnName) { - using (var cmd = new MySqlCommand($"SELECT `{columnName}` FROM datatypes_times WHERE `{columnName}` IS NOT NULL", Connection)) + using var cmd = new MySqlCommand($"SELECT `{columnName}` FROM datatypes_times WHERE `{columnName}` IS NOT NULL", Connection); + cmd.Prepare(); + using var reader = cmd.ExecuteReader(); + while (reader.Read()) { - cmd.Prepare(); - using (var reader = cmd.ExecuteReader()) - { - while (reader.Read()) - { - var dt = reader.GetDateTime(0); - var msdt = reader.GetMySqlDateTime(0); - Assert.True(msdt.IsValidDateTime); - Assert.Equal(dt, msdt.GetDateTime()); - } - } + var dt = reader.GetDateTime(0); + var msdt = reader.GetMySqlDateTime(0); + Assert.True(msdt.IsValidDateTime); + Assert.Equal(dt, msdt.GetDateTime()); } } @@ -1141,99 +1092,89 @@ private void DoGetSchemaTable(string column, string table, MySqlDbType mySqlDbTy var isLong = flags.IndexOf('L') != -1; var allowDbNull = flags.IndexOf('N') != -1; - using (var command = Connection.CreateCommand()) - { - command.CommandText = $"select `{column}` from `{table}`;"; - command.Prepare(); + using var command = Connection.CreateCommand(); + command.CommandText = $"select `{column}` from `{table}`;"; + command.Prepare(); - using (var reader = command.ExecuteReader()) - { - var schemaTable = reader.GetSchemaTable(); - Assert.Single(schemaTable.Rows); - var schema = schemaTable.Rows[0]; - Assert.Equal(column, schema["ColumnName"]); + using var reader = command.ExecuteReader(); + var schemaTable = reader.GetSchemaTable(); + Assert.Single(schemaTable.Rows); + var schema = schemaTable.Rows[0]; + Assert.Equal(column, schema["ColumnName"]); #if BASELINE - int ordinal = 1; // https://bugs.mysql.com/bug.php?id=61477 + int ordinal = 1; // https://bugs.mysql.com/bug.php?id=61477 #else - int ordinal = 0; + int ordinal = 0; #endif - Assert.Equal(ordinal, schema["ColumnOrdinal"]); - Assert.Equal(dataType, schema["DataType"]); + Assert.Equal(ordinal, schema["ColumnOrdinal"]); + Assert.Equal(dataType, schema["DataType"]); #if BASELINE - // https://bugs.mysql.com/bug.php?id=87876 - if (columnSize != int.MaxValue) - Assert.Equal(columnSize, schema["ColumnSize"]); + // https://bugs.mysql.com/bug.php?id=87876 + if (columnSize != int.MaxValue) + Assert.Equal(columnSize, schema["ColumnSize"]); #else - Assert.Equal(columnSize, schema["ColumnSize"]); + Assert.Equal(columnSize, schema["ColumnSize"]); #endif - Assert.Equal(isLong, schema["IsLong"]); - Assert.Equal(isAutoIncrement, schema["IsAutoIncrement"]); - Assert.Equal(isKey, schema["IsKey"]); - Assert.Equal(allowDbNull, schema["AllowDBNull"]); - Assert.Equal(precision, schema["NumericPrecision"]); - Assert.Equal(scale, schema["NumericScale"]); + Assert.Equal(isLong, schema["IsLong"]); + Assert.Equal(isAutoIncrement, schema["IsAutoIncrement"]); + Assert.Equal(isKey, schema["IsKey"]); + Assert.Equal(allowDbNull, schema["AllowDBNull"]); + Assert.Equal(precision, schema["NumericPrecision"]); + Assert.Equal(scale, schema["NumericScale"]); #if BASELINE - if (mySqlDbType == MySqlDbType.Enum || mySqlDbType == MySqlDbType.Set) - mySqlDbType = MySqlDbType.String; + if (mySqlDbType == MySqlDbType.Enum || mySqlDbType == MySqlDbType.Set) + mySqlDbType = MySqlDbType.String; #endif - Assert.Equal(mySqlDbType, (MySqlDbType) schema["ProviderType"]); - Assert.Equal(Connection.Database, schema["BaseSchemaName"]); - Assert.Equal(table, schema["BaseTableName"]); - Assert.Equal(column, schema["BaseColumnName"]); - Assert.False((bool) schema["IsUnique"]); - Assert.False((bool) schema["IsRowVersion"]); - Assert.False((bool) schema["IsReadOnly"]); - } - } + Assert.Equal(mySqlDbType, (MySqlDbType) schema["ProviderType"]); + Assert.Equal(Connection.Database, schema["BaseSchemaName"]); + Assert.Equal(table, schema["BaseTableName"]); + Assert.Equal(column, schema["BaseColumnName"]); + Assert.False((bool) schema["IsUnique"]); + Assert.False((bool) schema["IsRowVersion"]); + Assert.False((bool) schema["IsReadOnly"]); } [Fact] public void GetSchemaTableTwice() { - using (var command = Connection.CreateCommand()) - { - command.CommandText = "select Int16 from datatypes_integers; select Int32 from datatypes_integers;"; - using (var reader = command.ExecuteReader()) - { - var table = reader.GetSchemaTable(); - Assert.Equal("Int16", table.Rows[0]["ColumnName"]); + using var command = Connection.CreateCommand(); + command.CommandText = "select Int16 from datatypes_integers; select Int32 from datatypes_integers;"; - while (reader.Read()) - { - } - - Assert.True(reader.NextResult()); + using var reader = command.ExecuteReader(); + var table = reader.GetSchemaTable(); + Assert.Equal("Int16", table.Rows[0]["ColumnName"]); - table = reader.GetSchemaTable(); - Assert.Equal("Int32", table.Rows[0]["ColumnName"]); - } + while (reader.Read()) + { } + + Assert.True(reader.NextResult()); + + table = reader.GetSchemaTable(); + Assert.Equal("Int32", table.Rows[0]["ColumnName"]); } [Fact] public void GetSchemaTableAfterNextResult() { - using (var command = Connection.CreateCommand()) - { - command.CommandText = "select Int16 from datatypes_integers;"; - using (var reader = command.ExecuteReader()) - { - var table = reader.GetSchemaTable(); - Assert.NotNull(table); - Assert.Equal("Int16", table.Rows[0]["ColumnName"]); + using var command = Connection.CreateCommand(); + command.CommandText = "select Int16 from datatypes_integers;"; - while (reader.Read()) - { - } + using var reader = command.ExecuteReader(); + var table = reader.GetSchemaTable(); + Assert.NotNull(table); + Assert.Equal("Int16", table.Rows[0]["ColumnName"]); + + while (reader.Read()) + { + } - Assert.False(reader.NextResult()); + Assert.False(reader.NextResult()); #if BASELINE - Assert.Null(reader.GetSchemaTable()); + Assert.Null(reader.GetSchemaTable()); #else - Assert.Throws(() => reader.GetSchemaTable()); + Assert.Throws(() => reader.GetSchemaTable()); #endif - } - } } #endif @@ -1300,37 +1241,34 @@ public void GetColumnSchema(string column, string table, MySqlDbType mySqlDbType var allowDbNull = flags.IndexOf('N') != -1; var realPrecision = precision == -1 ? default(int?) : precision; - using (var command = Connection.CreateCommand()) - { - command.CommandText = $"select `{column}` from `{table}`;"; - command.Prepare(); - using (var reader = command.ExecuteReader()) - { - var columns = reader.GetColumnSchema(); - Assert.Single(columns); - var schema = (MySqlDbColumn) columns[0]; - Assert.Equal(allowDbNull, schema.AllowDBNull); - Assert.Equal(column, schema.BaseColumnName); - Assert.Equal(Connection.Database, schema.BaseSchemaName); - Assert.Equal(table, schema.BaseTableName); - Assert.Equal(column, schema.ColumnName); - Assert.Equal(0, schema.ColumnOrdinal); - Assert.Equal(dataType, schema.DataType); - Assert.Equal(dataTypeName, schema.DataTypeName); - Assert.Equal(columnSize, schema.ColumnSize); - Assert.False(schema.IsAliased.Value); - Assert.Equal(isAutoIncrement, schema.IsAutoIncrement); - Assert.False(schema.IsExpression.Value); - Assert.False(schema.IsHidden.Value); - Assert.Equal(isKey, schema.IsKey); - Assert.Equal(isLong, schema.IsLong); - Assert.False(schema.IsReadOnly.Value); - Assert.False(schema.IsUnique.Value); - Assert.Equal(realPrecision, schema.NumericPrecision); - Assert.Equal(scale, schema.NumericScale); - Assert.Equal(mySqlDbType, schema.ProviderType); - } - } + using var command = Connection.CreateCommand(); + command.CommandText = $"select `{column}` from `{table}`;"; + command.Prepare(); + + using var reader = command.ExecuteReader(); + var columns = reader.GetColumnSchema(); + Assert.Single(columns); + var schema = (MySqlDbColumn) columns[0]; + Assert.Equal(allowDbNull, schema.AllowDBNull); + Assert.Equal(column, schema.BaseColumnName); + Assert.Equal(Connection.Database, schema.BaseSchemaName); + Assert.Equal(table, schema.BaseTableName); + Assert.Equal(column, schema.ColumnName); + Assert.Equal(0, schema.ColumnOrdinal); + Assert.Equal(dataType, schema.DataType); + Assert.Equal(dataTypeName, schema.DataTypeName); + Assert.Equal(columnSize, schema.ColumnSize); + Assert.False(schema.IsAliased.Value); + Assert.Equal(isAutoIncrement, schema.IsAutoIncrement); + Assert.False(schema.IsExpression.Value); + Assert.False(schema.IsHidden.Value); + Assert.Equal(isKey, schema.IsKey); + Assert.Equal(isLong, schema.IsLong); + Assert.False(schema.IsReadOnly.Value); + Assert.False(schema.IsUnique.Value); + Assert.Equal(realPrecision, schema.NumericPrecision); + Assert.Equal(scale, schema.NumericScale); + Assert.Equal(mySqlDbType, schema.ProviderType); } #endif @@ -1463,14 +1401,12 @@ private static byte[] GetBytes(DbDataReader reader) private static byte[] GetStreamBytes(DbDataReader reader) { - using (var stream = reader.GetStream(0)) - { - Assert.True(stream.CanRead); - Assert.False(stream.CanWrite); - var bytes = new byte[stream.Length]; - Assert.Equal(bytes.Length, stream.Read(bytes, 0, bytes.Length)); - return bytes; - } + using var stream = reader.GetStream(0); + Assert.True(stream.CanRead); + Assert.False(stream.CanWrite); + var bytes = new byte[stream.Length]; + Assert.Equal(bytes.Length, stream.Read(bytes, 0, bytes.Length)); + return bytes; } private void DoQuery( @@ -1509,78 +1445,76 @@ private void DoQuery( { connection = connection ?? Connection; assertEqual = assertEqual ?? Assert.Equal; - using (var cmd = connection.CreateCommand()) + using var cmd = connection.CreateCommand(); + cmd.CommandText = $"select {column} from datatypes_{table} order by rowid"; + cmd.Prepare(); + using (var reader = cmd.ExecuteReader()) { - cmd.CommandText = $"select {column} from datatypes_{table} order by rowid"; - cmd.Prepare(); - using (var reader = cmd.ExecuteReader()) + Assert.Equal(dataTypeName, reader.GetDataTypeName(0)); + foreach (var value in expected) { - Assert.Equal(dataTypeName, reader.GetDataTypeName(0)); - foreach (var value in expected) + Assert.True(reader.Read()); + if (value is null) { - Assert.True(reader.Read()); - if (value is null) - { - Assert.Equal(DBNull.Value, reader.GetValue(0)); + Assert.Equal(DBNull.Value, reader.GetValue(0)); #if BASELINE - if (baselineCoercedNullValue is object) - Assert.Equal(baselineCoercedNullValue, getValue(reader)); - else - Assert.Throws(() => getValue(reader)); -#else + if (baselineCoercedNullValue is object) + Assert.Equal(baselineCoercedNullValue, getValue(reader)); + else Assert.Throws(() => getValue(reader)); +#else + Assert.Throws(() => getValue(reader)); #endif + } + else + { + assertEqual(value, getValue(reader)); + + // test `reader.GetValue` and `reader.GetFieldType` if value matches default type + if (matchesDefaultType) + { + assertEqual(value, reader.GetValue(0)); + Assert.Equal(value.GetType(), reader.GetFieldType(0)); + Assert.Equal(value.GetType(), reader.GetFieldType(column.Replace("`", ""))); } - else + + if (!omitGetFieldValueTest) { - assertEqual(value, getValue(reader)); - - // test `reader.GetValue` and `reader.GetFieldType` if value matches default type - if (matchesDefaultType) - { - assertEqual(value, reader.GetValue(0)); - Assert.Equal(value.GetType(), reader.GetFieldType(0)); - Assert.Equal(value.GetType(), reader.GetFieldType(column.Replace("`", ""))); - } - - if (!omitGetFieldValueTest) - { - // test `reader.GetFieldValue` - var syncMethod = typeof(MySqlDataReader) - .GetMethod("GetFieldValue") - .MakeGenericMethod(getFieldValueType ?? value.GetType()); - assertEqual(value, syncMethod.Invoke(reader, new object[] { 0 })); - - // test `reader.GetFieldValueAsync` - var asyncMethod = typeof(MySqlDataReader) - .GetMethod("GetFieldValueAsync", new[] { typeof(int) }) - .MakeGenericMethod(getFieldValueType ?? value.GetType()); - var asyncMethodValue = asyncMethod.Invoke(reader, new object[] { 0 }); - var asyncMethodGetAwaiter = asyncMethodValue.GetType() - .GetMethod("GetAwaiter"); - var asyncMethodGetAwaiterValue = asyncMethodGetAwaiter.Invoke(asyncMethodValue, new object[] { }); - var asyncMethodGetResult = asyncMethodGetAwaiterValue.GetType() - .GetMethod("GetResult"); - var asyncMethodGetResultValue = asyncMethodGetResult.Invoke(asyncMethodGetAwaiterValue, new object[] { }); - assertEqual(value, asyncMethodGetResultValue); - } + // test `reader.GetFieldValue` + var syncMethod = typeof(MySqlDataReader) + .GetMethod("GetFieldValue") + .MakeGenericMethod(getFieldValueType ?? value.GetType()); + assertEqual(value, syncMethod.Invoke(reader, new object[] { 0 })); + + // test `reader.GetFieldValueAsync` + var asyncMethod = typeof(MySqlDataReader) + .GetMethod("GetFieldValueAsync", new[] { typeof(int) }) + .MakeGenericMethod(getFieldValueType ?? value.GetType()); + var asyncMethodValue = asyncMethod.Invoke(reader, new object[] { 0 }); + var asyncMethodGetAwaiter = asyncMethodValue.GetType() + .GetMethod("GetAwaiter"); + var asyncMethodGetAwaiterValue = asyncMethodGetAwaiter.Invoke(asyncMethodValue, new object[] { }); + var asyncMethodGetResult = asyncMethodGetAwaiterValue.GetType() + .GetMethod("GetResult"); + var asyncMethodGetResultValue = asyncMethodGetResult.Invoke(asyncMethodGetAwaiterValue, new object[] { }); + assertEqual(value, asyncMethodGetResultValue); } } - Assert.False(reader.Read()); - Assert.False(reader.NextResult()); } + Assert.False(reader.Read()); + Assert.False(reader.NextResult()); + } - if (!omitWhereTest) - { - cmd.CommandText = $"select rowid from datatypes_{table} where {column} = @value"; - var p = cmd.CreateParameter(); - p.ParameterName = "@value"; - p.Value = expected.Last(); - cmd.Parameters.Add(p); - cmd.Prepare(); - var result = cmd.ExecuteScalar(); - Assert.Equal(Array.IndexOf(expected, p.Value) + 1, result); - } + if (!omitWhereTest) + { + cmd.CommandText = $"select rowid from datatypes_{table} where {column} = @value"; + var p = cmd.CreateParameter(); + p.ParameterName = "@value"; + p.Value = expected.Last(); + cmd.Parameters.Add(p); + cmd.Prepare(); + var result = cmd.ExecuteScalar(); + Assert.Equal(Array.IndexOf(expected, p.Value) + 1, result); } } diff --git a/tests/SideBySide/InsertTests.cs b/tests/SideBySide/InsertTests.cs index a40e2e359..b658c0aa9 100644 --- a/tests/SideBySide/InsertTests.cs +++ b/tests/SideBySide/InsertTests.cs @@ -25,12 +25,10 @@ public async Task LastInsertedId() try { await m_database.Connection.OpenAsync(); - using (var command = new MySqlCommand("INSERT INTO insert_ai (text) VALUES (@text);", m_database.Connection)) - { - command.Parameters.Add(new MySqlParameter { ParameterName = "@text", Value = "test" }); - await command.ExecuteNonQueryAsync(); - Assert.Equal(1L, command.LastInsertedId); - } + using var command = new MySqlCommand("INSERT INTO insert_ai (text) VALUES (@text);", m_database.Connection); + command.Parameters.Add(new MySqlParameter { ParameterName = "@text", Value = "test" }); + await command.ExecuteNonQueryAsync(); + Assert.Equal(1L, command.LastInsertedId); } finally { @@ -46,12 +44,10 @@ public async Task LastInsertedIdNegative() try { await m_database.Connection.OpenAsync(); - using (var command = new MySqlCommand("INSERT INTO insert_ai(rowid) VALUES (@rowid);", m_database.Connection)) - { - command.Parameters.AddWithValue("@rowid", -1); - await command.ExecuteNonQueryAsync(); - Assert.Equal(-1L, command.LastInsertedId); - } + using var command = new MySqlCommand("INSERT INTO insert_ai(rowid) VALUES (@rowid);", m_database.Connection); + command.Parameters.AddWithValue("@rowid", -1); + await command.ExecuteNonQueryAsync(); + Assert.Equal(-1L, command.LastInsertedId); } finally { @@ -67,12 +63,10 @@ public async Task LastInsertedIdUlong() try { await m_database.Connection.OpenAsync(); - using (var command = new MySqlCommand("INSERT INTO insert_ai(rowid) VALUES (@rowid);", m_database.Connection)) - { - command.Parameters.AddWithValue("@rowid", ((ulong) long.MaxValue) + 1); - await command.ExecuteNonQueryAsync(); - Assert.Equal(long.MinValue, command.LastInsertedId); - } + using var command = new MySqlCommand("INSERT INTO insert_ai(rowid) VALUES (@rowid);", m_database.Connection); + command.Parameters.AddWithValue("@rowid", ((ulong) long.MaxValue) + 1); + await command.ExecuteNonQueryAsync(); + Assert.Equal(long.MinValue, command.LastInsertedId); } finally { @@ -89,13 +83,11 @@ public async Task RowsAffected() try { await m_database.Connection.OpenAsync(); - using (var command = new MySqlCommand(@" + using var command = new MySqlCommand(@" INSERT INTO insert_rows_affected (value) VALUES (null); -INSERT INTO insert_rows_affected (value) VALUES (null);", m_database.Connection)) - { - var rowsAffected = await command.ExecuteNonQueryAsync(); - Assert.Equal(2, rowsAffected); - } +INSERT INTO insert_rows_affected (value) VALUES (null);", m_database.Connection); + var rowsAffected = await command.ExecuteNonQueryAsync(); + Assert.Equal(2, rowsAffected); } finally { @@ -111,11 +103,9 @@ public void LastInsertedIdExplicitStart() try { m_database.Connection.Open(); - using (var command = new MySqlCommand("insert into insert_ai_2(text) values('test');", m_database.Connection)) - { - command.ExecuteNonQuery(); - Assert.Equal(1234L, command.LastInsertedId); - } + using var command = new MySqlCommand("insert into insert_ai_2(text) values('test');", m_database.Connection); + command.ExecuteNonQuery(); + Assert.Equal(1234L, command.LastInsertedId); } finally { @@ -177,17 +167,15 @@ public void InsertDateTimeOffset() m_database.Connection.Open(); try { - using (var cmd = m_database.Connection.CreateCommand()) + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = @"insert into insert_datetimeoffset(datetimeoffset1) values(@datetimeoffset1);"; + cmd.Parameters.Add(new MySqlParameter { - cmd.CommandText = @"insert into insert_datetimeoffset(datetimeoffset1) values(@datetimeoffset1);"; - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@datetimeoffset1", - DbType = DbType.DateTimeOffset, - Value = value.datetimeoffset1 - }); - cmd.ExecuteNonQuery(); - } + ParameterName = "@datetimeoffset1", + DbType = DbType.DateTimeOffset, + Value = value.datetimeoffset1 + }); + cmd.ExecuteNonQuery(); } finally { @@ -211,12 +199,10 @@ public void InsertMySqlDateTime() m_database.Connection.Open(); try { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = @"insert into insert_mysqldatetime(ts) values(@ts);"; - cmd.Parameters.AddWithValue("@ts", new MySqlDateTime(2018, 6, 9, 12, 34, 56, 123456)); - cmd.ExecuteNonQuery(); - } + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = @"insert into insert_mysqldatetime(ts) values(@ts);"; + cmd.Parameters.AddWithValue("@ts", new MySqlDateTime(2018, 6, 9, 12, 34, 56, 123456)); + cmd.ExecuteNonQuery(); } finally { @@ -232,30 +218,28 @@ public void InsertOldGuid() { var csb = AppConfig.CreateConnectionStringBuilder(); csb.OldGuids = true; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); - connection.Execute(@"drop table if exists old_guids; + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); + connection.Execute(@"drop table if exists old_guids; create table old_guids(id integer not null primary key auto_increment, guid binary(16) null);"); - var guid = new Guid(1, 2, 3, 0x27, 0x5C, 0x7B, 0x7D, 0x22, 0x25, 0x26, 0x2C); + var guid = new Guid(1, 2, 3, 0x27, 0x5C, 0x7B, 0x7D, 0x22, 0x25, 0x26, 0x2C); - using (var cmd = connection.CreateCommand()) - { - cmd.CommandText = @"insert into old_guids(guid) values(@guid)"; - var parameter = cmd.CreateParameter(); - parameter.ParameterName = "@guid"; - parameter.Value = guid; - cmd.Parameters.Add(parameter); - cmd.ExecuteNonQuery(); - } + using (var cmd = connection.CreateCommand()) + { + cmd.CommandText = @"insert into old_guids(guid) values(@guid)"; + var parameter = cmd.CreateParameter(); + parameter.ParameterName = "@guid"; + parameter.Value = guid; + cmd.Parameters.Add(parameter); + cmd.ExecuteNonQuery(); + } - using (var cmd = connection.CreateCommand()) - { - cmd.CommandText = @"select guid from old_guids;"; - var selected = (Guid) cmd.ExecuteScalar(); - Assert.Equal(guid, selected); - } + using (var cmd = connection.CreateCommand()) + { + cmd.CommandText = @"select guid from old_guids;"; + var selected = (Guid) cmd.ExecuteScalar(); + Assert.Equal(guid, selected); } } @@ -285,20 +269,17 @@ public async Task EnumParametersAreParsedCorrectly() try { await m_database.Connection.OpenAsync(); - using (var command = new MySqlCommand("INSERT INTO insert_enum_value2 (`Varchar`, `String`, `Int`) VALUES (@Varchar, @String, @Int);", m_database.Connection)) - { - - command.Parameters.Add(new MySqlParameter("@String", MySqlColor.Orange)).MySqlDbType = MySqlDbType.String; - command.Parameters.Add(new MySqlParameter("@Varchar", MySqlColor.Green)).MySqlDbType = MySqlDbType.VarChar; - command.Parameters.Add(new MySqlParameter("@Int", MySqlColor.None)); - - await command.ExecuteNonQueryAsync(); - var result = (await m_database.Connection.QueryAsync(@"select `Varchar`, `String`, `Int` from insert_enum_value2;")).ToArray(); - Assert.Single(result); - Assert.Equal(MySqlColor.Orange.ToString("G"), result[0].String); - Assert.Equal(MySqlColor.Green.ToString("G"), result[0].Varchar); - Assert.Equal((int) MySqlColor.None, result[0].Int); - } + using var command = new MySqlCommand("INSERT INTO insert_enum_value2 (`Varchar`, `String`, `Int`) VALUES (@Varchar, @String, @Int);", m_database.Connection); + command.Parameters.Add(new MySqlParameter("@String", MySqlColor.Orange)).MySqlDbType = MySqlDbType.String; + command.Parameters.Add(new MySqlParameter("@Varchar", MySqlColor.Green)).MySqlDbType = MySqlDbType.VarChar; + command.Parameters.Add(new MySqlParameter("@Int", MySqlColor.None)); + + await command.ExecuteNonQueryAsync(); + var result = (await m_database.Connection.QueryAsync(@"select `Varchar`, `String`, `Int` from insert_enum_value2;")).ToArray(); + Assert.Single(result); + Assert.Equal(MySqlColor.Orange.ToString("G"), result[0].String); + Assert.Equal(MySqlColor.Green.ToString("G"), result[0].Varchar); + Assert.Equal((int) MySqlColor.None, result[0].Int); } finally { @@ -398,24 +379,22 @@ value set('one', 'two', 'four', 'eight') null [MemberData(nameof(GetBlobs))] public void InsertBlob(object data, bool prepare) { - using (var connection = new MySqlConnection(AppConfig.ConnectionString + ";IgnorePrepare=false")) - { - connection.Open(); - connection.Execute(@"drop table if exists insert_mysql_blob; + using var connection = new MySqlConnection(AppConfig.ConnectionString + ";IgnorePrepare=false"); + connection.Open(); + connection.Execute(@"drop table if exists insert_mysql_blob; create table insert_mysql_blob( - rowid integer not null primary key auto_increment, - value mediumblob null +rowid integer not null primary key auto_increment, +value mediumblob null );"); - using (var cmd = new MySqlCommand("insert into insert_mysql_blob(value) values(@data);", connection)) - { - cmd.Parameters.AddWithValue("@data", data); - if (prepare) - cmd.Prepare(); - cmd.ExecuteNonQuery(); - } - Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6 }, connection.Query(@"select value from insert_mysql_blob;").Single()); + using (var cmd = new MySqlCommand("insert into insert_mysql_blob(value) values(@data);", connection)) + { + cmd.Parameters.AddWithValue("@data", data); + if (prepare) + cmd.Prepare(); + cmd.ExecuteNonQuery(); } + Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6 }, connection.Query(@"select value from insert_mysql_blob;").Single()); } public static IEnumerable GetBlobs() diff --git a/tests/SideBySide/PreparedCommandTests.cs b/tests/SideBySide/PreparedCommandTests.cs index 7e1264c7c..8f7f7c0f0 100644 --- a/tests/SideBySide/PreparedCommandTests.cs +++ b/tests/SideBySide/PreparedCommandTests.cs @@ -16,74 +16,66 @@ public PreparedCommandTests(DatabaseFixture database) [SkippableFact(Baseline = "Parameter '@data' was not found during prepare.")] public void PrepareBeforeBindingParameters() { - using (var connection = CreatePrepareConnection()) - { - connection.Execute($@"DROP TABLE IF EXISTS bind_parameters_test; + using var connection = CreatePrepareConnection(); + connection.Execute($@"DROP TABLE IF EXISTS bind_parameters_test; CREATE TABLE bind_parameters_test(data TEXT NOT NULL);"); - using (var command = new MySqlCommand(@"INSERT INTO bind_parameters_test(data) VALUES(@data);", connection)) - { - command.Prepare(); - command.Parameters.AddWithValue("@data", "test"); - command.ExecuteNonQuery(); - } - - Assert.Equal(new[] { "test" }, connection.Query("SELECT data FROM bind_parameters_test;")); + using (var command = new MySqlCommand(@"INSERT INTO bind_parameters_test(data) VALUES(@data);", connection)) + { + command.Prepare(); + command.Parameters.AddWithValue("@data", "test"); + command.ExecuteNonQuery(); } + + Assert.Equal(new[] { "test" }, connection.Query("SELECT data FROM bind_parameters_test;")); } [SkippableFact(Baseline = "https://bugs.mysql.com/bug.php?id=91753")] public void UnnamedParameters() { - using (var connection = CreatePrepareConnection()) - { - connection.Execute($@"DROP TABLE IF EXISTS bind_parameters_test; + using var connection = CreatePrepareConnection(); + connection.Execute($@"DROP TABLE IF EXISTS bind_parameters_test; CREATE TABLE bind_parameters_test(data1 TEXT NOT NULL, data2 INTEGER);"); - using (var command = new MySqlCommand(@"INSERT INTO bind_parameters_test(data1, data2) VALUES(?, ?);", connection)) - { - command.Parameters.Add(new MySqlParameter { Value = "test" }); - command.Parameters.Add(new MySqlParameter { Value = 1234 }); - command.Prepare(); - command.ExecuteNonQuery(); - } + using (var command = new MySqlCommand(@"INSERT INTO bind_parameters_test(data1, data2) VALUES(?, ?);", connection)) + { + command.Parameters.Add(new MySqlParameter { Value = "test" }); + command.Parameters.Add(new MySqlParameter { Value = 1234 }); + command.Prepare(); + command.ExecuteNonQuery(); + } - using (var command = new MySqlCommand(@"SELECT data1, data2 FROM bind_parameters_test;", connection)) - { - command.Prepare(); - using (var reader = command.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Equal("test", reader.GetValue(0)); - Assert.Equal(1234, reader.GetValue(1)); - } - } + using (var command = new MySqlCommand(@"SELECT data1, data2 FROM bind_parameters_test;", connection)) + { + command.Prepare(); + using var reader = command.ExecuteReader(); + Assert.True(reader.Read()); + Assert.Equal("test", reader.GetValue(0)); + Assert.Equal(1234, reader.GetValue(1)); } } [Fact] public void ReuseCommand() { - using (var connection = CreatePrepareConnection()) - { - connection.Execute($@"DROP TABLE IF EXISTS reuse_command_test; + using var connection = CreatePrepareConnection(); + connection.Execute($@"DROP TABLE IF EXISTS reuse_command_test; CREATE TABLE reuse_command_test(rowid INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, data TEXT NOT NULL);"); - using (var command = new MySqlCommand(@"INSERT INTO reuse_command_test(data) VALUES(@data);", connection)) - { - // work around Connector/NET failure; see PrepareBeforeBindingParameters - var parameter = command.Parameters.AddWithValue("@data", ""); - command.Prepare(); + using (var command = new MySqlCommand(@"INSERT INTO reuse_command_test(data) VALUES(@data);", connection)) + { + // work around Connector/NET failure; see PrepareBeforeBindingParameters + var parameter = command.Parameters.AddWithValue("@data", ""); + command.Prepare(); - foreach (var value in new[] { "one", "two", "three" }) - { - parameter.Value = value; - command.ExecuteNonQuery(); - } + foreach (var value in new[] { "one", "two", "three" }) + { + parameter.Value = value; + command.ExecuteNonQuery(); } - - Assert.Equal(new[] { "one", "two", "three" }, connection.Query("SELECT data FROM reuse_command_test ORDER BY rowid;")); } + + Assert.Equal(new[] { "one", "two", "three" }, connection.Query("SELECT data FROM reuse_command_test ORDER BY rowid;")); } [Theory] @@ -94,41 +86,37 @@ public void InsertAndQuery(bool isPrepared, string dataType, object dataValue, M { IgnorePrepare = !isPrepared, }; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); - connection.Execute($@"DROP TABLE IF EXISTS prepared_command_test; + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); + connection.Execute($@"DROP TABLE IF EXISTS prepared_command_test; CREATE TABLE prepared_command_test(rowid INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, data {dataType});"); - using (var command = new MySqlCommand("INSERT INTO prepared_command_test(data) VALUES(@null), (@data);", connection)) - { - command.Parameters.AddWithValue("@null", null); - command.Parameters.AddWithValue("@data", dataValue).MySqlDbType = dbType; - if (isPrepared) - command.Prepare(); - Assert.Equal(isPrepared, command.IsPrepared); - command.ExecuteNonQuery(); - } + using (var command = new MySqlCommand("INSERT INTO prepared_command_test(data) VALUES(@null), (@data);", connection)) + { + command.Parameters.AddWithValue("@null", null); + command.Parameters.AddWithValue("@data", dataValue).MySqlDbType = dbType; + if (isPrepared) + command.Prepare(); + Assert.Equal(isPrepared, command.IsPrepared); + command.ExecuteNonQuery(); + } - using (var command = new MySqlCommand("SELECT data FROM prepared_command_test ORDER BY rowid;", connection)) - { - if (isPrepared) - command.Prepare(); - Assert.Equal(isPrepared, command.IsPrepared); - - using (var reader = command.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.True(reader.IsDBNull(0)); - - Assert.True(reader.Read()); - Assert.False(reader.IsDBNull(0)); - Assert.Equal(dataValue, reader.GetValue(0)); - - Assert.False(reader.Read()); - Assert.False(reader.NextResult()); - } - } + using (var command = new MySqlCommand("SELECT data FROM prepared_command_test ORDER BY rowid;", connection)) + { + if (isPrepared) + command.Prepare(); + Assert.Equal(isPrepared, command.IsPrepared); + + using var reader = command.ExecuteReader(); + Assert.True(reader.Read()); + Assert.True(reader.IsDBNull(0)); + + Assert.True(reader.Read()); + Assert.False(reader.IsDBNull(0)); + Assert.Equal(dataValue, reader.GetValue(0)); + + Assert.False(reader.Read()); + Assert.False(reader.NextResult()); } } @@ -141,41 +129,37 @@ public void InsertAndQueryInferrredType(bool isPrepared, string dataType, object { IgnorePrepare = !isPrepared, }; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); - connection.Execute($@"DROP TABLE IF EXISTS prepared_command_test; + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); + connection.Execute($@"DROP TABLE IF EXISTS prepared_command_test; CREATE TABLE prepared_command_test(rowid INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, data {dataType});"); - using (var command = new MySqlCommand("INSERT INTO prepared_command_test(data) VALUES(@null), (@data);", connection)) - { - command.Parameters.AddWithValue("@null", null); - command.Parameters.AddWithValue("@data", dataValue); - if (isPrepared) - command.Prepare(); - Assert.Equal(isPrepared, command.IsPrepared); - command.ExecuteNonQuery(); - } + using (var command = new MySqlCommand("INSERT INTO prepared_command_test(data) VALUES(@null), (@data);", connection)) + { + command.Parameters.AddWithValue("@null", null); + command.Parameters.AddWithValue("@data", dataValue); + if (isPrepared) + command.Prepare(); + Assert.Equal(isPrepared, command.IsPrepared); + command.ExecuteNonQuery(); + } - using (var command = new MySqlCommand("SELECT data FROM prepared_command_test ORDER BY rowid;", connection)) - { - if (isPrepared) - command.Prepare(); - Assert.Equal(isPrepared, command.IsPrepared); - - using (var reader = command.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.True(reader.IsDBNull(0)); - - Assert.True(reader.Read()); - Assert.False(reader.IsDBNull(0)); - Assert.Equal(dataValue, reader.GetValue(0)); - - Assert.False(reader.Read()); - Assert.False(reader.NextResult()); - } - } + using (var command = new MySqlCommand("SELECT data FROM prepared_command_test ORDER BY rowid;", connection)) + { + if (isPrepared) + command.Prepare(); + Assert.Equal(isPrepared, command.IsPrepared); + + using var reader = command.ExecuteReader(); + Assert.True(reader.Read()); + Assert.True(reader.IsDBNull(0)); + + Assert.True(reader.Read()); + Assert.False(reader.IsDBNull(0)); + Assert.Equal(dataValue, reader.GetValue(0)); + + Assert.False(reader.Read()); + Assert.False(reader.NextResult()); } } @@ -187,125 +171,106 @@ public void InsertAndQueryMultipleStatements(bool isPrepared, string dataType, o { IgnorePrepare = !isPrepared, }; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); - connection.Execute($@"DROP TABLE IF EXISTS prepared_command_test; + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); + connection.Execute($@"DROP TABLE IF EXISTS prepared_command_test; CREATE TABLE prepared_command_test(rowid INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, data {dataType});"); - using (var command = new MySqlCommand(@"INSERT INTO prepared_command_test(data) VALUES(@null); + using var command = new MySqlCommand(@"INSERT INTO prepared_command_test(data) VALUES(@null); INSERT INTO prepared_command_test(data) VALUES(@data); -SELECT data FROM prepared_command_test ORDER BY rowid;", connection)) - { - command.Parameters.AddWithValue("@null", null); - command.Parameters.AddWithValue("@data", dataValue).MySqlDbType = dbType; - if (isPrepared) - command.Prepare(); - Assert.Equal(isPrepared, command.IsPrepared); - - using (var reader = command.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.True(reader.IsDBNull(0)); - - Assert.True(reader.Read()); - Assert.False(reader.IsDBNull(0)); - Assert.Equal(dataValue, reader.GetValue(0)); - - Assert.False(reader.Read()); - Assert.False(reader.NextResult()); - } - } - } +SELECT data FROM prepared_command_test ORDER BY rowid;", connection); + command.Parameters.AddWithValue("@null", null); + command.Parameters.AddWithValue("@data", dataValue).MySqlDbType = dbType; + if (isPrepared) + command.Prepare(); + Assert.Equal(isPrepared, command.IsPrepared); + + using var reader = command.ExecuteReader(); + Assert.True(reader.Read()); + Assert.True(reader.IsDBNull(0)); + + Assert.True(reader.Read()); + Assert.False(reader.IsDBNull(0)); + Assert.Equal(dataValue, reader.GetValue(0)); + + Assert.False(reader.Read()); + Assert.False(reader.NextResult()); } [Fact] public void PrepareMultipleTimes() { - using (var connection = CreatePrepareConnection()) - { - using (var cmd = new MySqlCommand("SELECT 'test';", connection)) - { - Assert.False(cmd.IsPrepared); - cmd.Prepare(); - Assert.True(cmd.IsPrepared); - cmd.Prepare(); - Assert.Equal("test", cmd.ExecuteScalar()); - } - } + using var connection = CreatePrepareConnection(); + using var cmd = new MySqlCommand("SELECT 'test';", connection); + Assert.False(cmd.IsPrepared); + cmd.Prepare(); + Assert.True(cmd.IsPrepared); + cmd.Prepare(); + Assert.Equal("test", cmd.ExecuteScalar()); } [SkippableFact(Baseline = "Connector/NET doesn't cache prepared commands")] public void PreparedCommandIsCached() { - using (var connection = CreatePrepareConnection()) + using var connection = CreatePrepareConnection(); + + using (var cmd = new MySqlCommand("SELECT 'test';", connection)) { - using (var cmd = new MySqlCommand("SELECT 'test';", connection)) - { - cmd.Prepare(); - Assert.Equal("test", cmd.ExecuteScalar()); - } + cmd.Prepare(); + Assert.Equal("test", cmd.ExecuteScalar()); + } - using (var cmd = new MySqlCommand("SELECT 'test';", connection)) - { - Assert.True(cmd.IsPrepared); - Assert.Equal("test", cmd.ExecuteScalar()); - } + using (var cmd = new MySqlCommand("SELECT 'test';", connection)) + { + Assert.True(cmd.IsPrepared); + Assert.Equal("test", cmd.ExecuteScalar()); } } [Fact] public void ThrowsIfNamedParameterUsedButNoParametersDefined() { - using (var connection = CreatePrepareConnection()) - using (var cmd = new MySqlCommand("SELECT @param;", connection)) - { + using var connection = CreatePrepareConnection(); + using var cmd = new MySqlCommand("SELECT @param;", connection); #if BASELINE - Assert.Throws(() => cmd.Prepare()); + Assert.Throws(() => cmd.Prepare()); #else - cmd.Prepare(); - Assert.Throws(() => cmd.ExecuteScalar()); + cmd.Prepare(); + Assert.Throws(() => cmd.ExecuteScalar()); #endif - } } [Fact] public void ThrowsIfUnnamedParameterUsedButNoParametersDefined() { - using (var connection = CreatePrepareConnection()) - using (var cmd = new MySqlCommand("SELECT ?;", connection)) - { - cmd.Prepare(); - Assert.Throws(() => cmd.ExecuteScalar()); - } + using var connection = CreatePrepareConnection(); + using var cmd = new MySqlCommand("SELECT ?;", connection); + cmd.Prepare(); + Assert.Throws(() => cmd.ExecuteScalar()); } [Fact] public void ThrowsIfUndefinedNamedParameterUsed() { - using (var connection = CreatePrepareConnection()) - using (var cmd = new MySqlCommand("SELECT @param;", connection)) - { - cmd.Parameters.AddWithValue("@name", "test"); + using var connection = CreatePrepareConnection(); + using var cmd = new MySqlCommand("SELECT @param;", connection); + cmd.Parameters.AddWithValue("@name", "test"); #if BASELINE - Assert.Throws(() => cmd.Prepare()); + Assert.Throws(() => cmd.Prepare()); #else - cmd.Prepare(); - Assert.Throws(() => cmd.ExecuteScalar()); + cmd.Prepare(); + Assert.Throws(() => cmd.ExecuteScalar()); #endif - } } [Fact] public void ThrowsIfTooManyUnnamedParametersUsed() { - using (var connection = CreatePrepareConnection()) - using (var cmd = new MySqlCommand("SELECT ?, ?;", connection)) - { - cmd.Parameters.Add(new MySqlParameter { Value = 1 }); - cmd.Prepare(); - Assert.Throws(() => cmd.ExecuteScalar()); - } + using var connection = CreatePrepareConnection(); + using var cmd = new MySqlCommand("SELECT ?, ?;", connection); + cmd.Parameters.Add(new MySqlParameter { Value = 1 }); + cmd.Prepare(); + Assert.Throws(() => cmd.ExecuteScalar()); } [Theory] @@ -330,38 +295,32 @@ public void ThrowsIfTooManyUnnamedParametersUsed() [InlineData(65535)] public void ParametersAreBound(int parameterCount) { - using (var connection = CreateConnectionWithTableOfIntegers()) - using (var cmd = CreateCommandWithParameters(connection, parameterCount)) - { - cmd.Prepare(); + using var connection = CreateConnectionWithTableOfIntegers(); + using var cmd = CreateCommandWithParameters(connection, parameterCount); + cmd.Prepare(); - using (var reader = cmd.ExecuteReader()) - { - for (var i = 1; i <= Math.Min(parameterCount, 10); i++) - { - Assert.True(reader.Read()); - Assert.Equal(i, reader.GetInt32(0)); - } - Assert.False(reader.Read()); - } + using var reader = cmd.ExecuteReader(); + for (var i = 1; i <= Math.Min(parameterCount, 10); i++) + { + Assert.True(reader.Read()); + Assert.Equal(i, reader.GetInt32(0)); } + Assert.False(reader.Read()); } [Fact] public void CannotUse64KParameters() { - using (var connection = CreateConnectionWithTableOfIntegers()) - using (var cmd = CreateCommandWithParameters(connection, 65536)) + using var connection = CreateConnectionWithTableOfIntegers(); + using var cmd = CreateCommandWithParameters(connection, 65536); + try { - try - { - cmd.Prepare(); - Assert.False(true, "Exception wasn't thrown"); - } - catch (MySqlException ex) - { - Assert.Equal(MySqlErrorCode.PreparedStatementManyParameters, (MySqlErrorCode) ex.Number); - } + cmd.Prepare(); + Assert.False(true, "Exception wasn't thrown"); + } + catch (MySqlException ex) + { + Assert.Equal(MySqlErrorCode.PreparedStatementManyParameters, (MySqlErrorCode) ex.Number); } } diff --git a/tests/SideBySide/QueryTests.cs b/tests/SideBySide/QueryTests.cs index 645c577f2..d16ed812e 100644 --- a/tests/SideBySide/QueryTests.cs +++ b/tests/SideBySide/QueryTests.cs @@ -26,90 +26,71 @@ public void Dispose() [Fact] public void GetOrdinal() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "select 0 as zero, 1 as one;"; - using (var reader = cmd.ExecuteReader()) - { - Assert.Equal(0, reader.GetOrdinal("zero")); - Assert.Equal(1, reader.GetOrdinal("one")); - } - } + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "select 0 as zero, 1 as one;"; + + using var reader = cmd.ExecuteReader(); + Assert.Equal(0, reader.GetOrdinal("zero")); + Assert.Equal(1, reader.GetOrdinal("one")); } [Fact] public void GetOrdinalIgnoreCase() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "select 0 as zero, 1 as one;"; - using (var reader = cmd.ExecuteReader()) - { - Assert.Equal(0, reader.GetOrdinal("Zero")); - Assert.Equal(1, reader.GetOrdinal("ONE")); - } - } + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "select 0 as zero, 1 as one;"; + + using var reader = cmd.ExecuteReader(); + Assert.Equal(0, reader.GetOrdinal("Zero")); + Assert.Equal(1, reader.GetOrdinal("ONE")); } [Fact] public void GetOrdinalExceptionForNoColumn() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "select 0 as zero, 1 as one;"; - using (var reader = cmd.ExecuteReader()) - { - Assert.Throws(() => reader.GetOrdinal("three")); - } - } + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "select 0 as zero, 1 as one;"; + + using var reader = cmd.ExecuteReader(); + Assert.Throws(() => reader.GetOrdinal("three")); } [Fact] public void GetOrdinalExceptionForNull() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "select 0 as zero, 1 as one;"; - using (var reader = cmd.ExecuteReader()) - { - Assert.Throws(() => reader.GetOrdinal(null)); - } - } + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "select 0 as zero, 1 as one;"; + + using var reader = cmd.ExecuteReader(); + Assert.Throws(() => reader.GetOrdinal(null)); } [Fact] public void GetOrdinalAfterNextResult() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "select 0 as zero, 1 as one;"; - using (var reader = cmd.ExecuteReader()) - { - Assert.False(reader.NextResult()); + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "select 0 as zero, 1 as one;"; + using var reader = cmd.ExecuteReader(); + Assert.False(reader.NextResult()); #if BASELINE - Assert.Throws(() => reader.GetOrdinal("zero")); + Assert.Throws(() => reader.GetOrdinal("zero")); #else - Assert.Throws(() => reader.GetOrdinal("zero")); + Assert.Throws(() => reader.GetOrdinal("zero")); #endif - } - } } [Fact] public void GetOrdinalBeforeAndAfterRead() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "select 0 as zero, 1 as one;"; - using (var reader = cmd.ExecuteReader()) - { - Assert.Equal(1, reader.GetOrdinal("one")); - Assert.True(reader.Read()); - Assert.Equal(1, reader.GetOrdinal("one")); - Assert.False(reader.Read()); - Assert.Equal(1, reader.GetOrdinal("one")); - } - } + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "select 0 as zero, 1 as one;"; + + using var reader = cmd.ExecuteReader(); + Assert.Equal(1, reader.GetOrdinal("one")); + Assert.True(reader.Read()); + Assert.Equal(1, reader.GetOrdinal("one")); + Assert.False(reader.Read()); + Assert.Equal(1, reader.GetOrdinal("one")); } [Fact] @@ -117,13 +98,12 @@ public void WithoutUserVariables() { var csb = AppConfig.CreateConnectionStringBuilder(); csb.AllowUserVariables = false; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); - var cmd = connection.CreateCommand(); - cmd.CommandText = "set @var = 1; select @var + 1;"; - Assert.Throws(() => cmd.ExecuteScalar()); - } + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); + + using var cmd = connection.CreateCommand(); + cmd.CommandText = "set @var = 1; select @var + 1;"; + Assert.Throws(() => cmd.ExecuteScalar()); } [Fact] @@ -131,13 +111,12 @@ public void WithUserVariables() { var csb = AppConfig.CreateConnectionStringBuilder(); csb.AllowUserVariables = true; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - connection.Open(); - var cmd = connection.CreateCommand(); - cmd.CommandText = "set @var = 1; select @var + 1;"; - Assert.Equal(2L, cmd.ExecuteScalar()); - } + using var connection = new MySqlConnection(csb.ConnectionString); + connection.Open(); + + using var cmd = connection.CreateCommand(); + cmd.CommandText = "set @var = 1; select @var + 1;"; + Assert.Equal(2L, cmd.ExecuteScalar()); } [Fact] @@ -155,81 +134,65 @@ public void NextResultBeforeRead() using (var cmd = m_database.Connection.CreateCommand()) { cmd.CommandText = "select id, value FROM query_test;"; - using (var reader = cmd.ExecuteReader()) - Assert.False(reader.NextResult()); + using var reader = cmd.ExecuteReader(); + Assert.False(reader.NextResult()); } } [Fact] public void ReadAfterDispose() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "SELECT 1;"; - using (var reader = cmd.ExecuteReader()) - { - reader.Dispose(); + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "SELECT 1;"; + using var reader = cmd.ExecuteReader(); + reader.Dispose(); #if BASELINE - Assert.Throws(() => reader.Read()); + Assert.Throws(() => reader.Read()); #else - Assert.Throws(() => reader.Read()); + Assert.Throws(() => reader.Read()); #endif - } - } } [Fact] public async Task ReadAsyncAfterDispose() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "SELECT 1;"; - using (var reader = cmd.ExecuteReader()) - { - reader.Dispose(); + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "SELECT 1;"; + using var reader = cmd.ExecuteReader(); + reader.Dispose(); #if BASELINE - await Assert.ThrowsAsync(() => reader.ReadAsync()); + await Assert.ThrowsAsync(() => reader.ReadAsync()); #else - await Assert.ThrowsAsync(() => reader.ReadAsync()); + await Assert.ThrowsAsync(() => reader.ReadAsync()); #endif - } - } } [Fact] public void NextResultAfterDispose() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "SELECT 1;"; - using (var reader = cmd.ExecuteReader()) - { - reader.Dispose(); + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "SELECT 1;"; + using var reader = cmd.ExecuteReader(); + reader.Dispose(); #if BASELINE - Assert.Throws(() => reader.NextResult()); + Assert.Throws(() => reader.NextResult()); #else - Assert.Throws(() => reader.NextResult()); + Assert.Throws(() => reader.NextResult()); #endif - } - } } [Fact] public async Task NextResultAsyncAfterDispose() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "SELECT 1;"; - using (var reader = cmd.ExecuteReader()) - { - reader.Dispose(); + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "SELECT 1;"; + using var reader = cmd.ExecuteReader(); + reader.Dispose(); #if BASELINE - await Assert.ThrowsAsync(() => reader.NextResultAsync()); + await Assert.ThrowsAsync(() => reader.NextResultAsync()); #else - await Assert.ThrowsAsync(() => reader.NextResultAsync()); + await Assert.ThrowsAsync(() => reader.NextResultAsync()); #endif - } - } } [Fact] @@ -301,37 +264,33 @@ public async Task MultipleReaders() await cmd.ExecuteNonQueryAsync(); } - using (var cmd1 = m_database.Connection.CreateCommand()) - using (var cmd2 = m_database.Connection.CreateCommand()) - { - cmd1.CommandText = @"select id from query_multiple_readers;"; - cmd2.CommandText = @"select id from query_multiple_readers order by id;"; + using var cmd1 = m_database.Connection.CreateCommand(); + cmd1.CommandText = @"select id from query_multiple_readers;"; + using var cmd2 = m_database.Connection.CreateCommand(); + cmd2.CommandText = @"select id from query_multiple_readers order by id;"; - using (var reader1 = await cmd1.ExecuteReaderAsync()) + using var reader1 = await cmd1.ExecuteReaderAsync(); + Assert.Throws(exceptionType, () => cmd2.ExecuteReader()); + Assert.Throws(exceptionType, () => cmd2.ExecuteScalar()); + do + { + while (await reader1.ReadAsync()) { Assert.Throws(exceptionType, () => cmd2.ExecuteReader()); Assert.Throws(exceptionType, () => cmd2.ExecuteScalar()); - do - { - while (await reader1.ReadAsync()) - { - Assert.Throws(exceptionType, () => cmd2.ExecuteReader()); - Assert.Throws(exceptionType, () => cmd2.ExecuteScalar()); - } - Assert.Throws(exceptionType, () => cmd2.ExecuteReader()); - Assert.Throws(exceptionType, () => cmd2.ExecuteScalar()); - } while (await reader1.NextResultAsync()); + } + Assert.Throws(exceptionType, () => cmd2.ExecuteReader()); + Assert.Throws(exceptionType, () => cmd2.ExecuteScalar()); + } while (await reader1.NextResultAsync()); - Assert.Throws(exceptionType, () => cmd2.ExecuteReader()); - Assert.Throws(exceptionType, () => cmd2.ExecuteScalar()); + Assert.Throws(exceptionType, () => cmd2.ExecuteReader()); + Assert.Throws(exceptionType, () => cmd2.ExecuteScalar()); - reader1.Dispose(); - using (cmd2.ExecuteReader()) - { - } - Assert.Equal(1, cmd2.ExecuteScalar()); - } + reader1.Dispose(); + using (cmd2.ExecuteReader()) + { } + Assert.Equal(1, cmd2.ExecuteScalar()); } [Fact] @@ -345,24 +304,22 @@ public async Task UndisposedReader() await cmd.ExecuteNonQueryAsync(); } - using (var cmd1 = m_database.Connection.CreateCommand()) - using (var cmd2 = m_database.Connection.CreateCommand()) - { - var commandText = @"select id from query_undisposed_reader order by id;"; - cmd1.CommandText = commandText; - cmd2.CommandText = commandText; + using var cmd1 = m_database.Connection.CreateCommand(); + using var cmd2 = m_database.Connection.CreateCommand(); + var commandText = @"select id from query_undisposed_reader order by id;"; + cmd1.CommandText = commandText; + cmd2.CommandText = commandText; - var reader1 = await cmd1.ExecuteReaderAsync(); - Assert.True(reader1.Read()); - Assert.Equal(1, reader1.GetInt32(0)); + var reader1 = await cmd1.ExecuteReaderAsync(); + Assert.True(reader1.Read()); + Assert.Equal(1, reader1.GetInt32(0)); - m_database.Connection.Close(); - m_database.Connection.Open(); + m_database.Connection.Close(); + m_database.Connection.Open(); - var reader2 = await cmd1.ExecuteReaderAsync(); - Assert.True(reader2.Read()); - Assert.Equal(1, reader2.GetInt32(0)); - } + var reader2 = await cmd1.ExecuteReaderAsync(); + Assert.True(reader2.Read()); + Assert.Equal(1, reader2.GetInt32(0)); } [Fact] @@ -382,14 +339,12 @@ public async Task MultipleStatements() select value2 from query_multiple_statements order by value2; select value3 from query_multiple_statements order by value3;"; - using (var reader = await cmd.ExecuteReaderAsync()) - { - Assert.True(await reader.NextResultAsync()); - Assert.True(await reader.NextResultAsync()); - Assert.True(await reader.ReadAsync()); - Assert.Equal(3, reader.GetInt32(0)); - Assert.False(await reader.NextResultAsync()); - } + using var reader = await cmd.ExecuteReaderAsync(); + Assert.True(await reader.NextResultAsync()); + Assert.True(await reader.NextResultAsync()); + Assert.True(await reader.ReadAsync()); + Assert.Equal(3, reader.GetInt32(0)); + Assert.False(await reader.NextResultAsync()); } } @@ -463,66 +418,55 @@ public async Task ParameterIsNull() { cmd.CommandText = "select id, value FROM query_null_parameter where @parameter is null or value = @parameter order by id;"; cmd.Parameters.Add(new MySqlParameter { ParameterName = "@parameter", Value = "one" }); - using (var reader = cmd.ExecuteReader()) - { - Assert.True(await reader.ReadAsync()); - Assert.Equal(1L, reader.GetInt64(0)); - Assert.False(await reader.ReadAsync()); - Assert.False(await reader.NextResultAsync()); - } + using var reader = cmd.ExecuteReader(); + Assert.True(await reader.ReadAsync()); + Assert.Equal(1L, reader.GetInt64(0)); + Assert.False(await reader.ReadAsync()); + Assert.False(await reader.NextResultAsync()); } using (var cmd = m_database.Connection.CreateCommand()) { cmd.CommandText = "select id, value FROM query_null_parameter where @parameter is null or value = @parameter order by id;"; cmd.Parameters.Add(new MySqlParameter { ParameterName = "@parameter", Value = null }); - using (var reader = cmd.ExecuteReader()) - { - Assert.True(await reader.ReadAsync()); - Assert.Equal(1L, reader.GetInt64(0)); - Assert.True(await reader.ReadAsync()); - Assert.Equal(2L, reader.GetInt64(0)); - Assert.True(await reader.ReadAsync()); - Assert.Equal(3L, reader.GetInt64(0)); - Assert.False(await reader.ReadAsync()); - Assert.False(await reader.NextResultAsync()); - } + using var reader = cmd.ExecuteReader(); + Assert.True(await reader.ReadAsync()); + Assert.Equal(1L, reader.GetInt64(0)); + Assert.True(await reader.ReadAsync()); + Assert.Equal(2L, reader.GetInt64(0)); + Assert.True(await reader.ReadAsync()); + Assert.Equal(3L, reader.GetInt64(0)); + Assert.False(await reader.ReadAsync()); + Assert.False(await reader.NextResultAsync()); } } [Fact] public async Task DoubleDispose() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = @"select 1;"; - using (var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false)) - { - Assert.True(await reader.ReadAsync().ConfigureAwait(false)); - reader.Dispose(); - reader.Dispose(); - } - } + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = @"select 1;"; + using var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false); + Assert.True(await reader.ReadAsync().ConfigureAwait(false)); + reader.Dispose(); + reader.Dispose(); } [Fact] public async Task MultipleStatementsWithInvalidSql() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = @"select 1; select 1 from mysql.abc; select 2;"; - using (var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false)) - { - Assert.True(await reader.ReadAsync().ConfigureAwait(false)); - Assert.Equal(1, reader.GetInt32(0)); - Assert.False(await reader.ReadAsync().ConfigureAwait(false)); + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = @"select 1; select 1 from mysql.abc; select 2;"; - await Assert.ThrowsAsync(() => reader.NextResultAsync()); - Assert.False(await reader.ReadAsync().ConfigureAwait(false)); + using var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false); + Assert.True(await reader.ReadAsync().ConfigureAwait(false)); + Assert.Equal(1, reader.GetInt32(0)); + Assert.False(await reader.ReadAsync().ConfigureAwait(false)); - Assert.False(await reader.NextResultAsync().ConfigureAwait(false)); - } - } + await Assert.ThrowsAsync(() => reader.NextResultAsync()); + Assert.False(await reader.ReadAsync().ConfigureAwait(false)); + + Assert.False(await reader.NextResultAsync().ConfigureAwait(false)); } [Fact] @@ -554,8 +498,8 @@ public async Task GetEnumerator() using (var cmd = m_database.Connection.CreateCommand()) { cmd.CommandText = @"select value from query_enumerator order by value asc;"; - using (var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false)) - Assert.Equal(new[] { "four", "one", "three", "two" }, reader.Cast().Select(x => x.GetString(0))); + using var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false); + Assert.Equal(new[] { "four", "one", "three", "two" }, reader.Cast().Select(x => x.GetString(0))); } } @@ -622,29 +566,24 @@ public void ExecuteScalarReturnsNull() [Fact] public void ExecuteScalarReturnsDBNull() { - using (var command = m_database.Connection.CreateCommand()) - { - command.CommandText = "select null; select 2;"; - var result = command.ExecuteScalar(); - Assert.Equal(DBNull.Value, result); - } + using var command = m_database.Connection.CreateCommand(); + command.CommandText = "select null; select 2;"; + var result = command.ExecuteScalar(); + Assert.Equal(DBNull.Value, result); } [Fact] public void TrailingCommentIsNotAResultSet() { - using (var command = m_database.Connection.CreateCommand()) - { - command.CommandText = "select 0; -- trailing comment"; - using (var reader = command.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Equal(0, reader.GetInt32(0)); - Assert.False(reader.NextResult()); - Assert.False(reader.HasRows); - Assert.False(reader.Read()); - } - } + using var command = m_database.Connection.CreateCommand(); + command.CommandText = "select 0; -- trailing comment"; + + using var reader = command.ExecuteReader(); + Assert.True(reader.Read()); + Assert.Equal(0, reader.GetInt32(0)); + Assert.False(reader.NextResult()); + Assert.False(reader.HasRows); + Assert.False(reader.Read()); } [Fact] @@ -654,18 +593,14 @@ public void SumBytes() create table sum_bytes(value tinyint unsigned not null); insert into sum_bytes(value) values(0), (1), (2), (254), (255);"); - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "select sum(value) from sum_bytes"; - Assert.Equal(512m, cmd.ExecuteScalar()); + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "select sum(value) from sum_bytes"; + Assert.Equal(512m, cmd.ExecuteScalar()); - using (var reader = cmd.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Equal(512m, reader.GetValue(0)); - Assert.Equal(512, reader.GetInt32(0)); - } - } + using var reader = cmd.ExecuteReader(); + Assert.True(reader.Read()); + Assert.Equal(512m, reader.GetValue(0)); + Assert.Equal(512, reader.GetInt32(0)); } [Fact] @@ -675,20 +610,16 @@ public void SumShorts() create table sum_shorts(value smallint unsigned not null); insert into sum_shorts(value) values(0), (1), (2), (32766), (32767);"); - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "select sum(value) from sum_shorts"; - Assert.Equal(65536m, cmd.ExecuteScalar()); + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "select sum(value) from sum_shorts"; + Assert.Equal(65536m, cmd.ExecuteScalar()); - using (var reader = cmd.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Equal(65536m, reader.GetValue(0)); - Assert.Throws(() => reader.GetInt16(0)); - Assert.Equal(65536, reader.GetInt32(0)); - Assert.Equal(65536L, reader.GetInt64(0)); - } - } + using var reader = cmd.ExecuteReader(); + Assert.True(reader.Read()); + Assert.Equal(65536m, reader.GetValue(0)); + Assert.Throws(() => reader.GetInt16(0)); + Assert.Equal(65536, reader.GetInt32(0)); + Assert.Equal(65536L, reader.GetInt64(0)); } [Fact] @@ -698,19 +629,15 @@ public void SumInts() create table sum_ints(value int unsigned not null); insert into sum_ints(value) values(0), (1), (2), (2147483646), (2147483647);"); - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "select sum(value) from sum_ints"; - Assert.Equal(4294967296m, cmd.ExecuteScalar()); + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "select sum(value) from sum_ints"; + Assert.Equal(4294967296m, cmd.ExecuteScalar()); - using (var reader = cmd.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Equal(4294967296m, reader.GetValue(0)); - Assert.Throws(() => reader.GetInt32(0)); - Assert.Equal(4294967296L, reader.GetInt64(0)); - } - } + using var reader = cmd.ExecuteReader(); + Assert.True(reader.Read()); + Assert.Equal(4294967296m, reader.GetValue(0)); + Assert.Throws(() => reader.GetInt32(0)); + Assert.Equal(4294967296L, reader.GetInt64(0)); } [Fact] @@ -759,47 +686,36 @@ public void UseReaderWithoutDisposing() [InlineData("sqrt(2)", typeof(double))] public void GetFieldType(string value, Type expectedType) { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "select " + value + ";"; - using (var reader = cmd.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Equal(expectedType, reader.GetFieldType(0)); - } - } + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "select " + value + ";"; + + using var reader = cmd.ExecuteReader(); + Assert.True(reader.Read()); + Assert.Equal(expectedType, reader.GetFieldType(0)); } [Fact] public void GetFieldTypeInvalidIndex() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "select 1;"; - using (var reader = cmd.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Throws(() => reader.GetFieldType(1)); - } - } + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "select 1;"; + using var reader = cmd.ExecuteReader(); + Assert.True(reader.Read()); + Assert.Throws(() => reader.GetFieldType(1)); } [Fact] public void GetFieldTypeAfterNextResult() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "select 1;"; - using (var reader = cmd.ExecuteReader()) - { - Assert.False(reader.NextResult()); + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "select 1;"; + using var reader = cmd.ExecuteReader(); + Assert.False(reader.NextResult()); #if BASELINE - Assert.Throws(() => reader.GetFieldType(0)); + Assert.Throws(() => reader.GetFieldType(0)); #else - Assert.Throws(() => reader.GetFieldType(0)); + Assert.Throws(() => reader.GetFieldType(0)); #endif - } - } } [Theory] @@ -820,62 +736,47 @@ public void GetFieldTypeAfterNextResult() [InlineData("sqrt(2)", "DOUBLE")] public void GetDataTypeName(string value, string expectedDataType) { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "select " + value + ";"; - using (var reader = cmd.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Equal(expectedDataType, reader.GetDataTypeName(0)); - } - } + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "select " + value + ";"; + + using var reader = cmd.ExecuteReader(); + Assert.True(reader.Read()); + Assert.Equal(expectedDataType, reader.GetDataTypeName(0)); } [Fact] public void GetDataTypeNameInvalidIndex() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "select 1;"; - using (var reader = cmd.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Throws(() => reader.GetDataTypeName(1)); - } - } + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "select 1;"; + using var reader = cmd.ExecuteReader(); + Assert.True(reader.Read()); + Assert.Throws(() => reader.GetDataTypeName(1)); } [Fact] public void GetDataTypeNameAfterNextResult() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "select 1;"; - using (var reader = cmd.ExecuteReader()) - { - Assert.False(reader.NextResult()); + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "select 1;"; + using var reader = cmd.ExecuteReader(); + Assert.False(reader.NextResult()); #if BASELINE - Assert.Throws(() => reader.GetDataTypeName(0)); + Assert.Throws(() => reader.GetDataTypeName(0)); #else - Assert.Throws(() => reader.GetDataTypeName(0)); + Assert.Throws(() => reader.GetDataTypeName(0)); #endif - } - } } #if !BASELINE [Fact] public void GetColumnSchemaAfterNextResult() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "select 1;"; - using (var reader = cmd.ExecuteReader()) - { - Assert.False(reader.NextResult()); - Assert.Throws(() => reader.GetColumnSchema()); - } - } + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "select 1;"; + using var reader = cmd.ExecuteReader(); + Assert.False(reader.NextResult()); + Assert.Throws(() => reader.GetColumnSchema()); } #endif @@ -887,16 +788,14 @@ private void UseReaderWithoutDisposingThread(object obj) { for (int i = 0; i < 100; i++) { - using (var connection = new MySqlConnection(data.ConnectionStringBuilder.ConnectionString)) - { - connection.Open(); - using (var cmd = connection.CreateCommand()) - { - cmd.CommandText = @"select * from dispose_reader;"; - var reader = cmd.ExecuteReader(); - reader.Read(); - } - } + using var connection = new MySqlConnection(data.ConnectionStringBuilder.ConnectionString); + connection.Open(); + + using var cmd = connection.CreateCommand(); + cmd.CommandText = @"select * from dispose_reader;"; + + var reader = cmd.ExecuteReader(); + reader.Read(); } } catch (Exception ex) @@ -909,40 +808,36 @@ private void UseReaderWithoutDisposingThread(object obj) [Fact] public void InputOutputParameter() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "set @param = 1234"; + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "set @param = 1234"; - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@param", - Direction = ParameterDirection.InputOutput, - Value = 123, - }); + cmd.Parameters.Add(new MySqlParameter + { + ParameterName = "@param", + Direction = ParameterDirection.InputOutput, + Value = 123, + }); - Assert.Throws(() => cmd.ExecuteNonQuery()); + Assert.Throws(() => cmd.ExecuteNonQuery()); - // Issue #231: Assert.Equal(1234, cmd.Parameters["@param"].Value); - } + // Issue #231: Assert.Equal(1234, cmd.Parameters["@param"].Value); } [Fact] public void OutputParameter() { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "set @param = 1234"; + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "set @param = 1234"; - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@param", - Direction = ParameterDirection.Output, - }); + cmd.Parameters.Add(new MySqlParameter + { + ParameterName = "@param", + Direction = ParameterDirection.Output, + }); - Assert.Throws(() => cmd.ExecuteNonQuery()); + Assert.Throws(() => cmd.ExecuteNonQuery()); - // Issue #231: Assert.Equal(1234, cmd.Parameters["@param"].Value); - } + // Issue #231: Assert.Equal(1234, cmd.Parameters["@param"].Value); } [Fact] @@ -956,34 +851,28 @@ public void CharParameter() using (var command = new MySqlCommand("select id from char_test where char1 = @ch;", m_database.Connection)) { command.Parameters.AddWithValue("@ch", '\''); - using (var reader = command.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Equal(1, reader.GetInt32(0)); - Assert.False(reader.Read()); - } + using var reader = command.ExecuteReader(); + Assert.True(reader.Read()); + Assert.Equal(1, reader.GetInt32(0)); + Assert.False(reader.Read()); } using (var command = new MySqlCommand("select id from char_test where char4 = @ch;", m_database.Connection)) { command.Parameters.AddWithValue("@ch", '\\'); - using (var reader = command.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Equal(2, reader.GetInt32(0)); - Assert.False(reader.Read()); - } + using var reader = command.ExecuteReader(); + Assert.True(reader.Read()); + Assert.Equal(2, reader.GetInt32(0)); + Assert.False(reader.Read()); } using (var command = new MySqlCommand("select id from char_test where varchar1 = @ch;", m_database.Connection)) { command.Parameters.AddWithValue("@ch", '"'); - using (var reader = command.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Equal(2, reader.GetInt32(0)); - Assert.False(reader.Read()); - } + using var reader = command.ExecuteReader(); + Assert.True(reader.Read()); + Assert.Equal(2, reader.GetInt32(0)); + Assert.False(reader.Read()); } #if !BASELINE @@ -991,12 +880,10 @@ public void CharParameter() using (var command = new MySqlCommand("select id from char_test where varchar4 = @ch;", m_database.Connection)) { command.Parameters.AddWithValue("@ch", 'Σ'); - using (var reader = command.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Equal(1, reader.GetInt32(0)); - Assert.False(reader.Read()); - } + using var reader = command.ExecuteReader(); + Assert.True(reader.Read()); + Assert.Equal(1, reader.GetInt32(0)); + Assert.False(reader.Read()); } #endif } @@ -1009,17 +896,14 @@ public void EnumParameter() insert into enum_test (id, value) VALUES (1002, 'no'), (1003, 'yes'); "); - using (var command = new MySqlCommand("select * from enum_test where id = @ID;", m_database.Connection)) - { - command.Parameters.AddWithValue("@ID", MySqlErrorCode.No); - using (var reader = command.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Equal((int) MySqlErrorCode.No, reader.GetInt32(0)); - Assert.Equal("no", reader.GetString(1)); - Assert.False(reader.Read()); - } - } + using var command = new MySqlCommand("select * from enum_test where id = @ID;", m_database.Connection); + command.Parameters.AddWithValue("@ID", MySqlErrorCode.No); + + using var reader = command.ExecuteReader(); + Assert.True(reader.Read()); + Assert.Equal((int) MySqlErrorCode.No, reader.GetInt32(0)); + Assert.Equal("no", reader.GetString(1)); + Assert.False(reader.Read()); } [SkippableFact(Baseline = "https://bugs.mysql.com/bug.php?id=84701")] @@ -1030,50 +914,45 @@ public void Int64EnumParameter() insert into long_enum_test (id, value) VALUES (0x7FFFFFFFFFFFFFFF, 1); "); - using (var command = new MySqlCommand("select * from long_enum_test where id = @ID;", m_database.Connection)) - { - command.Parameters.AddWithValue("@ID", TestLongEnum.Value); - using (var reader = command.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Equal(long.MaxValue, reader.GetInt64(0)); - Assert.Equal(1, reader.GetInt32(1)); - Assert.False(reader.Read()); - } - } + using var command = new MySqlCommand("select * from long_enum_test where id = @ID;", m_database.Connection); + command.Parameters.AddWithValue("@ID", TestLongEnum.Value); + + using var reader = command.ExecuteReader(); + Assert.True(reader.Read()); + Assert.Equal(long.MaxValue, reader.GetInt64(0)); + Assert.Equal(1, reader.GetInt32(1)); + Assert.False(reader.Read()); } [Fact] public void ReturnDerivedTypes() { - using (MySqlTransaction transaction = m_database.Connection.BeginTransaction()) - using (MySqlCommand command = m_database.Connection.CreateCommand()) - { - command.Transaction = transaction; - command.CommandText = "select @param + @param2"; + using MySqlTransaction transaction = m_database.Connection.BeginTransaction(); + using MySqlCommand command = m_database.Connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = "select @param + @param2"; - MySqlParameter parameter = command.CreateParameter(); - parameter.ParameterName = "param"; - parameter.Value = 1; - MySqlParameterCollection parameterCollection = command.Parameters; - parameterCollection.Add(parameter); + MySqlParameter parameter = command.CreateParameter(); + parameter.ParameterName = "param"; + parameter.Value = 1; + MySqlParameterCollection parameterCollection = command.Parameters; + parameterCollection.Add(parameter); - MySqlParameter parameter2 = parameterCollection.AddWithValue("param2", 2); + MySqlParameter parameter2 = parameterCollection.AddWithValue("param2", 2); - MySqlParameter parameterB = parameterCollection[0]; - Assert.Same(parameter, parameterB); - MySqlParameter parameter2B = parameterCollection["param2"]; - Assert.Same(parameter2, parameter2B); + MySqlParameter parameterB = parameterCollection[0]; + Assert.Same(parameter, parameterB); + MySqlParameter parameter2B = parameterCollection["param2"]; + Assert.Same(parameter2, parameter2B); - using (MySqlDataReader reader = command.ExecuteReader()) - { - Assert.True(reader.Read()); - Assert.Equal(3L, Convert.ToInt64(reader.GetValue(0))); - Assert.False(reader.Read()); - } - - transaction.Rollback(); + using (MySqlDataReader reader = command.ExecuteReader()) + { + Assert.True(reader.Read()); + Assert.Equal(3L, Convert.ToInt64(reader.GetValue(0))); + Assert.False(reader.Read()); } + + transaction.Rollback(); } [Theory] @@ -1093,21 +972,18 @@ public void HasRows(int[] values, bool[] expecteds) foreach (var value in values) sql += $"select * from has_rows where value = {value};"; - using (var cmd = m_database.Connection.CreateCommand()) + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = sql; + + using var reader = cmd.ExecuteReader(); + for (int i = 0; i < expecteds.Length; i++) { - cmd.CommandText = sql; - using (var reader = cmd.ExecuteReader()) - { - for (int i = 0; i < expecteds.Length; i++) - { - Assert.Equal(expecteds[i], reader.HasRows); - Assert.Equal(expecteds[i], reader.Read()); - Assert.False(reader.Read()); - Assert.Equal(expecteds[i], reader.HasRows); + Assert.Equal(expecteds[i], reader.HasRows); + Assert.Equal(expecteds[i], reader.Read()); + Assert.False(reader.Read()); + Assert.Equal(expecteds[i], reader.HasRows); - Assert.Equal(i != expecteds.Length - 1, reader.NextResult()); - } - } + Assert.Equal(i != expecteds.Length - 1, reader.NextResult()); } } @@ -1118,29 +994,26 @@ public void HasRowsRepeated() create table has_rows(value int not null); insert into has_rows(value) values(1),(2),(3);"); - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "select * from has_rows where value = 1;"; - using (var reader = cmd.ExecuteReader()) - { - Assert.True(reader.HasRows); - Assert.True(reader.HasRows); - Assert.True(reader.HasRows); - Assert.True(reader.HasRows); + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "select * from has_rows where value = 1;"; - Assert.True(reader.Read()); + using var reader = cmd.ExecuteReader(); + Assert.True(reader.HasRows); + Assert.True(reader.HasRows); + Assert.True(reader.HasRows); + Assert.True(reader.HasRows); - Assert.True(reader.HasRows); - Assert.True(reader.HasRows); - Assert.True(reader.HasRows); + Assert.True(reader.Read()); - Assert.False(reader.Read()); + Assert.True(reader.HasRows); + Assert.True(reader.HasRows); + Assert.True(reader.HasRows); - Assert.True(reader.HasRows); - Assert.True(reader.HasRows); - Assert.True(reader.HasRows); - } - } + Assert.False(reader.Read()); + + Assert.True(reader.HasRows); + Assert.True(reader.HasRows); + Assert.True(reader.HasRows); } #if !NETCOREAPP1_1_2 @@ -1185,21 +1058,17 @@ public void CommandBehaviorCloseConnection() [Fact] public void CommandBehaviorSingleRow() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - { - connection.Open(); - connection.Execute(@"drop table if exists command_behavior_single_row; + using var connection = new MySqlConnection(AppConfig.ConnectionString); + connection.Open(); + connection.Execute(@"drop table if exists command_behavior_single_row; create table command_behavior_single_row(id integer not null primary key); insert into command_behavior_single_row(id) values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10);"); - using (var cmd = new MySqlCommand("SELECT id FROM command_behavior_single_row ORDER BY id;", connection)) - using (var reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) - { - Assert.True(reader.Read()); - Assert.Equal(1, reader.GetInt32(0)); - Assert.False(reader.Read()); - } - } + using var cmd = new MySqlCommand("SELECT id FROM command_behavior_single_row ORDER BY id;", connection); + using var reader = cmd.ExecuteReader(CommandBehavior.SingleRow); + Assert.True(reader.Read()); + Assert.Equal(1, reader.GetInt32(0)); + Assert.False(reader.Read()); } class BoolTest diff --git a/tests/SideBySide/SideBySide.csproj b/tests/SideBySide/SideBySide.csproj index 96973289b..1403a8f13 100644 --- a/tests/SideBySide/SideBySide.csproj +++ b/tests/SideBySide/SideBySide.csproj @@ -1,4 +1,4 @@ - + net452;net461;net472;netcoreapp1.1.2;netcoreapp2.0;netcoreapp2.1;netcoreapp3.0 @@ -21,6 +21,7 @@ true true 64 + 8.0 diff --git a/tests/SideBySide/SslTests.cs b/tests/SideBySide/SslTests.cs index 1f5688284..4ccbac123 100644 --- a/tests/SideBySide/SslTests.cs +++ b/tests/SideBySide/SslTests.cs @@ -22,20 +22,16 @@ public async Task ConnectSslPreferred() csb.SslMode = MySqlSslMode.Preferred; csb.CertificateFile = null; csb.CertificatePassword = null; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - using (var cmd = connection.CreateCommand()) - { - await connection.OpenAsync(); - Assert.True(connection.SslIsEncrypted); - Assert.True(connection.SslIsSigned); - Assert.True(connection.SslIsAuthenticated); - Assert.False(connection.SslIsMutuallyAuthenticated); - cmd.CommandText = "SHOW SESSION STATUS LIKE 'Ssl_version'"; - var sslVersion = (string)await cmd.ExecuteScalarAsync(); - Assert.False(string.IsNullOrWhiteSpace(sslVersion)); - } - } + using var connection = new MySqlConnection(csb.ConnectionString); + using var cmd = connection.CreateCommand(); + await connection.OpenAsync(); + Assert.True(connection.SslIsEncrypted); + Assert.True(connection.SslIsSigned); + Assert.True(connection.SslIsAuthenticated); + Assert.False(connection.SslIsMutuallyAuthenticated); + cmd.CommandText = "SHOW SESSION STATUS LIKE 'Ssl_version'"; + var sslVersion = (string) await cmd.ExecuteScalarAsync(); + Assert.False(string.IsNullOrWhiteSpace(sslVersion)); } #endif @@ -82,22 +78,18 @@ public async Task ConnectSslClientCertificatePem(string certFile, string keyFile private async Task DoTestSsl(string connectionString) { - using (var connection = new MySqlConnection(connectionString)) - { - using (var cmd = connection.CreateCommand()) - { - await connection.OpenAsync(); + using var connection = new MySqlConnection(connectionString); + using var cmd = connection.CreateCommand(); + await connection.OpenAsync(); #if !BASELINE - Assert.True(connection.SslIsEncrypted); - Assert.True(connection.SslIsSigned); - Assert.True(connection.SslIsAuthenticated); - Assert.True(connection.SslIsMutuallyAuthenticated); + Assert.True(connection.SslIsEncrypted); + Assert.True(connection.SslIsSigned); + Assert.True(connection.SslIsAuthenticated); + Assert.True(connection.SslIsMutuallyAuthenticated); #endif - cmd.CommandText = "SHOW SESSION STATUS LIKE 'Ssl_version'"; - var sslVersion = (string) await cmd.ExecuteScalarAsync(); - Assert.False(string.IsNullOrWhiteSpace(sslVersion)); - } - } + cmd.CommandText = "SHOW SESSION STATUS LIKE 'Ssl_version'"; + var sslVersion = (string) await cmd.ExecuteScalarAsync(); + Assert.False(string.IsNullOrWhiteSpace(sslVersion)); } [SkippableTheory(ConfigSettings.RequiresSsl | ConfigSettings.KnownClientCertificate)] @@ -111,25 +103,23 @@ public async Task ConnectSslClientCertificateFromCertificateStore(string certFil store.Add(certificate); var csb = AppConfig.CreateConnectionStringBuilder(); - + csb.CertificateStoreLocation = storeLocation; csb.CertificateThumbprint = thumbprint; using (var connection = new MySqlConnection(csb.ConnectionString)) { - using (var cmd = connection.CreateCommand()) - { - await connection.OpenAsync(); + using var cmd = connection.CreateCommand(); + await connection.OpenAsync(); #if !BASELINE - Assert.True(connection.SslIsEncrypted); - Assert.True(connection.SslIsSigned); - Assert.True(connection.SslIsAuthenticated); - Assert.True(connection.SslIsMutuallyAuthenticated); + Assert.True(connection.SslIsEncrypted); + Assert.True(connection.SslIsSigned); + Assert.True(connection.SslIsAuthenticated); + Assert.True(connection.SslIsMutuallyAuthenticated); #endif - cmd.CommandText = "SHOW SESSION STATUS LIKE 'Ssl_version'"; - var sslVersion = (string) await cmd.ExecuteScalarAsync(); - Assert.False(string.IsNullOrWhiteSpace(sslVersion)); - } + cmd.CommandText = "SHOW SESSION STATUS LIKE 'Ssl_version'"; + var sslVersion = (string) await cmd.ExecuteScalarAsync(); + Assert.False(string.IsNullOrWhiteSpace(sslVersion)); } // Remove the certificate from store @@ -142,10 +132,8 @@ public async Task ConnectSslClientCertificateNoPrivateKey() var csb = AppConfig.CreateConnectionStringBuilder(); csb.CertificateFile = Path.Combine(AppConfig.CertsPath, "ssl-client-cert.pem"); csb.SslMode = MySqlSslMode.Required; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - await Assert.ThrowsAsync(async () => await connection.OpenAsync()); - } + using var connection = new MySqlConnection(csb.ConnectionString); + await Assert.ThrowsAsync(async () => await connection.OpenAsync()); } [SkippableFact(ServerFeatures.KnownCertificateAuthority, ConfigSettings.RequiresSsl)] @@ -154,10 +142,8 @@ public async Task ConnectSslBadClientCertificate() var csb = AppConfig.CreateConnectionStringBuilder(); csb.CertificateFile = Path.Combine(AppConfig.CertsPath, "non-ca-client.pfx"); csb.CertificatePassword = ""; - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - await Assert.ThrowsAsync(async () => await connection.OpenAsync()); - } + using var connection = new MySqlConnection(csb.ConnectionString); + await Assert.ThrowsAsync(async () => await connection.OpenAsync()); } [SkippableFact(ServerFeatures.KnownCertificateAuthority, ConfigSettings.RequiresSsl)] @@ -172,38 +158,32 @@ public async Task ConnectSslBadCaCertificate() #endif csb.SslMode = MySqlSslMode.VerifyCA; csb.SslCa = Path.Combine(AppConfig.CertsPath, "non-ca-client-cert.pem"); - using (var connection = new MySqlConnection(csb.ConnectionString)) - { - await Assert.ThrowsAsync(async () => await connection.OpenAsync()); - } + using var connection = new MySqlConnection(csb.ConnectionString); + await Assert.ThrowsAsync(async () => await connection.OpenAsync()); } [SkippableFact(ConfigSettings.RequiresSsl)] public async Task ConnectSslTlsVersion() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - { - await connection.OpenAsync(); + using var connection = new MySqlConnection(AppConfig.ConnectionString); + await connection.OpenAsync(); #if BASELINE - var expectedProtocol = AppConfig.SupportedFeatures.HasFlag(ServerFeatures.Tls11) ? SslProtocols.Tls11 : SslProtocols.Tls; + var expectedProtocol = AppConfig.SupportedFeatures.HasFlag(ServerFeatures.Tls11) ? SslProtocols.Tls11 : SslProtocols.Tls; #else - var expectedProtocol = AppConfig.SupportedFeatures.HasFlag(ServerFeatures.Tls12) ? SslProtocols.Tls12 : - AppConfig.SupportedFeatures.HasFlag(ServerFeatures.Tls11) ? SslProtocols.Tls11 : - SslProtocols.Tls; + var expectedProtocol = AppConfig.SupportedFeatures.HasFlag(ServerFeatures.Tls12) ? SslProtocols.Tls12 : + AppConfig.SupportedFeatures.HasFlag(ServerFeatures.Tls11) ? SslProtocols.Tls11 : + SslProtocols.Tls; #endif - var expectedProtocolString = expectedProtocol == SslProtocols.Tls12 ? "TLSv1.2" : - expectedProtocol == SslProtocols.Tls11 ? "TLSv1.1" : "TLSv1"; + var expectedProtocolString = expectedProtocol == SslProtocols.Tls12 ? "TLSv1.2" : + expectedProtocol == SslProtocols.Tls11 ? "TLSv1.1" : "TLSv1"; #if !BASELINE - Assert.Equal(expectedProtocol, connection.SslProtocol); + Assert.Equal(expectedProtocol, connection.SslProtocol); #endif - using (var cmd = new MySqlCommand("show status like 'Ssl_version';", connection)) - using (var reader = await cmd.ExecuteReaderAsync()) - { - Assert.True(reader.Read()); - Assert.Equal(expectedProtocolString, reader.GetString(1)); - } - } + using var cmd = new MySqlCommand("show status like 'Ssl_version';", connection); + using var reader = await cmd.ExecuteReaderAsync(); + Assert.True(reader.Read()); + Assert.Equal(expectedProtocolString, reader.GetString(1)); } readonly DatabaseFixture m_database; diff --git a/tests/SideBySide/StoredProcedureTests.cs b/tests/SideBySide/StoredProcedureTests.cs index adefab44e..57de045a1 100644 --- a/tests/SideBySide/StoredProcedureTests.cs +++ b/tests/SideBySide/StoredProcedureTests.cs @@ -24,80 +24,73 @@ public StoredProcedureTests(StoredProcedureFixture database) [InlineData("PROCEDURE", "Reader")] public async Task StoredProcedureEcho(string procedureType, string executorType) { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "echo" + (procedureType == "FUNCTION" ? "f" : "p"); - cmd.CommandType = CommandType.StoredProcedure; + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "echo" + (procedureType == "FUNCTION" ? "f" : "p"); + cmd.CommandType = CommandType.StoredProcedure; + cmd.Parameters.Add(new MySqlParameter + { + ParameterName = "@name", + DbType = DbType.String, + Direction = ParameterDirection.Input, + Value = "hello", + }); + + // we make the assumption that Stored Procedures with ParameterDirection.ReturnValue are functions + if (procedureType == "FUNCTION") + { cmd.Parameters.Add(new MySqlParameter { - ParameterName = "@name", + ParameterName = "@result", DbType = DbType.String, - Direction = ParameterDirection.Input, - Value = "hello", + Direction = ParameterDirection.ReturnValue, }); - - // we make the assumption that Stored Procedures with ParameterDirection.ReturnValue are functions - if (procedureType == "FUNCTION") - { - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@result", - DbType = DbType.String, - Direction = ParameterDirection.ReturnValue, - }); - } - - var result = await ExecuteCommandAsync(cmd, executorType); - if (procedureType == "PROCEDURE" && executorType != "NonQuery") - Assert.Equal(cmd.Parameters["@name"].Value, result); - if (procedureType == "FUNCTION") - Assert.Equal(cmd.Parameters["@name"].Value, cmd.Parameters["@result"].Value); } + + var result = await ExecuteCommandAsync(cmd, executorType); + if (procedureType == "PROCEDURE" && executorType != "NonQuery") + Assert.Equal(cmd.Parameters["@name"].Value, result); + if (procedureType == "FUNCTION") + Assert.Equal(cmd.Parameters["@name"].Value, cmd.Parameters["@result"].Value); } [Fact] public void CallFailingFunction() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - using (var command = connection.CreateCommand()) - { - connection.Open(); + using var connection = new MySqlConnection(AppConfig.ConnectionString); + using var command = connection.CreateCommand(); + connection.Open(); - command.CommandType = CommandType.StoredProcedure; - command.CommandText = "failing_function"; + command.CommandType = CommandType.StoredProcedure; + command.CommandText = "failing_function"; - var returnParameter = command.CreateParameter(); - returnParameter.DbType = DbType.Int32; - returnParameter.Direction = ParameterDirection.ReturnValue; - command.Parameters.Add(returnParameter); + var returnParameter = command.CreateParameter(); + returnParameter.DbType = DbType.Int32; + returnParameter.Direction = ParameterDirection.ReturnValue; + command.Parameters.Add(returnParameter); - Assert.Throws(() => command.ExecuteNonQuery()); - } + Assert.Throws(() => command.ExecuteNonQuery()); } [Fact] public void CallFailingFunctionInTransaction() { - using (var connection = new MySqlConnection(AppConfig.ConnectionString)) - { - connection.Open(); - using (var transaction = connection.BeginTransaction()) - using (var command = connection.CreateCommand()) - { - command.Transaction = transaction; - command.CommandType = CommandType.StoredProcedure; - command.CommandText = "failing_function"; - - var returnParameter = command.CreateParameter(); - returnParameter.DbType = DbType.Int32; - returnParameter.Direction = ParameterDirection.ReturnValue; - command.Parameters.Add(returnParameter); - - Assert.Throws(() => command.ExecuteNonQuery()); - transaction.Commit(); - } - } + using var connection = new MySqlConnection(AppConfig.ConnectionString); + connection.Open(); + + using var transaction = connection.BeginTransaction(); + using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandType = CommandType.StoredProcedure; + command.CommandText = "failing_function"; + + var returnParameter = command.CreateParameter(); + returnParameter.DbType = DbType.Int32; + returnParameter.Direction = ParameterDirection.ReturnValue; + command.Parameters.Add(returnParameter); + + Assert.Throws(() => command.ExecuteNonQuery()); + transaction.Commit(); } [SkippableTheory(ServerFeatures.StoredProcedures)] @@ -105,88 +98,80 @@ public void CallFailingFunctionInTransaction() [InlineData("PROCEDURE")] public async Task StoredProcedureEchoException(string procedureType) { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "echo" + (procedureType == "FUNCTION" ? "f" : "p"); - cmd.CommandType = CommandType.StoredProcedure; + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "echo" + (procedureType == "FUNCTION" ? "f" : "p"); + cmd.CommandType = CommandType.StoredProcedure; - if (procedureType == "FUNCTION") - await Assert.ThrowsAsync(async () => await cmd.ExecuteNonQueryAsync()); - else - await Assert.ThrowsAsync(async () => await cmd.ExecuteNonQueryAsync()); - } + if (procedureType == "FUNCTION") + await Assert.ThrowsAsync(async () => await cmd.ExecuteNonQueryAsync()); + else + await Assert.ThrowsAsync(async () => await cmd.ExecuteNonQueryAsync()); } [Fact] public async Task StoredProcedureNoResultSet() { - using (var cmd = m_database.Connection.CreateCommand()) + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "out_string"; + cmd.CommandType = CommandType.StoredProcedure; + cmd.Parameters.Add(new MySqlParameter { - cmd.CommandText = "out_string"; - cmd.CommandType = CommandType.StoredProcedure; - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@value", - DbType = DbType.String, - Direction = ParameterDirection.Output, - }); + ParameterName = "@value", + DbType = DbType.String, + Direction = ParameterDirection.Output, + }); - using (var reader = await cmd.ExecuteReaderAsync()) - { - Assert.False(await reader.ReadAsync()); - Assert.False(await reader.NextResultAsync()); - } - - Assert.Equal("test value", cmd.Parameters[0].Value); + using (var reader = await cmd.ExecuteReaderAsync()) + { + Assert.False(await reader.ReadAsync()); + Assert.False(await reader.NextResultAsync()); } + + Assert.Equal("test value", cmd.Parameters[0].Value); } [Fact] public async Task StoredProcedureOutIncorrectType() { - using (var cmd = m_database.Connection.CreateCommand()) + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "out_string"; + cmd.CommandType = CommandType.StoredProcedure; + cmd.Parameters.Add(new MySqlParameter { - cmd.CommandText = "out_string"; - cmd.CommandType = CommandType.StoredProcedure; - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@value", - DbType = DbType.Double, - Direction = ParameterDirection.Output, - }); + ParameterName = "@value", + DbType = DbType.Double, + Direction = ParameterDirection.Output, + }); - await Assert.ThrowsAsync(cmd.ExecuteNonQueryAsync); - } + await Assert.ThrowsAsync(cmd.ExecuteNonQueryAsync); } [Fact] public async Task StoredProcedureReturnsNull() { - using (var cmd = m_database.Connection.CreateCommand()) + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "out_null"; + cmd.CommandType = CommandType.StoredProcedure; + cmd.Parameters.Add(new MySqlParameter { - cmd.CommandText = "out_null"; - cmd.CommandType = CommandType.StoredProcedure; - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@string_value", - DbType = DbType.String, - Direction = ParameterDirection.Output, - IsNullable = true, - Value = "non null", - }); - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@int_value", - DbType = DbType.Int32, - Direction = ParameterDirection.Output, - IsNullable = true, - Value = "123", - }); - await cmd.ExecuteNonQueryAsync(); - - Assert.Equal(DBNull.Value, cmd.Parameters["@string_value"].Value); - Assert.Equal(DBNull.Value, cmd.Parameters["@int_value"].Value); - } + ParameterName = "@string_value", + DbType = DbType.String, + Direction = ParameterDirection.Output, + IsNullable = true, + Value = "non null", + }); + cmd.Parameters.Add(new MySqlParameter + { + ParameterName = "@int_value", + DbType = DbType.Int32, + Direction = ParameterDirection.Output, + IsNullable = true, + Value = "123", + }); + await cmd.ExecuteNonQueryAsync(); + + Assert.Equal(DBNull.Value, cmd.Parameters["@string_value"].Value); + Assert.Equal(DBNull.Value, cmd.Parameters["@int_value"].Value); } [Theory] @@ -195,64 +180,62 @@ public async Task StoredProcedureReturnsNull() [InlineData("Reader")] public async Task StoredProcedureCircle(string executorType) { - using (var cmd = m_database.Connection.CreateCommand()) + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "circle"; + cmd.CommandType = CommandType.StoredProcedure; + cmd.Parameters.Add(new MySqlParameter { - cmd.CommandText = "circle"; - cmd.CommandType = CommandType.StoredProcedure; - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@radius", - DbType = DbType.Double, - Direction = ParameterDirection.Input, - Value = 1.0, - }); - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@height", - DbType = DbType.Double, - Direction = ParameterDirection.Input, - Value = 2.0, - }); - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@name", - DbType = DbType.String, - Direction = ParameterDirection.Input, - Value = "awesome", - }); - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@diameter", - DbType = DbType.Double, - Direction = ParameterDirection.Output, - }); - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@circumference", - DbType = DbType.Double, - Direction = ParameterDirection.Output, - }); - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@area", - DbType = DbType.Double, - Direction = ParameterDirection.Output, - }); - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@volume", - DbType = DbType.Double, - Direction = ParameterDirection.Output, - }); - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@shape", - DbType = DbType.String, - Direction = ParameterDirection.Output, - }); + ParameterName = "@radius", + DbType = DbType.Double, + Direction = ParameterDirection.Input, + Value = 1.0, + }); + cmd.Parameters.Add(new MySqlParameter + { + ParameterName = "@height", + DbType = DbType.Double, + Direction = ParameterDirection.Input, + Value = 2.0, + }); + cmd.Parameters.Add(new MySqlParameter + { + ParameterName = "@name", + DbType = DbType.String, + Direction = ParameterDirection.Input, + Value = "awesome", + }); + cmd.Parameters.Add(new MySqlParameter + { + ParameterName = "@diameter", + DbType = DbType.Double, + Direction = ParameterDirection.Output, + }); + cmd.Parameters.Add(new MySqlParameter + { + ParameterName = "@circumference", + DbType = DbType.Double, + Direction = ParameterDirection.Output, + }); + cmd.Parameters.Add(new MySqlParameter + { + ParameterName = "@area", + DbType = DbType.Double, + Direction = ParameterDirection.Output, + }); + cmd.Parameters.Add(new MySqlParameter + { + ParameterName = "@volume", + DbType = DbType.Double, + Direction = ParameterDirection.Output, + }); + cmd.Parameters.Add(new MySqlParameter + { + ParameterName = "@shape", + DbType = DbType.String, + Direction = ParameterDirection.Output, + }); - await CircleAssertions(cmd, executorType); - } + await CircleAssertions(cmd, executorType); } [SkippableTheory(ServerFeatures.StoredProcedures)] @@ -265,102 +248,100 @@ public async Task StoredProcedureCircleCached(string executorType) // remove return types // remove directions (MySqlConnector only, MySql.Data does not fix these up) // CachedProcedure class should fix everything up based on parameter names - using (var cmd = m_database.Connection.CreateCommand()) + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "circle"; + cmd.CommandType = CommandType.StoredProcedure; + cmd.Parameters.Add(new MySqlParameter { - cmd.CommandText = "circle"; - cmd.CommandType = CommandType.StoredProcedure; - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@name", - Value = "awesome", + ParameterName = "@name", + Value = "awesome", #if BASELINE - Direction = ParameterDirection.Input, + Direction = ParameterDirection.Input, #endif - }); - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@radius", - Value = 1.5, + }); + cmd.Parameters.Add(new MySqlParameter + { + ParameterName = "@radius", + Value = 1.5, #if BASELINE - Direction = ParameterDirection.Input, + Direction = ParameterDirection.Input, #endif - }); - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@shape", + }); + cmd.Parameters.Add(new MySqlParameter + { + ParameterName = "@shape", #if BASELINE - Direction = ParameterDirection.Output, + Direction = ParameterDirection.Output, #endif - }); - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@height", - Value = 2.0, + }); + cmd.Parameters.Add(new MySqlParameter + { + ParameterName = "@height", + Value = 2.0, #if BASELINE - Direction = ParameterDirection.Input, + Direction = ParameterDirection.Input, #endif - }); - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@diameter", + }); + cmd.Parameters.Add(new MySqlParameter + { + ParameterName = "@diameter", #if BASELINE - Direction = ParameterDirection.Output, + Direction = ParameterDirection.Output, #endif - }); - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@area", + }); + cmd.Parameters.Add(new MySqlParameter + { + ParameterName = "@area", #if BASELINE - Direction = ParameterDirection.Output, + Direction = ParameterDirection.Output, #endif - }); - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@volume", + }); + cmd.Parameters.Add(new MySqlParameter + { + ParameterName = "@volume", #if BASELINE - Direction = ParameterDirection.Output, + Direction = ParameterDirection.Output, #endif - }); - cmd.Parameters.Add(new MySqlParameter - { - ParameterName = "@circumference", + }); + cmd.Parameters.Add(new MySqlParameter + { + ParameterName = "@circumference", #if BASELINE - Direction = ParameterDirection.Output, + Direction = ParameterDirection.Output, #endif - }); + }); - await CircleAssertions(cmd, executorType); - } + await CircleAssertions(cmd, executorType); } private async Task CircleAssertions(DbCommand cmd, string executorType) { var result = await ExecuteCommandAsync(cmd, executorType); if (executorType != "NonQuery") - Assert.Equal((string)cmd.Parameters["@name"].Value + (string)cmd.Parameters["@shape"].Value, result); + Assert.Equal((string) cmd.Parameters["@name"].Value + (string) cmd.Parameters["@shape"].Value, result); - Assert.Equal(2 * (double)cmd.Parameters["@radius"].Value, cmd.Parameters["@diameter"].Value); - Assert.Equal(2.0 * Math.PI * (double)cmd.Parameters["@radius"].Value, cmd.Parameters["@circumference"].Value); - Assert.Equal(Math.PI * Math.Pow((double)cmd.Parameters["@radius"].Value, 2), cmd.Parameters["@area"].Value); - Assert.Equal((double)cmd.Parameters["@area"].Value * (double)cmd.Parameters["@height"].Value, cmd.Parameters["@volume"].Value); + Assert.Equal(2 * (double) cmd.Parameters["@radius"].Value, cmd.Parameters["@diameter"].Value); + Assert.Equal(2.0 * Math.PI * (double) cmd.Parameters["@radius"].Value, cmd.Parameters["@circumference"].Value); + Assert.Equal(Math.PI * Math.Pow((double) cmd.Parameters["@radius"].Value, 2), cmd.Parameters["@area"].Value); + Assert.Equal((double) cmd.Parameters["@area"].Value * (double) cmd.Parameters["@height"].Value, cmd.Parameters["@volume"].Value); } private async Task ExecuteCommandAsync(DbCommand cmd, string executorType) { switch (executorType) { - case "NonQuery": - await cmd.ExecuteNonQueryAsync(); + case "NonQuery": + await cmd.ExecuteNonQueryAsync(); + return null; + case "Scalar": + return await cmd.ExecuteScalarAsync(); + default: + using (var reader = await cmd.ExecuteReaderAsync()) + { + if (await reader.ReadAsync()) + return reader.GetValue(0); return null; - case "Scalar": - return await cmd.ExecuteScalarAsync(); - default: - using (var reader = await cmd.ExecuteReaderAsync()) - { - if (await reader.ReadAsync()) - return reader.GetValue(0); - return null; - } + } } } @@ -370,21 +351,18 @@ private async Task ExecuteCommandAsync(DbCommand cmd, string executorTyp [InlineData("?factor")] public async Task MultipleRows(string paramaterName) { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "number_multiples"; - cmd.CommandType = CommandType.StoredProcedure; - cmd.Parameters.Add(new MySqlParameter { ParameterName = paramaterName, Value = 3 }); - using (var reader = await cmd.ExecuteReaderAsync()) - { - Assert.True(await reader.ReadAsync()); - Assert.Equal("six", reader.GetString(0)); - Assert.True(await reader.ReadAsync()); - Assert.Equal("three", reader.GetString(0)); - Assert.False(await reader.ReadAsync()); - Assert.False(await reader.NextResultAsync()); - } - } + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "number_multiples"; + cmd.CommandType = CommandType.StoredProcedure; + cmd.Parameters.Add(new MySqlParameter { ParameterName = paramaterName, Value = 3 }); + + using var reader = await cmd.ExecuteReaderAsync(); + Assert.True(await reader.ReadAsync()); + Assert.Equal("six", reader.GetString(0)); + Assert.True(await reader.ReadAsync()); + Assert.Equal("three", reader.GetString(0)); + Assert.False(await reader.ReadAsync()); + Assert.False(await reader.NextResultAsync()); } [Theory] @@ -393,32 +371,29 @@ public async Task MultipleRows(string paramaterName) [InlineData(8, new[] { "five", "four", "one", "seven", "six", "three", "two" }, new string[0])] public async Task MultipleResultSets(int pivot, string[] firstResultSet, string[] secondResultSet) { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = "multiple_result_sets"; - cmd.CommandType = CommandType.StoredProcedure; - cmd.Parameters.Add(new MySqlParameter { ParameterName = "@pivot", Value = pivot }); - using (var reader = await cmd.ExecuteReaderAsync()) - { - foreach (var result in firstResultSet) - { - Assert.True(await reader.ReadAsync()); - Assert.Equal(result, reader.GetString(0)); - } - Assert.False(await reader.ReadAsync()); + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = "multiple_result_sets"; + cmd.CommandType = CommandType.StoredProcedure; + cmd.Parameters.Add(new MySqlParameter { ParameterName = "@pivot", Value = pivot }); - Assert.True(await reader.NextResultAsync()); + using var reader = await cmd.ExecuteReaderAsync(); + foreach (var result in firstResultSet) + { + Assert.True(await reader.ReadAsync()); + Assert.Equal(result, reader.GetString(0)); + } + Assert.False(await reader.ReadAsync()); - foreach (var result in secondResultSet) - { - Assert.True(await reader.ReadAsync()); - Assert.Equal(result, reader.GetString(0)); - } - Assert.False(await reader.ReadAsync()); + Assert.True(await reader.NextResultAsync()); - Assert.False(await reader.NextResultAsync()); - } + foreach (var result in secondResultSet) + { + Assert.True(await reader.ReadAsync()); + Assert.Equal(result, reader.GetString(0)); } + Assert.False(await reader.ReadAsync()); + + Assert.False(await reader.NextResultAsync()); } [Fact] @@ -433,24 +408,23 @@ public async Task InOut() }; while ((int) parameter.Value < 8) { - using (var cmd = m_database.Connection.CreateCommand()) + using var cmd = m_database.Connection.CreateCommand(); + var nextValue = (int) parameter.Value + 1; + cmd.CommandText = "number_lister"; + cmd.CommandType = CommandType.StoredProcedure; + cmd.Parameters.Add(parameter); + cmd.Prepare(); + using (var reader = await cmd.ExecuteReaderAsync()) { - var nextValue = (int) parameter.Value + 1; - cmd.CommandText = "number_lister"; - cmd.CommandType = CommandType.StoredProcedure; - cmd.Parameters.Add(parameter); - using (var reader = await cmd.ExecuteReaderAsync()) + for (var i = 0; i < (int) parameter.Value; i++) { - for (var i = 0; i < (int) parameter.Value; i++) - { - Assert.True(await reader.ReadAsync()); - Assert.Equal(i + 1, reader.GetInt32(0)); - Assert.True(reader.GetString(1).Length > 0); - } - await reader.NextResultAsync(); + Assert.True(await reader.ReadAsync()); + Assert.Equal(i + 1, reader.GetInt32(0)); + Assert.True(reader.GetString(1).Length > 0); } - Assert.Equal(nextValue, parameter.Value); + await reader.NextResultAsync(); } + Assert.Equal(nextValue, parameter.Value); } } @@ -459,92 +433,79 @@ public async Task InOut() [InlineData(true)] public async Task DottedName(bool useDatabaseName) { - using (var cmd = m_database.Connection.CreateCommand()) - { - cmd.CommandText = (useDatabaseName ? $"{m_database.Connection.Database}." : "") + "`dotted.name`"; - cmd.CommandType = CommandType.StoredProcedure; - using (var reader = await cmd.ExecuteReaderAsync()) - { - Assert.True(await reader.ReadAsync()); - Assert.Equal(1, reader.GetInt32(0)); - Assert.Equal(2, reader.GetInt32(1)); - Assert.Equal(3, reader.GetInt32(2)); - Assert.False(await reader.ReadAsync()); - Assert.False(await reader.NextResultAsync()); - } - } + using var cmd = m_database.Connection.CreateCommand(); + cmd.CommandText = (useDatabaseName ? $"{m_database.Connection.Database}." : "") + "`dotted.name`"; + cmd.CommandType = CommandType.StoredProcedure; + + using var reader = await cmd.ExecuteReaderAsync(); + Assert.True(await reader.ReadAsync()); + Assert.Equal(1, reader.GetInt32(0)); + Assert.Equal(2, reader.GetInt32(1)); + Assert.Equal(3, reader.GetInt32(2)); + Assert.False(await reader.ReadAsync()); + Assert.False(await reader.NextResultAsync()); } [Fact] public void DeriveParametersCircle() { - using (var cmd = new MySqlCommand("circle", m_database.Connection)) - { - cmd.CommandType = CommandType.StoredProcedure; - MySqlCommandBuilder.DeriveParameters(cmd); - - Assert.Collection(cmd.Parameters.Cast(), - AssertParameter("@radius", ParameterDirection.Input, MySqlDbType.Double), - AssertParameter("@height", ParameterDirection.Input, MySqlDbType.Double), - AssertParameter("@name", ParameterDirection.Input, MySqlDbType.VarChar), - AssertParameter("@diameter", ParameterDirection.Output, MySqlDbType.Double), - AssertParameter("@circumference", ParameterDirection.Output, MySqlDbType.Double), - AssertParameter("@area", ParameterDirection.Output, MySqlDbType.Double), - AssertParameter("@volume", ParameterDirection.Output, MySqlDbType.Double), - AssertParameter("@shape", ParameterDirection.Output, MySqlDbType.VarChar)); - } + using var cmd = new MySqlCommand("circle", m_database.Connection); + cmd.CommandType = CommandType.StoredProcedure; + MySqlCommandBuilder.DeriveParameters(cmd); + + Assert.Collection(cmd.Parameters.Cast(), + AssertParameter("@radius", ParameterDirection.Input, MySqlDbType.Double), + AssertParameter("@height", ParameterDirection.Input, MySqlDbType.Double), + AssertParameter("@name", ParameterDirection.Input, MySqlDbType.VarChar), + AssertParameter("@diameter", ParameterDirection.Output, MySqlDbType.Double), + AssertParameter("@circumference", ParameterDirection.Output, MySqlDbType.Double), + AssertParameter("@area", ParameterDirection.Output, MySqlDbType.Double), + AssertParameter("@volume", ParameterDirection.Output, MySqlDbType.Double), + AssertParameter("@shape", ParameterDirection.Output, MySqlDbType.VarChar)); } [Fact] public void DeriveParametersNumberLister() { - using (var cmd = new MySqlCommand("number_lister", m_database.Connection)) - { - cmd.CommandType = CommandType.StoredProcedure; - MySqlCommandBuilder.DeriveParameters(cmd); + using var cmd = new MySqlCommand("number_lister", m_database.Connection); + cmd.CommandType = CommandType.StoredProcedure; + MySqlCommandBuilder.DeriveParameters(cmd); - Assert.Collection(cmd.Parameters.Cast(), - AssertParameter("@high", ParameterDirection.InputOutput, MySqlDbType.Int32)); - } + Assert.Collection(cmd.Parameters.Cast(), + AssertParameter("@high", ParameterDirection.InputOutput, MySqlDbType.Int32)); } [Fact] public void DeriveParametersRemovesExisting() { - using (var cmd = new MySqlCommand("number_lister", m_database.Connection)) - { - cmd.CommandType = CommandType.StoredProcedure; - cmd.Parameters.AddWithValue("test1", 1); - cmd.Parameters.AddWithValue("test2", 2); - cmd.Parameters.AddWithValue("test3", 3); - - MySqlCommandBuilder.DeriveParameters(cmd); - Assert.Collection(cmd.Parameters.Cast(), - AssertParameter("@high", ParameterDirection.InputOutput, MySqlDbType.Int32)); - } + using var cmd = new MySqlCommand("number_lister", m_database.Connection); + cmd.CommandType = CommandType.StoredProcedure; + cmd.Parameters.AddWithValue("test1", 1); + cmd.Parameters.AddWithValue("test2", 2); + cmd.Parameters.AddWithValue("test3", 3); + + MySqlCommandBuilder.DeriveParameters(cmd); + Assert.Collection(cmd.Parameters.Cast(), + AssertParameter("@high", ParameterDirection.InputOutput, MySqlDbType.Int32)); } [Fact] public void DeriveParametersDoesNotExist() { - using (var cmd = new MySqlCommand("xx_does_not_exist", m_database.Connection)) - { - cmd.CommandType = CommandType.StoredProcedure; - Assert.Throws(() => MySqlCommandBuilder.DeriveParameters(cmd)); - } + using var cmd = new MySqlCommand("xx_does_not_exist", m_database.Connection); + cmd.CommandType = CommandType.StoredProcedure; + Assert.Throws(() => MySqlCommandBuilder.DeriveParameters(cmd)); } [SkippableFact(ServerFeatures.Json, Baseline = "https://bugs.mysql.com/bug.php?id=89335")] public void DeriveParametersSetJson() { - using (var cmd = new MySqlCommand("SetJson", m_database.Connection)) - { - cmd.CommandType = CommandType.StoredProcedure; - MySqlCommandBuilder.DeriveParameters(cmd); + using var cmd = new MySqlCommand("SetJson", m_database.Connection); + cmd.CommandType = CommandType.StoredProcedure; + MySqlCommandBuilder.DeriveParameters(cmd); - Assert.Collection(cmd.Parameters.Cast(), - AssertParameter("@vJson", ParameterDirection.Input, MySqlDbType.JSON)); - } + Assert.Collection(cmd.Parameters.Cast(), + AssertParameter("@vJson", ParameterDirection.Input, MySqlDbType.JSON)); } private static Action AssertParameter(string name, ParameterDirection direction, MySqlDbType mySqlDbType) @@ -583,27 +544,23 @@ public void ProceduresSchema(string procedureName, string procedureType, string [Fact] public void CallNonExistentStoredProcedure() { - using (var command = new MySqlCommand("NonExistentStoredProcedure", m_database.Connection)) - { - command.CommandType = CommandType.StoredProcedure; - Assert.Throws(() => command.ExecuteNonQuery()); - } + using var command = new MySqlCommand("NonExistentStoredProcedure", m_database.Connection); + command.CommandType = CommandType.StoredProcedure; + Assert.Throws(() => command.ExecuteNonQuery()); } [Fact] public void OutputTimeParameter() { - using (var command = new MySqlCommand("GetTime", m_database.Connection)) - { - command.CommandType = CommandType.StoredProcedure; - var parameter = command.CreateParameter(); - parameter.ParameterName = "OutTime"; - parameter.Direction = ParameterDirection.Output; - command.Parameters.Add(parameter); - - command.ExecuteNonQuery(); - Assert.IsType(parameter.Value); - } + using var command = new MySqlCommand("GetTime", m_database.Connection); + command.CommandType = CommandType.StoredProcedure; + var parameter = command.CreateParameter(); + parameter.ParameterName = "OutTime"; + parameter.Direction = ParameterDirection.Output; + command.Parameters.Add(parameter); + + command.ExecuteNonQuery(); + Assert.IsType(parameter.Value); } private static string NormalizeSpaces(string input) diff --git a/tests/SideBySide/TransactionScopeTests.cs b/tests/SideBySide/TransactionScopeTests.cs index 728771e79..ca2508453 100644 --- a/tests/SideBySide/TransactionScopeTests.cs +++ b/tests/SideBySide/TransactionScopeTests.cs @@ -60,44 +60,35 @@ public void EnlistSameTransaction(string connectionString) [MemberData(nameof(ConnectionStrings))] public void EnlistTwoTransactions(string connectionString) { - using (var connection = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString)) - { - connection.Open(); + using var connection = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString); + connection.Open(); - using (var transaction1 = new CommittableTransaction()) - using (var transaction2 = new CommittableTransaction()) - { - connection.EnlistTransaction(transaction1); - Assert.Throws(() => connection.EnlistTransaction(transaction2)); - } - } + using var transaction1 = new CommittableTransaction(); + using var transaction2 = new CommittableTransaction(); + connection.EnlistTransaction(transaction1); + Assert.Throws(() => connection.EnlistTransaction(transaction2)); } [Theory] [MemberData(nameof(ConnectionStrings))] public void BeginTransactionInScope(string connectionString) { - using (var transactionScope = new TransactionScope()) - using (var connection = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString)) - { - connection.Open(); - Assert.Throws(() => connection.BeginTransaction()); - } + using var transactionScope = new TransactionScope(); + using var connection = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString); + connection.Open(); + Assert.Throws(() => connection.BeginTransaction()); } [Theory] [MemberData(nameof(ConnectionStrings))] public void BeginTransactionThenEnlist(string connectionString) { - using (var connection = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString)) - { - connection.Open(); - using (var dbTransaction = connection.BeginTransaction()) - using (var transaction = new CommittableTransaction()) - { - Assert.Throws(() => connection.EnlistTransaction(transaction)); - } - } + using var connection = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString); + connection.Open(); + + using var dbTransaction = connection.BeginTransaction(); + using var transaction = new CommittableTransaction(); + Assert.Throws(() => connection.EnlistTransaction(transaction)); } [Theory] @@ -109,13 +100,11 @@ public void CommitOneTransactionWithTransactionScope(string connectionString) using (var transactionScope = new TransactionScope()) { - using (var conn = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString)) - { - conn.Open(); - conn.Execute("insert into transaction_scope_test(value) values(1), (2);"); + using var conn = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString); + conn.Open(); + conn.Execute("insert into transaction_scope_test(value) values(1), (2);"); - transactionScope.Complete(); - } + transactionScope.Complete(); } var values = m_database.Connection.Query(@"select value from transaction_scope_test order by value;").ToList(); @@ -132,12 +121,10 @@ public void CommitOneTransactionWithEnlistTransaction(string connectionString) using (var conn = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString)) { conn.Open(); - using (var transaction = new CommittableTransaction()) - { - conn.EnlistTransaction(transaction); - conn.Execute("insert into transaction_scope_test(value) values(1), (2);"); - transaction.Commit(); - } + using var transaction = new CommittableTransaction(); + conn.EnlistTransaction(transaction); + conn.Execute("insert into transaction_scope_test(value) values(1), (2);"); + transaction.Commit(); } var values = m_database.Connection.Query(@"select value from transaction_scope_test order by value;").ToList(); @@ -153,11 +140,9 @@ public void RollBackOneTransactionWithTransactionScope(string connectionString) using (var transactionScope = new TransactionScope()) { - using (var conn = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString)) - { - conn.Open(); - conn.Execute("insert into transaction_scope_test(value) values(1), (2);"); - } + using var conn = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString); + conn.Open(); + conn.Execute("insert into transaction_scope_test(value) values(1), (2);"); } var values = m_database.Connection.Query(@"select value from transaction_scope_test order by value;").ToList(); @@ -174,11 +159,9 @@ public void RollBackOneTransactionWithEnlistTransaction(string connectionString) using (var conn = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString)) { conn.Open(); - using (var transaction = new CommittableTransaction()) - { - conn.EnlistTransaction(transaction); - conn.Execute("insert into transaction_scope_test(value) values(1), (2);"); - } + using var transaction = new CommittableTransaction(); + conn.EnlistTransaction(transaction); + conn.Execute("insert into transaction_scope_test(value) values(1), (2);"); } var values = m_database.Connection.Query(@"select value from transaction_scope_test order by value;").ToList(); @@ -194,16 +177,12 @@ public void ThrowExceptionInTransaction(string connectionString) try { - using (var transactionScope = new TransactionScope()) - { - using (var conn = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString)) - { - conn.Open(); - conn.Execute("insert into transaction_scope_test(value) values(1), (2);"); + using var transactionScope = new TransactionScope(); + using var conn = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString); + conn.Open(); + conn.Execute("insert into transaction_scope_test(value) values(1), (2);"); - throw new ApplicationException(); - } - } + throw new ApplicationException(); } catch (ApplicationException) { @@ -222,18 +201,14 @@ public void ThrowExceptionAfterCompleteInTransaction(string connectionString) try { - using (var transactionScope = new TransactionScope()) - { - using (var conn = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString)) - { - conn.Open(); - conn.Execute("insert into transaction_scope_test(value) values(1), (2);"); + using var transactionScope = new TransactionScope(); + using var conn = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString); + conn.Open(); + conn.Execute("insert into transaction_scope_test(value) values(1), (2);"); - transactionScope.Complete(); + transactionScope.Complete(); - throw new ApplicationException(); - } - } + throw new ApplicationException(); } catch (ApplicationException) { @@ -254,13 +229,11 @@ public void AutoEnlistFalseWithCommit(string connectionString) using (var conn = new MySqlConnection(AppConfig.ConnectionString + ";auto enlist=false;" + connectionString)) { conn.Open(); - using (var dbTransaction = conn.BeginTransaction()) - { - conn.Execute("insert into transaction_scope_test(value) values(1), (2);", transaction: dbTransaction); + using var dbTransaction = conn.BeginTransaction(); + conn.Execute("insert into transaction_scope_test(value) values(1), (2);", transaction: dbTransaction); - dbTransaction.Commit(); - transactionScope.Complete(); - } + dbTransaction.Commit(); + transactionScope.Complete(); } var values = m_database.Connection.Query(@"select value from transaction_scope_test order by value;").ToList(); @@ -278,18 +251,16 @@ public void AutoEnlistFalseWithoutCommit(string connectionString) using (var conn = new MySqlConnection(AppConfig.ConnectionString + ";auto enlist=false;" + connectionString)) { conn.Open(); - using (var dbTransaction = conn.BeginTransaction()) - { - conn.Execute("insert into transaction_scope_test(value) values(1), (2);", transaction: dbTransaction); + using var dbTransaction = conn.BeginTransaction(); + conn.Execute("insert into transaction_scope_test(value) values(1), (2);", transaction: dbTransaction); #if BASELINE - // With Connector/NET a MySqlTransaction can't roll back after TransactionScope has been completed; - // workaround is to explicitly dispose it first. In MySqlConnector (with AutoEnlist=false) they have - // independent lifetimes. - dbTransaction.Dispose(); + // With Connector/NET a MySqlTransaction can't roll back after TransactionScope has been completed; + // workaround is to explicitly dispose it first. In MySqlConnector (with AutoEnlist=false) they have + // independent lifetimes. + dbTransaction.Dispose(); #endif - transactionScope.Complete(); - } + transactionScope.Complete(); } var values = m_database.Connection.Query(@"select value from transaction_scope_test order by value;").ToList(); @@ -461,25 +432,19 @@ public void UsingSequentialConnectionsInOneTransactionWithoutAutoEnlistDoesNotDe public void UsingSequentialConnectionsInOneTransactionReusesPhysicalConnection(string connectionString) { connectionString = AppConfig.ConnectionString + ";AutoEnlist=false;" + connectionString; - using (var transaction = new CommittableTransaction()) - { - using (var connection1 = new MySqlConnection(connectionString)) - { - connection1.Open(); - connection1.EnlistTransaction(transaction); - var sessionId1 = connection1.ServerThread; + using var transaction = new CommittableTransaction(); + using var connection1 = new MySqlConnection(connectionString); + connection1.Open(); + connection1.EnlistTransaction(transaction); + var sessionId1 = connection1.ServerThread; - using (var connection2 = new MySqlConnection(connectionString)) - { - connection2.Open(); - Assert.NotEqual(sessionId1, connection2.ServerThread); + using var connection2 = new MySqlConnection(connectionString); + connection2.Open(); + Assert.NotEqual(sessionId1, connection2.ServerThread); - connection1.Close(); - connection2.EnlistTransaction(transaction); - Assert.Equal(sessionId1, connection2.ServerThread); - } - } - } + connection1.Close(); + connection2.EnlistTransaction(transaction); + Assert.Equal(sessionId1, connection2.ServerThread); } [Theory] @@ -697,19 +662,15 @@ public void CommitTwoTransactions() using (var transactionScope = new TransactionScope()) { - using (var conn1 = new MySqlConnection(AppConfig.ConnectionString)) - { - conn1.Open(); - conn1.Execute("insert into transaction_scope_test_1(value) values(1), (2);"); + using var conn1 = new MySqlConnection(AppConfig.ConnectionString); + conn1.Open(); + conn1.Execute("insert into transaction_scope_test_1(value) values(1), (2);"); - using (var conn2 = new MySqlConnection(AppConfig.ConnectionString)) - { - conn2.Open(); - conn2.Execute("insert into transaction_scope_test_2(value) values(3), (4);"); + using var conn2 = new MySqlConnection(AppConfig.ConnectionString); + conn2.Open(); + conn2.Execute("insert into transaction_scope_test_2(value) values(3), (4);"); - transactionScope.Complete(); - } - } + transactionScope.Complete(); } var values1 = m_database.Connection.Query(@"select value from transaction_scope_test_1 order by value;").ToList(); @@ -728,17 +689,13 @@ public void RollBackTwoTransactions() using (var transactionScope = new TransactionScope()) { - using (var conn1 = new MySqlConnection(AppConfig.ConnectionString)) - { - conn1.Open(); - conn1.Execute("insert into transaction_scope_test_1(value) values(1), (2);"); + using var conn1 = new MySqlConnection(AppConfig.ConnectionString); + conn1.Open(); + conn1.Execute("insert into transaction_scope_test_1(value) values(1), (2);"); - using (var conn2 = new MySqlConnection(AppConfig.ConnectionString)) - { - conn2.Open(); - conn2.Execute("insert into transaction_scope_test_2(value) values(3), (4);"); - } - } + using var conn2 = new MySqlConnection(AppConfig.ConnectionString); + conn2.Open(); + conn2.Execute("insert into transaction_scope_test_2(value) values(3), (4);"); } var values1 = m_database.Connection.Query(@"select value from transaction_scope_test_1 order by value;").ToList(); @@ -757,15 +714,11 @@ public void TwoSimultaneousConnectionsThrowsWithNonXaTransactions() using (new TransactionScope()) { - using (var conn1 = new MySqlConnection(connectionString)) - { - conn1.Open(); + using var conn1 = new MySqlConnection(connectionString); + conn1.Open(); - using (var conn2 = new MySqlConnection(connectionString)) - { - Assert.Throws(() => conn2.Open()); - } - } + using var conn2 = new MySqlConnection(connectionString); + Assert.Throws(() => conn2.Open()); } } @@ -831,15 +784,11 @@ public void TwoDifferentConnectionStringsThrowsWithNonXaTransactions() using (new TransactionScope()) { - using (var conn1 = new MySqlConnection(connectionString)) - { - conn1.Open(); - } + using var conn1 = new MySqlConnection(connectionString); + conn1.Open(); - using (var conn2 = new MySqlConnection(connectionString + ";MaxPoolSize=6")) - { - Assert.Throws(() => conn2.Open()); - } + using var conn2 = new MySqlConnection(connectionString + ";MaxPoolSize=6"); + Assert.Throws(() => conn2.Open()); } } @@ -849,15 +798,11 @@ public void CannotMixXaAndNonXaTransactions() { using (new TransactionScope()) { - using (var conn1 = new MySqlConnection(AppConfig.ConnectionString)) - { - conn1.Open(); + using var conn1 = new MySqlConnection(AppConfig.ConnectionString); + conn1.Open(); - using (var conn2 = new MySqlConnection(AppConfig.ConnectionString + ";UseXaTransactions=False")) - { - Assert.Throws(() => conn2.Open()); - } - } + using var conn2 = new MySqlConnection(AppConfig.ConnectionString + ";UseXaTransactions=False"); + Assert.Throws(() => conn2.Open()); } } @@ -866,15 +811,11 @@ public void CannotMixNonXaAndXaTransactions() { using (new TransactionScope()) { - using (var conn1 = new MySqlConnection(AppConfig.ConnectionString + ";UseXaTransactions=False")) - { - conn1.Open(); + using var conn1 = new MySqlConnection(AppConfig.ConnectionString + ";UseXaTransactions=False"); + conn1.Open(); - using (var conn2 = new MySqlConnection(AppConfig.ConnectionString)) - { - Assert.Throws(() => conn2.Open()); - } - } + using var conn2 = new MySqlConnection(AppConfig.ConnectionString); + Assert.Throws(() => conn2.Open()); } } #endif diff --git a/tests/SideBySide/UpdateTests.cs b/tests/SideBySide/UpdateTests.cs index b4199f308..9bd1239bf 100644 --- a/tests/SideBySide/UpdateTests.cs +++ b/tests/SideBySide/UpdateTests.cs @@ -47,12 +47,10 @@ public async Task UpdateRowsExecuteReader(int oldValue, int expectedRowsUpdated) p.Value = 4; cmd.Parameters.Add(p); - using (var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false)) - { - Assert.False(await reader.ReadAsync().ConfigureAwait(false)); - Assert.Equal(expectedRowsUpdated, reader.RecordsAffected); - Assert.False(await reader.NextResultAsync().ConfigureAwait(false)); - } + using var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false); + Assert.False(await reader.ReadAsync().ConfigureAwait(false)); + Assert.Equal(expectedRowsUpdated, reader.RecordsAffected); + Assert.False(await reader.NextResultAsync().ConfigureAwait(false)); } }