Skip to content

Commit 04b37f3

Browse files
authored
EF1003: Detect explicit string.Format/string.Concat in raw SQL APIs (#38208)
The EF1003 analyzer warns when a raw SQL API receives a dynamically built string. It already covered interpolated strings (EF1002) and the binary `+` concatenation operator (EF1003), but explicit calls such as db.Database.ExecuteSqlRaw(string.Format("UPDATE T SET X={0}", id)); db.Users.FromSqlRaw(string.Concat("SELECT * FROM T WHERE Id=", id)); were silently allowed. Extend the analyzer to also report these when at least one argument is non-constant. Implicit conversions (object boxing in the `string.Format(string, object)` overloads) are unwrapped so that fully constant calls do not trigger the warning. Fixes #37915
1 parent 1c5cd69 commit 04b37f3

2 files changed

Lines changed: 202 additions & 0 deletions

File tree

‎src/EFCore.Analyzers/StringsUsageInRawQueriesDiagnosticAnalyzer.cs‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,9 +186,74 @@ IInterpolatedStringOperation interpolatedString when AnalyzeInterpolatedString(i
186186
} concatenation when AnalyzeConcatenation(concatenation)
187187
=> StringConcatenationDescriptor,
188188

189+
// ...an explicit call to string.Format(...) or string.Concat(...)
190+
IInvocationOperation argInvocation
191+
=> AnalyzeStringMethodInvocation(argInvocation),
192+
189193
_ => null,
190194
};
191195

