Skip to content

Commit

Permalink
support string.Format in direct usage
Browse files Browse the repository at this point in the history
  • Loading branch information
DeagleGross committed Oct 22, 2023
1 parent 1280a1a commit c61b69c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Dapper.AOT.Analyzers/Internal/Inspection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -966,6 +966,7 @@ public static bool TryGetConstantValueWithSyntax<T>(IOperation val, out T? value

if (initializer is BinaryExpressionSyntax)
{
// since we are parsing `string` here, `BinaryExpression` stands for string concatenation
value = default!;
syntax = null;
syntaxKind = SyntaxKind.AddExpression;
Expand All @@ -992,6 +993,21 @@ public static bool TryGetConstantValueWithSyntax<T>(IOperation val, out T? value
return false;
}

if (val is IInvocationOperation invocation)
{
if (invocation.TargetMethod is {
Name: "Format",
ContainingType: { SpecialType: SpecialType.System_String },
ContainingNamespace: { Name: "System" }
})
{
value = default!;
syntax = null;
syntaxKind = SyntaxKind.AddExpression;
return false;
}
}

// other non-trivial default constant values
if (val.ConstantValue.HasValue)
{
Expand Down
6 changes: 6 additions & 0 deletions test/Dapper.AOT.Test/Verifiers/DAP242.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ public Task ConcatenatedStringDetection_LocalVariableUsage() => Test("""
_ = connection.Query<int>({|#0:sqlQuery|});
""", Diagnostic(Diagnostics.ConcatenatedStringSqlExpression).WithLocation(0));

[Fact]
public Task ConcatenatedStringDetection_StringFormat() => Test("""
int id = 1;
_ = connection.Query<int>({|#0:string.Format("select Id from Customers where Id = {0}", id)|});
""", Diagnostic(Diagnostics.ConcatenatedStringSqlExpression).WithLocation(0));

private Task Test(string methodCode, params DiagnosticResult[] expected) => CSVerifyAsync($$"""
using Dapper;
using System.Data;
Expand Down

0 comments on commit c61b69c

Please sign in to comment.