-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNpgsqlAnalyzer.cs
More file actions
333 lines (300 loc) · 14.8 KB
/
NpgsqlAnalyzer.cs
File metadata and controls
333 lines (300 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Npgsql;
namespace NpgsqlAnalyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class NpgsqlAnalyzer : DiagnosticAnalyzer
{
private const string ConfigFileName = ".npgsqlanalyzers";
private Configuration _configuration;
public NpgsqlAnalyzer()
{
}
public NpgsqlAnalyzer(Configuration configuration)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
}
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(
Rules.BadSqlStatement,
Rules.UndefinedTable,
Rules.UndefinedColumn,
Rules.MissingCommand);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction((compilationContext) =>
{
if (_configuration is null)
{
var configFile = compilationContext.Options.AdditionalFiles.FirstOrDefault(
(file) => Path.GetFileName(file.Path).Equals(ConfigFileName));
if (configFile is null)
{
throw new InvalidOperationException("Missing configuration file.");
}
_configuration = Configuration.FromFile(
configFile.GetText().Lines.Select(line => line.ToString()));
}
compilationContext.RegisterSyntaxNodeAction(
AnalyzeInvocationExpressionNode,
SyntaxKind.ObjectCreationExpression);
});
}
private static void Log(string value)
{
var logFile = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
nameof(NpgsqlAnalyzer),
"log.txt");
Directory.CreateDirectory(Path.GetDirectoryName(logFile));
File.AppendAllText(logFile, $"{value}{Environment.NewLine}");
}
/// <summary>
/// Extracts the pure query from a literal.
/// </summary>
/// <param name="queryLiteral">
/// A query literal in the form of <c>"{query}"</c> or <c>@"{query}"</c>.
/// </param>
/// <remarks>
/// A query literal is retrieved from the analysis context in the form of <c>"{query}"</c> or <c>@"{query}"</c>.
/// </remarks>
/// <returns>
/// The pure query, without the enclosing quotes and @.
/// </returns>
private static string ExtractQuery(string queryLiteral) =>
queryLiteral
.Trim()
.Substring(1) // Removes the @ or " at the start of the string definition
.Replace("\"", string.Empty);
/// <summary>
/// Replaces named parameters inside the query with <c>NULL</c>.
/// </summary>
/// <param name="query">
/// A query containing named parameters. For example, <c>SELECT * FROM TABLE WHERE Id = @id;</c>.
/// </param>
/// <returns>
/// The same query with the named parameters replaced by <c>NULL</c>.
/// </returns>
private static string ReplaceNamedParameters(string query) =>
Regex.Replace(query, @"@\w+", "NULL");
private static VariableDeclaratorSyntax FindVariableDeclaratorInNodes(
IEnumerable<SyntaxNode> nodes,
string variableName)
{
return nodes
.SelectMany(child => child.ChildNodes())
.OfType<LocalDeclarationStatementSyntax>()
.Select(localDeclaration => localDeclaration.Declaration)
.SelectMany(variableDeclaration => variableDeclaration.Variables)
.Where(variableDeclarator => variableDeclarator.Identifier.Text.Equals(variableName))
.FirstOrDefault();
}
private static IEnumerable<AssignmentExpressionSyntax> FindVariableAssignmentsInNodes(
IEnumerable<SyntaxNode> nodes,
Func<string, bool> matchVariableName)
{
return nodes
.SelectMany(node => node.ChildNodes())
.OfType<ExpressionStatementSyntax>()
.Select(expressionStatement => expressionStatement.Expression)
.Where(expression => expression.IsKind(SyntaxKind.SimpleAssignmentExpression))
.OfType<AssignmentExpressionSyntax>()
.Where(expression => matchVariableName(expression.Left.ToString()));
}
private static IEnumerable<AssignmentExpressionSyntax> FindVariableAssignmentsInNodes(
IEnumerable<SyntaxNode> nodes,
string variableName)
{
return nodes
.SelectMany(node => node.ChildNodes())
.OfType<ExpressionStatementSyntax>()
.Select(expressionStatement => expressionStatement.Expression)
.Where(expression => expression.IsKind(SyntaxKind.SimpleAssignmentExpression))
.OfType<AssignmentExpressionSyntax>()
.Where(expression => expression.Left.ToString().Equals(variableName));
}
private static SqlStatement ExtractSqlStatement(
SyntaxNodeAnalysisContext context,
ObjectCreationExpressionSyntax npgsqlCommandCtor)
{
if (!npgsqlCommandCtor.ArgumentList.Arguments.Any())
{
/**
* Query is not passed through the constructor,
* therefore it might be assigned to the CommandText prop
*/
var commandTextAssignment = FindVariableAssignmentsInNodes(
npgsqlCommandCtor.Ancestors(),
name => name.Contains($".{nameof(NpgsqlCommand.CommandText)}"))
.FirstOrDefault();
if (commandTextAssignment is null)
{
// Query is not assigned to the CommandText prop
return SqlStatement.StatementNotFound;
}
if (commandTextAssignment.Right.IsKind(SyntaxKind.StringLiteralExpression))
{
return new SqlStatement(
statement: ExtractQuery(commandTextAssignment.Right.ToString()),
location: commandTextAssignment.Right.GetLocation());
}
else if (commandTextAssignment.Right.IsKind(SyntaxKind.IdentifierName))
{
var varDeclarator = FindVariableDeclaratorInNodes(
nodes: npgsqlCommandCtor.Ancestors(),
variableName: commandTextAssignment.Right.ToString());
var varAssignments = FindVariableAssignmentsInNodes(
nodes: npgsqlCommandCtor.Ancestors(),
variableName: commandTextAssignment.Right.ToString());
if (varAssignments.Any())
{
var declarationSymbol = context.SemanticModel.GetDeclaredSymbol(varDeclarator);
int declarationLine = declarationSymbol.Locations.First().GetLineSpan().StartLinePosition.Line;
int commandTextLine = commandTextAssignment.GetLocation().GetLineSpan().StartLinePosition.Line;
var variableAssignment = varAssignments
.OrderBy(assignment =>
{
int assignmentLine = assignment.GetLocation().GetLineSpan().StartLinePosition.Line;
return Math.Abs(commandTextLine - assignmentLine);
})
.First();
int assignmentLine = variableAssignment.GetLocation().GetLineSpan().StartLinePosition.Line;
if (Math.Abs(commandTextLine - assignmentLine) < Math.Abs(commandTextLine - declarationLine))
{
return new SqlStatement(
statement: ExtractQuery(variableAssignment.Right.ToString()),
location: variableAssignment.Right.GetLocation());
}
}
// The syntax used to assign a value to NpgsqlCommand.CommandText is not supported
return new SqlStatement(
statement: ExtractQuery(varDeclarator.Initializer.Value.ToString()),
location: varDeclarator.Initializer.Value.GetLocation());
}
return default;
}
var queryArgument = npgsqlCommandCtor.ArgumentList.Arguments.First();
if (queryArgument.Expression.IsKind(SyntaxKind.StringLiteralExpression))
{
// Query is defined in the constructor
return new SqlStatement(
statement: ExtractQuery(queryArgument.ToString()),
location: npgsqlCommandCtor.GetLocation());
}
/**
* The first constructor argument is not a string literal containing the query,
* therefore we should search for a variable declaring the query
*/
string queryVariableName = queryArgument.ToString();
/**
* Variable declaration => string query = "";
* Variable assignment => query = "assignment after being declared";
*/
var variableDeclarator = FindVariableDeclaratorInNodes(context.Node.Ancestors(), queryVariableName);
var variableAssignments = FindVariableAssignmentsInNodes(context.Node.Ancestors(), queryVariableName);
if (variableAssignments.Any())
{
/**
* If there are any assignments that means the variable is reused, we should analyze the one that
* is closest to the NpgsqlCommand constructor
*/
var declarationSymbol = context.SemanticModel.GetDeclaredSymbol(variableDeclarator);
int declarationLine = declarationSymbol.Locations.First().GetLineSpan().StartLinePosition.Line;
int npgsqlCommandLine = npgsqlCommandCtor.GetLocation().GetLineSpan().StartLinePosition.Line;
var variableAssignment = variableAssignments
.OrderBy(assignment =>
{
int assignmentLine = assignment.GetLocation().GetLineSpan().StartLinePosition.Line;
return Math.Abs(npgsqlCommandLine - assignmentLine);
})
.First();
int assignmentLine = variableAssignment.GetLocation().GetLineSpan().StartLinePosition.Line;
if (Math.Abs(npgsqlCommandLine - assignmentLine) < Math.Abs(npgsqlCommandLine - declarationLine))
{
return new SqlStatement(
statement: ExtractQuery(variableAssignment.Right.ToString()),
location: variableAssignment.Right.GetLocation());
}
}
return new SqlStatement(
statement: ExtractQuery(variableDeclarator.Initializer.Value.ToString()),
location: variableDeclarator.Initializer.Value.GetLocation());
}
private void AnalyzeInvocationExpressionNode(SyntaxNodeAnalysisContext context)
{
var semanticModel = context.SemanticModel;
var npgsqlCommandExpression = (ObjectCreationExpressionSyntax)context.Node;
// Check if object creation is NpgsqlCommand
if (!(semanticModel.GetSymbolInfo(npgsqlCommandExpression).Symbol is IMethodSymbol methodSymbol) ||
methodSymbol.MethodKind != MethodKind.Constructor ||
!methodSymbol.ReceiverType.Name.Equals(nameof(NpgsqlCommand), StringComparison.OrdinalIgnoreCase))
{
return;
}
var statement = ExtractSqlStatement(context, npgsqlCommandExpression);
if (statement.IsValid)
{
ExecuteAndValidateQuery(
query: ReplaceNamedParameters(statement.Statement),
context: context,
sourceLocation: statement.Location);
}
else if (statement.NotFound)
{
context.ReportDiagnostic(Diagnostic.Create(
descriptor: Rules.MissingCommand,
location: npgsqlCommandExpression.GetLocation()));
}
}
private void ExecuteAndValidateQuery(
string query,
SyntaxNodeAnalysisContext context,
Location sourceLocation)
{
try
{
using var connection = new NpgsqlConnection(_configuration.ConnectionString);
connection.Open();
using var command = new NpgsqlCommand(query, connection);
command.ExecuteReader(CommandBehavior.SchemaOnly);
}
catch (PostgresException ex)
{
switch (ex.SqlState)
{
case PostgresErrorCodes.UndefinedTable:
string table = Regex.Match(ex.Statement.SQL.Substring(ex.Position - 1), @"\w+").Value;
context.ReportDiagnostic(Diagnostic.Create(
descriptor: Rules.UndefinedTable,
location: sourceLocation,
messageArgs: table));
break;
case PostgresErrorCodes.UndefinedColumn:
string column = Regex.Match(ex.Statement.SQL.Substring(ex.Position - 1), @"\w+").Value;
context.ReportDiagnostic(Diagnostic.Create(
descriptor: Rules.UndefinedColumn,
location: sourceLocation,
messageArgs: column));
break;
default:
context.ReportDiagnostic(Diagnostic.Create(
descriptor: Rules.BadSqlStatement,
location: sourceLocation,
ex.Message));
break;
}
}
}
}
}