Skip to content

Commit

Permalink
[repo/SqlClient] Prepare to .NET9 (#2297)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kielek authored Nov 5, 2024
1 parent e7449fb commit 4301c94
Show file tree
Hide file tree
Showing 10 changed files with 89 additions and 79 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ public override void OnEventWritten(string name, object? payload)

_ = this.commandTextFetcher.TryFetch(command, out var commandText);

if (this.commandTypeFetcher.TryFetch(command, out CommandType commandType))
if (this.commandTypeFetcher.TryFetch(command, out var commandType))
{
switch (commandType)
{
Expand Down Expand Up @@ -135,6 +135,8 @@ public override void OnEventWritten(string name, object? payload)

case CommandType.TableDirect:
break;
default:
break;
}
}

Expand Down Expand Up @@ -186,7 +188,7 @@ public override void OnEventWritten(string name, object? payload)
{
if (activity.IsAllDataRequested)
{
if (this.exceptionFetcher.TryFetch(payload, out Exception? exception) && exception != null)
if (this.exceptionFetcher.TryFetch(payload, out var exception) && exception != null)
{
activity.AddTag(SemanticConventions.AttributeErrorType, exception.GetType().FullName);

Expand Down Expand Up @@ -214,6 +216,8 @@ public override void OnEventWritten(string name, object? payload)
}
}

break;
default:
break;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,32 +55,32 @@ private SqlConnectionDetails()

public static SqlConnectionDetails ParseFromDataSource(string dataSource)
{
if (ConnectionDetailCache.TryGetValue(dataSource, out SqlConnectionDetails? connectionDetails))
if (ConnectionDetailCache.TryGetValue(dataSource, out var connectionDetails))
{
return connectionDetails;
}

var match = DataSourceRegex.Match(dataSource);

string? serverHostName = match.Groups[2].Value;
var serverHostName = match.Groups[2].Value;
string? serverIpAddress = null;
string? instanceName = null;
int? port = null;

var uriHostNameType = Uri.CheckHostName(serverHostName);
if (uriHostNameType == UriHostNameType.IPv4 || uriHostNameType == UriHostNameType.IPv6)
if (uriHostNameType is UriHostNameType.IPv4 or UriHostNameType.IPv6)
{
serverIpAddress = serverHostName;
serverHostName = null;
}

string maybeProtocol = match.Groups[1].Value;
bool isNamedPipe = maybeProtocol.Length > 0 &&
maybeProtocol.StartsWith("np", StringComparison.OrdinalIgnoreCase);
var maybeProtocol = match.Groups[1].Value;
var isNamedPipe = maybeProtocol.Length > 0 &&
maybeProtocol.StartsWith("np", StringComparison.OrdinalIgnoreCase);

if (isNamedPipe)
{
string pipeName = match.Groups[3].Value;
var pipeName = match.Groups[3].Value;
if (pipeName.Length > 0)
{
var namedInstancePipeMatch = NamedPipeRegex.Match(pipeName);
Expand All @@ -95,11 +95,11 @@ public static SqlConnectionDetails ParseFromDataSource(string dataSource)
if (match.Groups[4].Length > 0)
{
instanceName = match.Groups[3].Value;
port = int.TryParse(match.Groups[4].Value, out int parsedPort)
port = int.TryParse(match.Groups[4].Value, out var parsedPort)
? parsedPort == 1433 ? null : parsedPort
: null;
}
else if (int.TryParse(match.Groups[3].Value, out int parsedPort))
else if (int.TryParse(match.Groups[3].Value, out var parsedPort))
{
instanceName = null;
port = parsedPort == 1433 ? null : parsedPort;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,8 @@ private void OnBeginExecute(EventWrittenEventArgs eventData)
return;
}

string dataSource = (string)eventData.Payload[1];
string databaseName = (string)eventData.Payload[2];
var dataSource = (string)eventData.Payload[1];
var databaseName = (string)eventData.Payload[2];
var startTags = SqlActivitySourceHelper.GetTagListFromConnectionInfo(dataSource, databaseName, this.options, out var activityName);
var activity = SqlActivitySourceHelper.ActivitySource.StartActivity(
activityName,
Expand All @@ -129,7 +129,7 @@ private void OnBeginExecute(EventWrittenEventArgs eventData)

if (activity.IsAllDataRequested)
{
string commandText = (string)eventData.Payload[3];
var commandText = (string)eventData.Payload[3];
if (!string.IsNullOrEmpty(commandText) && this.options.SetDbStatementForText)
{
if (this.options.EmitOldAttributes)
Expand Down Expand Up @@ -170,7 +170,7 @@ private void OnEndExecute(EventWrittenEventArgs eventData)
{
if (activity.IsAllDataRequested)
{
int compositeState = (int)eventData.Payload[1];
var compositeState = (int)eventData.Payload[1];
if ((compositeState & 0b001) != 0b001)
{
if ((compositeState & 0b010) == 0b010)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@ internal sealed class SqlClientInstrumentation : IDisposable
#if NETFRAMEWORK
private readonly SqlEventSourceListener sqlEventSourceListener;
#else
private static readonly HashSet<string> DiagnosticSourceEvents = new()
{
private static readonly HashSet<string> DiagnosticSourceEvents =
[
"System.Data.SqlClient.WriteCommandBefore",
"Microsoft.Data.SqlClient.WriteCommandBefore",
"System.Data.SqlClient.WriteCommandAfter",
"Microsoft.Data.SqlClient.WriteCommandAfter",
"System.Data.SqlClient.WriteCommandError",
"Microsoft.Data.SqlClient.WriteCommandError",
};
"Microsoft.Data.SqlClient.WriteCommandError"
];

private readonly Func<string, object?, object?, bool> isEnabled = (eventName, _, _)
=> DiagnosticSourceEvents.Contains(eventName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,15 @@ public void SuccessfulCommandTest(
})
.Build();

using SqlConnection sqlConnection = new SqlConnection(this.GetConnectionString());
using var sqlConnection = new SqlConnection(this.GetConnectionString());

sqlConnection.Open();

string dataSource = sqlConnection.DataSource;
var dataSource = sqlConnection.DataSource;

sqlConnection.ChangeDatabase("master");
#pragma warning disable CA2100
using SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection)
using var sqlCommand = new SqlCommand(commandText, sqlConnection)
#pragma warning restore CA2100
{
CommandType = commandType,
Expand Down Expand Up @@ -107,14 +107,11 @@ public void SuccessfulCommandTest(

private string GetConnectionString()
{
switch (this.fixture.DatabaseContainer)
return this.fixture.DatabaseContainer switch
{
case SqlEdgeContainer container:
return container.GetConnectionString();
case MsSqlContainer container:
return container.GetConnectionString();
default:
throw new InvalidOperationException($"Container type '${this.fixture.DatabaseContainer.GetType().Name}' is not supported.");
}
SqlEdgeContainer container => container.GetConnectionString(),
MsSqlContainer container => container.GetConnectionString(),
_ => throw new InvalidOperationException($"Container type '${this.fixture.DatabaseContainer.GetType().Name}' is not supported."),
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,21 @@

namespace OpenTelemetry.Instrumentation.SqlClient.Tests;

#pragma warning disable CA1515
public sealed class SqlClientIntegrationTestsFixture : IAsyncLifetime
#pragma warning restore CA1515
{
// The Microsoft SQL Server Docker image is not compatible with ARM devices, such as Macs with Apple Silicon.
private readonly IContainer databaseContainer = Architecture.Arm64.Equals(RuntimeInformation.ProcessArchitecture) ? CreateSqlEdge() : CreateMsSql();

public IContainer DatabaseContainer => this.databaseContainer;
public IContainer DatabaseContainer { get; } = Architecture.Arm64.Equals(RuntimeInformation.ProcessArchitecture) ? CreateSqlEdge() : CreateMsSql();

public Task InitializeAsync()
{
return this.databaseContainer.StartAsync();
return this.DatabaseContainer.StartAsync();
}

public Task DisposeAsync()
{
return this.databaseContainer.DisposeAsync().AsTask();
return this.DatabaseContainer.DisposeAsync().AsTask();
}

private static SqlEdgeContainer CreateSqlEdge()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@

namespace OpenTelemetry.Instrumentation.SqlClient.Tests;

#pragma warning disable CA1515
public class SqlClientTestCase : IEnumerable<object[]>
#pragma warning restore CA1515
{
public string ConnectionString { get; set; } = string.Empty;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ public void SqlClient_BadArgs()
[Fact]
public void SqlClient_NamedOptions()
{
int defaultExporterOptionsConfigureOptionsInvocations = 0;
int namedExporterOptionsConfigureOptionsInvocations = 0;
var defaultExporterOptionsConfigureOptionsInvocations = 0;
var namedExporterOptionsConfigureOptionsInvocations = 0;

using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.ConfigureServices(services =>
Expand Down Expand Up @@ -310,12 +310,7 @@ public void ShouldCollectTelemetryWhenFilterEvaluatesToTrue()
},
cmd =>
{
if (cmd is SqlCommand command)
{
return command.CommandText == "select 2";
}
return true;
return cmd is not SqlCommand command || command.CommandText == "select 2";
});

Assert.Single(activities);
Expand All @@ -333,12 +328,7 @@ public void ShouldNotCollectTelemetryWhenFilterEvaluatesToFalse()
},
cmd =>
{
if (cmd is SqlCommand command)
{
return command.CommandText == "select 2";
}
return true;
return cmd is not SqlCommand command || command.CommandText == "select 2";
});

Assert.Empty(activities);
Expand Down Expand Up @@ -406,7 +396,7 @@ internal static void VerifyActivityData(
if (shouldEnrich)
{
Assert.NotEmpty(activity.Tags.Where(tag => tag.Key == "enriched"));
Assert.Equal("yes", activity.Tags.Where(tag => tag.Key == "enriched").FirstOrDefault().Value);
Assert.Equal("yes", activity.Tags.FirstOrDefault(tag => tag.Key == "enriched").Value);
}
else
{
Expand Down Expand Up @@ -461,6 +451,12 @@ internal static void VerifyActivityData(
Assert.Null(activity.GetTagValue(SemanticConventions.AttributeDbQueryText));
}

break;
case CommandType.TableDirect:
Assert.Fail("Not supported command type: CommandType.TableDirect");
break;
default:
Assert.Fail($"Not supported command type: {commandType}");
break;
}
}
Expand Down Expand Up @@ -614,7 +610,7 @@ private Activity[] RunCommandWithFilter(
afterExecuteEventData);
}

return activities.ToArray();
return [.. activities];
}
#endif

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,16 @@ public async Task SuccessfulCommandTest(CommandType commandType, string commandT
.Build();

Assert.NotNull(SqlConnectionString);
using SqlConnection sqlConnection = new SqlConnection(SqlConnectionString);
using var sqlConnection = new SqlConnection(SqlConnectionString);

await sqlConnection.OpenAsync();

string dataSource = sqlConnection.DataSource;
var dataSource = sqlConnection.DataSource;

sqlConnection.ChangeDatabase("master");

#pragma warning disable CA2100
using SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection)
using var sqlCommand = new SqlCommand(commandText, sqlConnection)
#pragma warning restore CA2100
{
CommandType = commandType,
Expand Down Expand Up @@ -114,7 +114,7 @@ public void EventSourceFakeTests(
bool emitOldAttributes = true,
bool emitNewAttributes = false)
{
using IFakeBehavingSqlEventSource fakeSqlEventSource = (IFakeBehavingSqlEventSource)Activator.CreateInstance(eventSourceType);
using var fakeSqlEventSource = (IFakeBehavingSqlEventSource)Activator.CreateInstance(eventSourceType);

var exportedItems = new List<Activity>();
using var shutdownSignal = Sdk.CreateTracerProviderBuilder()
Expand All @@ -128,21 +128,21 @@ public void EventSourceFakeTests(
})
.Build();

int objectId = Guid.NewGuid().GetHashCode();
var objectId = Guid.NewGuid().GetHashCode();

var dataSource = "127.0.0.1\\instanceName,port";
fakeSqlEventSource.WriteBeginExecuteEvent(objectId, dataSource, "master", commandType == CommandType.StoredProcedure ? commandText : string.Empty);

// success is stored in the first bit in compositeState 0b001
int successFlag = !isFailure ? 1 : 0;
var successFlag = !isFailure ? 1 : 0;

// isSqlException is stored in the second bit in compositeState 0b010
int isSqlExceptionFlag = sqlExceptionNumber > 0 ? 2 : 0;
var isSqlExceptionFlag = sqlExceptionNumber > 0 ? 2 : 0;

// synchronous state is stored in the third bit in compositeState 0b100
int synchronousFlag = false ? 4 : 0;
var synchronousFlag = false ? 4 : 0;

int compositeState = successFlag | isSqlExceptionFlag | synchronousFlag;
var compositeState = successFlag | isSqlExceptionFlag | synchronousFlag;

fakeSqlEventSource.WriteEndExecuteEvent(objectId, compositeState, sqlExceptionNumber);
shutdownSignal.Dispose();
Expand All @@ -158,7 +158,7 @@ public void EventSourceFakeTests(
[InlineData(typeof(FakeMisbehavingMdsSqlEventSource))]
public void EventSourceFakeUnknownEventWithNullPayloadTest(Type eventSourceType)
{
using IFakeMisbehavingSqlEventSource fakeSqlEventSource = (IFakeMisbehavingSqlEventSource)Activator.CreateInstance(eventSourceType);
using var fakeSqlEventSource = (IFakeMisbehavingSqlEventSource)Activator.CreateInstance(eventSourceType);

var exportedItems = new List<Activity>();
using var shutdownSignal = Sdk.CreateTracerProviderBuilder()
Expand All @@ -178,7 +178,7 @@ public void EventSourceFakeUnknownEventWithNullPayloadTest(Type eventSourceType)
[InlineData(typeof(FakeMisbehavingMdsSqlEventSource))]
public void EventSourceFakeInvalidPayloadTest(Type eventSourceType)
{
using IFakeMisbehavingSqlEventSource fakeSqlEventSource = (IFakeMisbehavingSqlEventSource)Activator.CreateInstance(eventSourceType);
using var fakeSqlEventSource = (IFakeMisbehavingSqlEventSource)Activator.CreateInstance(eventSourceType);

var exportedItems = new List<Activity>();
using var shutdownSignal = Sdk.CreateTracerProviderBuilder()
Expand All @@ -199,29 +199,29 @@ public void EventSourceFakeInvalidPayloadTest(Type eventSourceType)
[InlineData(typeof(FakeBehavingMdsSqlEventSource))]
public void DefaultCaptureTextFalse(Type eventSourceType)
{
using IFakeBehavingSqlEventSource fakeSqlEventSource = (IFakeBehavingSqlEventSource)Activator.CreateInstance(eventSourceType);
using var fakeSqlEventSource = (IFakeBehavingSqlEventSource)Activator.CreateInstance(eventSourceType);

var exportedItems = new List<Activity>();
var shutdownSignal = Sdk.CreateTracerProviderBuilder()
.AddInMemoryExporter(exportedItems)
.AddSqlClientInstrumentation()
.Build();

int objectId = Guid.NewGuid().GetHashCode();
var objectId = Guid.NewGuid().GetHashCode();

const string commandText = "TestCommandTest";
fakeSqlEventSource.WriteBeginExecuteEvent(objectId, "127.0.0.1", "master", commandText);

// success is stored in the first bit in compositeState 0b001
int successFlag = 1;
var successFlag = 1;

// isSqlException is stored in the second bit in compositeState 0b010
int isSqlExceptionFlag = 2;
var isSqlExceptionFlag = 2;

// synchronous state is stored in the third bit in compositeState 0b100
int synchronousFlag = 4;
var synchronousFlag = 4;

int compositeState = successFlag | isSqlExceptionFlag | synchronousFlag;
var compositeState = successFlag | isSqlExceptionFlag | synchronousFlag;

fakeSqlEventSource.WriteEndExecuteEvent(objectId, compositeState, 0);
shutdownSignal.Dispose();
Expand Down
Loading

0 comments on commit 4301c94

Please sign in to comment.