Skip to content

Commit a3b5c79

Browse files
committed
Use C# 9 pattern matching.
1 parent 088cc34 commit a3b5c79

17 files changed

+92
-92
lines changed

src/MySqlConnector/Core/BinaryRow.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ protected override object GetValueCore(ReadOnlySpan<byte> data, ColumnDefinition
115115
if (columnDefinition.CharacterSet == CharacterSet.Binary)
116116
{
117117
var guidFormat = Connection.GuidFormat;
118-
if ((guidFormat == MySqlGuidFormat.Binary16 || guidFormat == MySqlGuidFormat.TimeSwapBinary16 || guidFormat == MySqlGuidFormat.LittleEndianBinary16) && columnDefinition.ColumnLength == 16)
118+
if ((guidFormat is MySqlGuidFormat.Binary16 or MySqlGuidFormat.TimeSwapBinary16 or MySqlGuidFormat.LittleEndianBinary16) && columnDefinition.ColumnLength == 16)
119119
return CreateGuidFromBytes(guidFormat, data);
120120

121121
return data.ToArray();

src/MySqlConnector/Core/CommandExecutor.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ public static async Task<MySqlDataReader> ExecuteReaderAsync(IReadOnlyList<IMySq
6464
Log.Warn("Session{0} query was interrupted", connection.Session.Id);
6565
throw new OperationCanceledException(ex. Message, ex, cancellationToken);
6666
}
67-
catch (Exception ex) when (payload.Span.Length > 4_194_304 && (ex is SocketException || ex is IOException || ex is MySqlProtocolException))
67+
catch (Exception ex) when (payload.Span.Length > 4_194_304 && (ex is SocketException or IOException or MySqlProtocolException))
6868
{
6969
// 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
7070
// use "decimal megabytes" (to round up) when creating the exception message

src/MySqlConnector/Core/ResultSet.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ private bool IsHostVerified(MySqlConnection connection)
182182

183183
public async Task ReadEntireAsync(IOBehavior ioBehavior, CancellationToken cancellationToken)
184184
{
185-
while (State == ResultSetState.ReadingRows || State == ResultSetState.ReadResultSetHeader)
185+
while (State is ResultSetState.ReadingRows or ResultSetState.ReadResultSetHeader)
186186
await ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
187187
}
188188

@@ -227,7 +227,7 @@ public async Task<bool> ReadAsync(IOBehavior ioBehavior, CancellationToken cance
227227
private ValueTask<Row?> ScanRowAsync(IOBehavior ioBehavior, Row? row, CancellationToken cancellationToken)
228228
{
229229
// if we've already read past the end of this resultset, Read returns false
230-
if (BufferState == ResultSetState.HasMoreData || BufferState == ResultSetState.NoMoreData || BufferState == ResultSetState.None)
230+
if (BufferState is ResultSetState.HasMoreData or ResultSetState.NoMoreData or ResultSetState.None)
231231
return new ValueTask<Row?>(default(Row?));
232232

233233
using var registration = Command.CancellableCommand.RegisterCancel(cancellationToken); // lgtm[cs/useless-assignment-to-local]

src/MySqlConnector/Core/Row.cs

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -211,17 +211,13 @@ public int GetInt32(int ordinal)
211211
throw new InvalidCastException();
212212

213213
var columnDefinition = ResultSet.ColumnDefinitions[ordinal];
214-
if (columnDefinition.ColumnType == ColumnType.Decimal || columnDefinition.ColumnType == ColumnType.NewDecimal)
214+
if (columnDefinition.ColumnType is ColumnType.Decimal or ColumnType.NewDecimal)
215215
{
216216
return (int) (decimal) GetValue(ordinal);
217217
}
218-
else if (columnDefinition.ColumnType != ColumnType.Tiny &&
219-
columnDefinition.ColumnType != ColumnType.Short &&
220-
columnDefinition.ColumnType != ColumnType.Int24 &&
221-
columnDefinition.ColumnType != ColumnType.Long &&
222-
columnDefinition.ColumnType != ColumnType.Longlong &&
223-
columnDefinition.ColumnType != ColumnType.Bit &&
224-
columnDefinition.ColumnType != ColumnType.Year)
218+
else if (columnDefinition.ColumnType is not ColumnType.Tiny and not ColumnType.Short
219+
and not ColumnType.Int24 and not ColumnType.Long and not ColumnType.Longlong
220+
and not ColumnType.Bit and not ColumnType.Year)
225221
{
226222
throw new InvalidCastException("Can't convert {0} to Int32".FormatInvariant(ResultSet.ColumnTypes![ordinal]));
227223
}

src/MySqlConnector/Core/SchemaProvider.cs

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -254,32 +254,31 @@ private Task FillDataTypes(IOBehavior ioBehavior, DataTable dataTable, Cancellat
254254
foreach (var columnType in TypeMapper.Instance.GetColumnTypeMetadata())
255255
{
256256
// hard-code a few types to not appear in the schema table
257-
var mySqlDbType = columnType.MySqlDbType;
258-
if (mySqlDbType == MySqlDbType.Decimal || mySqlDbType == MySqlDbType.Newdate || mySqlDbType == MySqlDbType.Null || mySqlDbType == MySqlDbType.VarString)
257+
if (columnType.MySqlDbType is MySqlDbType.Decimal or MySqlDbType.Newdate or MySqlDbType.Null or MySqlDbType.VarString)
259258
continue;
260-
if (mySqlDbType == MySqlDbType.Bool && columnType.IsUnsigned)
259+
if (columnType is { MySqlDbType: MySqlDbType.Bool, IsUnsigned: true })
261260
continue;
262261

263262
// set miscellaneous properties in code (rather than being data-driven)
264263
var clrType = columnType.DbTypeMapping.ClrType;
265264
var clrTypeName = clrType.ToString();
265+
var mySqlDbType = columnType.MySqlDbType;
266266
var dataTypeName = mySqlDbType == MySqlDbType.Guid ? "GUID" :
267267
mySqlDbType == MySqlDbType.Bool ? "BOOL" : columnType.DataTypeName;
268-
var isAutoIncrementable = mySqlDbType == MySqlDbType.Byte || mySqlDbType == MySqlDbType.Int16 || mySqlDbType == MySqlDbType.Int24 || mySqlDbType == MySqlDbType.Int32 || mySqlDbType == MySqlDbType.Int64 ||
269-
mySqlDbType == MySqlDbType.UByte || mySqlDbType == MySqlDbType.UInt16 || mySqlDbType == MySqlDbType.UInt24 || mySqlDbType == MySqlDbType.UInt32 || mySqlDbType == MySqlDbType.UInt64;
268+
var isAutoIncrementable = mySqlDbType is MySqlDbType.Byte or MySqlDbType.Int16 or MySqlDbType.Int24 or MySqlDbType.Int32 or MySqlDbType.Int64
269+
or MySqlDbType.UByte or MySqlDbType.UInt16 or MySqlDbType.UInt24 or MySqlDbType.UInt32 or MySqlDbType.UInt64;
270270
var isBestMatch = clrTypes.Add(clrTypeName);
271271
var isFixedLength = isAutoIncrementable ||
272-
mySqlDbType == MySqlDbType.Date || mySqlDbType == MySqlDbType.DateTime || mySqlDbType == MySqlDbType.Time || mySqlDbType == MySqlDbType.Timestamp ||
273-
mySqlDbType == MySqlDbType.Double || mySqlDbType == MySqlDbType.Float || mySqlDbType == MySqlDbType.Year || mySqlDbType == MySqlDbType.Guid || mySqlDbType == MySqlDbType.Bool;
274-
var isFixedPrecisionScale = isFixedLength ||
275-
mySqlDbType == MySqlDbType.Bit || mySqlDbType == MySqlDbType.NewDecimal;
276-
var isLong = mySqlDbType == MySqlDbType.Blob || mySqlDbType == MySqlDbType.MediumBlob || mySqlDbType == MySqlDbType.LongBlob;
272+
mySqlDbType is MySqlDbType.Date or MySqlDbType.DateTime or MySqlDbType.Time or MySqlDbType.Timestamp
273+
or MySqlDbType.Double or MySqlDbType.Float or MySqlDbType.Year or MySqlDbType.Guid or MySqlDbType.Bool;
274+
var isFixedPrecisionScale = isFixedLength || mySqlDbType is MySqlDbType.Bit or MySqlDbType.NewDecimal;
275+
var isLong = mySqlDbType is MySqlDbType.Blob or MySqlDbType.MediumBlob or MySqlDbType.LongBlob;
277276

278277
// map ColumnTypeMetadata to the row for this data type
279278
var createFormatParts = columnType.CreateFormat.Split(';');
280279
dataTable.Rows.Add(
281280
dataTypeName,
282-
(int)mySqlDbType,
281+
(int) mySqlDbType,
283282
columnType.ColumnSize,
284283
createFormatParts[0],
285284
createFormatParts.Length == 1 ? null : createFormatParts[1],

src/MySqlConnector/Core/ServerSession.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ public void StartQuerying(ICancellableCommand command)
246246
{
247247
lock (m_lock)
248248
{
249-
if (m_state == State.Querying || m_state == State.CancelingQuery)
249+
if (m_state is State.Querying or State.CancelingQuery)
250250
{
251251
m_logArguments[1] = m_state;
252252
Log.Error("Session{0} can't execute new command when in SessionState: {1}", m_logArguments[0], m_state);
@@ -289,7 +289,7 @@ public void FinishQuerying()
289289

290290
lock (m_lock)
291291
{
292-
if (m_state == State.Querying || m_state == State.ClearingPendingCancellation)
292+
if (m_state is State.Querying or State.ClearingPendingCancellation)
293293
m_state = State.Connected;
294294
else
295295
VerifyState(State.Failed);
@@ -307,7 +307,7 @@ public async Task DisposeAsync(IOBehavior ioBehavior, CancellationToken cancella
307307
State state;
308308
lock (m_lock)
309309
{
310-
if (m_state == State.Connected || m_state == State.Failed)
310+
if (m_state is State.Connected or State.Failed)
311311
m_state = State.Closing;
312312
state = m_state;
313313
}
@@ -1099,7 +1099,7 @@ private async Task InitSslAsync(ProtocolCapabilities serverCapabilities, Connect
10991099
}
11001100
else
11011101
{
1102-
var requireValid = cs.SslMode == MySqlSslMode.VerifyCA || cs.SslMode == MySqlSslMode.VerifyFull;
1102+
var requireValid = cs.SslMode is MySqlSslMode.VerifyCA or MySqlSslMode.VerifyFull;
11031103
var foundCertificates = store.Certificates.Find(X509FindType.FindByThumbprint, cs.CertificateThumbprint, requireValid);
11041104
if (foundCertificates.Count == 0)
11051105
{
@@ -1290,7 +1290,7 @@ private async Task InitSslAsync(ProtocolCapabilities serverCapabilities, Connect
12901290

12911291
bool ValidateRemoteCertificate(object rcbSender, X509Certificate? rcbCertificate, X509Chain? rcbChain, SslPolicyErrors rcbPolicyErrors)
12921292
{
1293-
if (cs.SslMode == MySqlSslMode.Preferred || cs.SslMode == MySqlSslMode.Required)
1293+
if (cs.SslMode is MySqlSslMode.Preferred or MySqlSslMode.Required)
12941294
return true;
12951295

12961296
if ((rcbPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0 && caCertificateChain is not null && rcbCertificate is not null)
@@ -1412,7 +1412,7 @@ internal sealed class SslClientAuthenticationOptions
14121412
private bool ShouldGetRealServerDetails(ConnectionSettings cs)
14131413
{
14141414
// currently hardcoded to the version(s) returned by the Azure Database for MySQL proxy
1415-
if (ServerVersion.OriginalString == "5.6.42.0" || ServerVersion.OriginalString == "5.6.39.0" || ServerVersion.OriginalString == "5.6.26.0")
1415+
if (ServerVersion.OriginalString is "5.6.42.0" or "5.6.39.0" or "5.6.26.0")
14161416
return true;
14171417

14181418
// detect Azure Database for MySQL DNS suffixes

src/MySqlConnector/Core/SqlParser.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,7 @@ public void Parse(string sql)
270270
states |= FinalParseStates.NeedsNewline;
271271
state = beforeCommentState;
272272
}
273-
else if (state == State.SingleQuotedStringSingleQuote || state == State.DoubleQuotedStringDoubleQuote || state == State.BacktickQuotedStringBacktick)
273+
else if (state is State.SingleQuotedStringSingleQuote or State.DoubleQuotedStringDoubleQuote or State.BacktickQuotedStringBacktick)
274274
{
275275
state = State.Statement;
276276
}
@@ -334,9 +334,9 @@ protected enum FinalParseStates
334334
NeedsSemicolon = 4,
335335
}
336336

337-
private static bool IsWhitespace(char ch) => ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n';
337+
private static bool IsWhitespace(char ch) => ch is ' ' or '\t' or '\r' or '\n';
338338

339-
private static bool IsVariableName(char ch) => (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '.' || ch == '_' || ch == '$' || (ch >= 0x0080 && ch <= 0xFFFF); // lgtm[cs/constant-comparison]
339+
private static bool IsVariableName(char ch) => ch is (>= 'a' and <= 'z') or (>= 'A' and <= 'Z') or (>= '0' and <= '9') or '.' or '_' or '$' or (>= (char) 0x0080 and <= (char) 0xFFFF);
340340

341341
private enum State
342342
{

src/MySqlConnector/Core/TextRow.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ protected override object GetValueCore(ReadOnlySpan<byte> data, ColumnDefinition
7171
if (columnDefinition.CharacterSet == CharacterSet.Binary)
7272
{
7373
var guidFormat = Connection.GuidFormat;
74-
if ((guidFormat == MySqlGuidFormat.Binary16 || guidFormat == MySqlGuidFormat.TimeSwapBinary16 || guidFormat == MySqlGuidFormat.LittleEndianBinary16) && columnDefinition.ColumnLength == 16)
74+
if ((guidFormat is MySqlGuidFormat.Binary16 or MySqlGuidFormat.TimeSwapBinary16 or MySqlGuidFormat.LittleEndianBinary16) && columnDefinition.ColumnLength == 16)
7575
return CreateGuidFromBytes(guidFormat, data);
7676

7777
return data.ToArray();

src/MySqlConnector/Core/TypeMapper.cs

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -216,22 +216,28 @@ public static MySqlDbType ConvertToMySqlDbType(ColumnDefinitionPayload columnDef
216216
var type = columnDefinition.ColumnType;
217217
if (columnDefinition.CharacterSet == CharacterSet.Binary)
218218
{
219-
if ((guidFormat == MySqlGuidFormat.Binary16 || guidFormat == MySqlGuidFormat.TimeSwapBinary16 || guidFormat == MySqlGuidFormat.LittleEndianBinary16) && columnDefinition.ColumnLength == 16)
219+
if ((guidFormat is MySqlGuidFormat.Binary16 or MySqlGuidFormat.TimeSwapBinary16 or MySqlGuidFormat.LittleEndianBinary16) && columnDefinition.ColumnLength == 16)
220220
return MySqlDbType.Guid;
221221

222-
return type == ColumnType.String ? MySqlDbType.Binary :
223-
type == ColumnType.VarString ? MySqlDbType.VarBinary :
224-
type == ColumnType.TinyBlob ? MySqlDbType.TinyBlob :
225-
type == ColumnType.Blob ? MySqlDbType.Blob :
226-
type == ColumnType.MediumBlob ? MySqlDbType.MediumBlob :
227-
MySqlDbType.LongBlob;
222+
return type switch
223+
{
224+
ColumnType.String => MySqlDbType.Binary,
225+
ColumnType.VarString => MySqlDbType.VarBinary,
226+
ColumnType.TinyBlob => MySqlDbType.TinyBlob,
227+
ColumnType.Blob => MySqlDbType.Blob,
228+
ColumnType.MediumBlob => MySqlDbType.MediumBlob,
229+
_ => MySqlDbType.LongBlob,
230+
};
228231
}
229-
return type == ColumnType.String ? MySqlDbType.String :
230-
type == ColumnType.VarString ? MySqlDbType.VarChar :
231-
type == ColumnType.TinyBlob ? MySqlDbType.TinyText :
232-
type == ColumnType.Blob ? MySqlDbType.Text :
233-
type == ColumnType.MediumBlob ? MySqlDbType.MediumText :
234-
MySqlDbType.LongText;
232+
return type switch
233+
{
234+
ColumnType.String => MySqlDbType.String,
235+
ColumnType.VarString => MySqlDbType.VarChar,
236+
ColumnType.TinyBlob => MySqlDbType.TinyText,
237+
ColumnType.Blob => MySqlDbType.Text,
238+
ColumnType.MediumBlob => MySqlDbType.MediumText,
239+
_ => MySqlDbType.LongText,
240+
};
235241

236242
case ColumnType.Json:
237243
return MySqlDbType.JSON;
@@ -285,8 +291,7 @@ public static MySqlDbType ConvertToMySqlDbType(ColumnDefinitionPayload columnDef
285291

286292
public static ushort ConvertToColumnTypeAndFlags(MySqlDbType dbType, MySqlGuidFormat guidFormat)
287293
{
288-
var isUnsigned = dbType == MySqlDbType.UByte || dbType == MySqlDbType.UInt16 ||
289-
dbType == MySqlDbType.UInt24 || dbType == MySqlDbType.UInt32 || dbType == MySqlDbType.UInt64;
294+
var isUnsigned = dbType is MySqlDbType.UByte or MySqlDbType.UInt16 or MySqlDbType.UInt24 or MySqlDbType.UInt32 or MySqlDbType.UInt64;
290295
var columnType = dbType switch
291296
{
292297
MySqlDbType.Bool or MySqlDbType.Byte or MySqlDbType.UByte => ColumnType.Tiny,
@@ -295,7 +300,7 @@ public static ushort ConvertToColumnTypeAndFlags(MySqlDbType dbType, MySqlGuidFo
295300
MySqlDbType.Int32 or MySqlDbType.UInt32 => ColumnType.Long,
296301
MySqlDbType.Int64 or MySqlDbType.UInt64 => ColumnType.Longlong,
297302
MySqlDbType.Bit => ColumnType.Bit,
298-
MySqlDbType.Guid => (guidFormat == MySqlGuidFormat.Char36 || guidFormat == MySqlGuidFormat.Char32) ? ColumnType.String : ColumnType.Blob,
303+
MySqlDbType.Guid => (guidFormat is MySqlGuidFormat.Char36 or MySqlGuidFormat.Char32) ? ColumnType.String : ColumnType.Blob,
299304
MySqlDbType.Enum or MySqlDbType.Set => ColumnType.String,
300305
MySqlDbType.Binary or MySqlDbType.String => ColumnType.String,
301306
MySqlDbType.VarBinary or MySqlDbType.VarChar or MySqlDbType.VarString => ColumnType.VarString,

src/MySqlConnector/MySqlBulkCopy.cs

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,7 @@ private async ValueTask WriteToServerAsync(IOBehavior ioBehavior, CancellationTo
265265
else
266266
{
267267
var type = schema[i].DataType;
268-
if (type == typeof(byte[]) || (type == typeof(Guid) && (m_connection.GuidFormat == MySqlGuidFormat.Binary16 || m_connection.GuidFormat == MySqlGuidFormat.LittleEndianBinary16 || m_connection.GuidFormat == MySqlGuidFormat.TimeSwapBinary16)))
268+
if (type == typeof(byte[]) || (type == typeof(Guid) && (m_connection.GuidFormat is MySqlGuidFormat.Binary16 or MySqlGuidFormat.LittleEndianBinary16 or MySqlGuidFormat.TimeSwapBinary16)))
269269
{
270270
AddColumnMapping(columnMappings, addDefaultMappings, i, destinationColumn, $"@`\uE002\bcol{i}`", $"%COL% = UNHEX(%VAR%)");
271271
}
@@ -479,13 +479,16 @@ static bool WriteValue(MySqlConnection connection, object value, ref int inputIn
479479
{
480480
return Utf8Formatter.TryFormat(decimalValue, output, out bytesWritten);
481481
}
482-
else if (value is byte[] || value is ReadOnlyMemory<byte> || value is Memory<byte> || value is ArraySegment<byte> || value is MySqlGeometry)
482+
else if (value is byte[] or ReadOnlyMemory<byte> or Memory<byte> or ArraySegment<byte> or MySqlGeometry)
483483
{
484-
var inputSpan = value is byte[] byteArray ? byteArray.AsSpan() :
485-
value is ArraySegment<byte> arraySegment ? arraySegment.AsSpan() :
486-
value is Memory<byte> memory ? memory.Span :
487-
value is MySqlGeometry geometry ? geometry.ValueSpan :
488-
((ReadOnlyMemory<byte>) value).Span;
484+
var inputSpan = value switch
485+
{
486+
byte[] byteArray => byteArray.AsSpan(),
487+
ArraySegment<byte> arraySegment => arraySegment.AsSpan(),
488+
Memory<byte> memory => memory.Span,
489+
MySqlGeometry geometry => geometry.ValueSpan,
490+
_ => ((ReadOnlyMemory<byte>) value).Span,
491+
};
489492

490493
return WriteBytes(inputSpan, ref inputIndex, output, out bytesWritten);
491494
}
@@ -500,7 +503,7 @@ static bool WriteValue(MySqlConnection connection, object value, ref int inputIn
500503
bytesWritten = 1;
501504
return true;
502505
}
503-
else if (value is float || value is double)
506+
else if (value is float or double)
504507
{
505508
// NOTE: Utf8Formatter doesn't support "R"
506509
return WriteString("{0:R}".FormatInvariant(value), ref utf8Encoder, output, out bytesWritten);
@@ -538,9 +541,7 @@ static bool WriteValue(MySqlConnection connection, object value, ref int inputIn
538541
}
539542
else if (value is Guid guidValue)
540543
{
541-
if (connection.GuidFormat == MySqlGuidFormat.Binary16 ||
542-
connection.GuidFormat == MySqlGuidFormat.TimeSwapBinary16 ||
543-
connection.GuidFormat == MySqlGuidFormat.LittleEndianBinary16)
544+
if (connection.GuidFormat is MySqlGuidFormat.Binary16 or MySqlGuidFormat.TimeSwapBinary16 or MySqlGuidFormat.LittleEndianBinary16)
544545
{
545546
var bytes = guidValue.ToByteArray();
546547
if (connection.GuidFormat != MySqlGuidFormat.LittleEndianBinary16)

0 commit comments

Comments
 (0)