196+
private static DiagnosticDescriptor? AnalyzeStringMethodInvocation(IInvocationOperation invocation)
197+
{
198+
if (invocation.TargetMethod.ContainingType.SpecialType != SpecialType.System_String
199+
|| invocation.TargetMethod.Name is not (nameof(string.Format) or nameof(string.Concat)))
200+
{
201+
return null;
202+
}
203+
204+
return HasNonConstantArgument(invocation) ? StringConcatenationDescriptor : null;
205+
}
206+
207+
private static bool HasNonConstantArgument(IInvocationOperation invocation)
208+
{
209+
foreach (var argument in invocation.Arguments)
210+
{
211+
// The IFormatProvider argument of the string.Format(IFormatProvider, ...) overloads
212+
// (e.g. CultureInfo.InvariantCulture) never contributes to the SQL text and is never a
213+
// compile-time constant — skip it so a fully-constant format call isn't flagged. See #37915.
214+
if (argument.Parameter?.Type is
215+
{ Name: "IFormatProvider", ContainingNamespace: { Name: "System", ContainingNamespace.IsGlobalNamespace: true } })
216+
{
217+
continue;
218+
}
219+
220+
var value = Unwrap(argument.Value);
221+
222+
// Implicit params arrays — inspect each element rather than the array itself.
223+
if (argument.ArgumentKind == ArgumentKind.ParamArray
224+
&& value is IArrayCreationOperation { Initializer.ElementValues: var elements })
225+
{
226+
foreach (var element in elements)
227+
{
228+
if (!Unwrap(element).ConstantValue.HasValue)
229+
{
230+
return true;
231+
}
232+
}
233+
234+
continue;
235+
}
236+
237+
if (!value.ConstantValue.HasValue)
238+
{
239+
return true;
240+
}
241+
}
242+
243+
return false;
244+
245+
// Strip implicit conversions (e.g. boxing to object) so we see the original constant.
246+
static IOperation Unwrap(IOperation operation)
247+
{
248+
while (operation is IConversionOperation { IsImplicit: true } conversion)
249+
{
250+
operation = conversion.Operand;
251+
}
252+
253+
return operation;
254+
}
255+
}
256+
192257
private static bool AnalyzeInterpolatedString(IInterpolatedStringOperation interpolatedString)
193258
{
194259
if (interpolatedString.ConstantValue.HasValue)

‎test/EFCore.Analyzers.Tests/StringConcatenationInRawQueriesAnalyzerTests.cs‎

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,143 @@ void M(MyDbContext db)
162162
db.{{call}}("FooBar WHERE Id = " + Id);
163163
}
164164
}
165+
""",
166+
DiagnosticResult.CompilerWarning(EFDiagnostics.StringConcatenationUsageInRawQueries).WithLocation(0));
167+
168+
[Theory]
169+
[MemberData(nameof(DoNotReportData))]
170+
public Task Constant_string_format_do_not_report(string call)
171+
=> Verify.VerifyAnalyzerAsync(
172+
$$"""
173+
{{MyDbContext}}
174+
175+
class C
176+
{
177+
void M(MyDbContext db)
178+
{
179+
db.{{call}}(string.Format("FooBar WHERE Id = {0}", "1"));
180+
}
181+
}
182+
""");
183+
184+
[Theory]
185+
[MemberData(nameof(DoNotReportData))]
186+
public Task Constant_string_format_with_format_provider_do_not_report(string call)
187+
=> Verify.VerifyAnalyzerAsync(
188+
$$"""
189+
{{MyDbContext}}
190+
191+
class C
192+
{
193+
void M(MyDbContext db)
194+
{
195+
db.{{call}}(string.Format(System.Globalization.CultureInfo.InvariantCulture, "FooBar WHERE Id = {0}", "1"));
196+
}
197+
}
198+
""");
199+
200+
[Theory]
201+
[MemberData(nameof(ShouldReportData))]
202+
public Task String_format_with_format_provider_and_argument_should_report(string call)
203+
=> Verify.VerifyAnalyzerAsync(
204+
$$"""
205+
{{MyDbContext}}
206+
207+
class C
208+
{
209+
void M(MyDbContext db, string id)
210+
{
211+
db.{{call}}(string.Format(System.Globalization.CultureInfo.InvariantCulture, "FooBar WHERE Id = {0}", id));
212+
}
213+
}
214+
""",
215+
DiagnosticResult.CompilerWarning(EFDiagnostics.StringConcatenationUsageInRawQueries).WithLocation(0));
216+
217+
[Theory]
218+
[MemberData(nameof(ShouldReportData))]
219+
public Task String_format_with_argument_should_report(string call)
220+
=> Verify.VerifyAnalyzerAsync(
221+
$$"""
222+
{{MyDbContext}}
223+
224+
class C
225+
{
226+
void M(MyDbContext db, string id)
227+
{
228+
db.{{call}}(string.Format("FooBar WHERE Id = {0}", id));
229+
}
230+
}
231+
""",
232+
DiagnosticResult.CompilerWarning(EFDiagnostics.StringConcatenationUsageInRawQueries).WithLocation(0));
233+
234+
[Theory]
235+
[MemberData(nameof(ShouldReportData))]
236+
public Task String_format_with_method_call_should_report(string call)
237+
=> Verify.VerifyAnalyzerAsync(
238+
$$"""
239+
{{MyDbContext}}
240+
241+
class C
242+
{
243+
void M(MyDbContext db)
244+
{
245+
db.{{call}}(string.Format("FooBar WHERE Id = {0}", GetId()));
246+
}
247+
248+
string GetId() => "1";
249+
}
250+
""",
251+
DiagnosticResult.CompilerWarning(EFDiagnostics.StringConcatenationUsageInRawQueries).WithLocation(0));
252+
253+
[Theory]
254+
[MemberData(nameof(DoNotReportData))]
255+
public Task Constant_string_concat_do_not_report(string call)
256+
=> Verify.VerifyAnalyzerAsync(
257+
$$"""
258+
{{MyDbContext}}
259+
260+
class C
261+
{
262+
void M(MyDbContext db)
263+
{
264+
db.{{call}}(string.Concat("FooBar", " WHERE Id = ", "1"));
265+
}
266+
}
267+
""");
268+
269+
[Theory]
270+
[MemberData(nameof(ShouldReportData))]
271+
public Task String_concat_with_argument_should_report(string call)
272+
=> Verify.VerifyAnalyzerAsync(
273+
$$"""
274+
{{MyDbContext}}
275+
276+
class C
277+
{
278+
void M(MyDbContext db, string id)
279+
{
280+
db.{{call}}(string.Concat("FooBar WHERE Id = ", id));
281+
}
282+
}
283+
""",
284+
DiagnosticResult.CompilerWarning(EFDiagnostics.StringConcatenationUsageInRawQueries).WithLocation(0));
285+
286+
[Theory]
287+
[MemberData(nameof(ShouldReportData))]
288+
public Task String_concat_with_method_call_should_report(string call)
289+
=> Verify.VerifyAnalyzerAsync(
290+
$$"""
291+
{{MyDbContext}}
292+
293+
class C
294+
{
295+
void M(MyDbContext db)
296+
{
297+
db.{{call}}(string.Concat("FooBar WHERE Id = ", GetId()));
298+
}
299+
300+
string GetId() => "1";
301+
}
165302
""",
166303
DiagnosticResult.CompilerWarning(EFDiagnostics.StringConcatenationUsageInRawQueries).WithLocation(0));
167304
}

0 commit comments

Comments
 (0)