65 lines
8.1 KiB
C#
65 lines
8.1 KiB
C#
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.RegularExpressions;
|
|
using Microsoft.CodeAnalysis;
|
|
using Microsoft.CodeAnalysis.CSharp;
|
|
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
|
|
|
// Syntax-based, production-source-only check. No database connection or application SQL execution.
|
|
internal static class DatabaseArchitectureTests
|
|
{
|
|
public sealed record Finding(string File, int Line, string Method, string Operation, string Fingerprint);
|
|
static readonly Regex Sql = new(@"\b(SELECT\s+[\s\S]*?\bFROM|INSERT\s+(?:INTO\s+)?(?:dbo\.|@)|UPDATE\s+(?:dbo\.|[a-z_]+\s+SET)|DELETE\s+(?:FROM\s+)?dbo\.|MERGE\s+dbo\.|ALTER\s+TABLE|CREATE\s+(?:OR\s+ALTER\s+)?PROCEDURE|SET\s+NOCOUNT|COL_LENGTH\s*\()", RegexOptions.IgnoreCase);
|
|
public static IReadOnlyList<Finding> Inspect(string code, string file)
|
|
{
|
|
var syntax=CSharpSyntaxTree.ParseText(code).GetRoot();var findings=new List<Finding>();
|
|
var values=syntax.DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v=>v.Initializer!=null).GroupBy(v=>v.Identifier.Text).ToDictionary(g=>g.Key,g=>g.First().Initializer!.Value);
|
|
var helpers=syntax.DescendantNodes().OfType<MethodDeclarationSyntax>().Where(m=>m.ReturnType.ToString().EndsWith("CommandDefinition")).Select(m=>m.Identifier.Text).ToHashSet();
|
|
var connections=syntax.DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v=>v.Initializer?.Value.ToString().Contains(".CreateConnection(")==true||v.Initializer?.Value.ToString().Contains("new SqlConnection(")==true).Select(v=>v.Identifier.Text).Concat(syntax.DescendantNodes().OfType<ParameterSyntax>().Where(p=>p.Type?.ToString().EndsWith("DbConnection")==true).Select(p=>p.Identifier.Text)).ToHashSet();
|
|
var commandParameters=syntax.DescendantNodes().OfType<ParameterSyntax>().Where(p=>p.Type?.ToString().EndsWith("CommandDefinition")==true).Select(p=>p.Identifier.Text).ToHashSet();
|
|
string Text(ExpressionSyntax e,int depth=0)=>depth>8?e.ToString():e switch {LiteralExpressionSyntax l=>l.Token.ValueText,IdentifierNameSyntax n when values.TryGetValue(n.Identifier.Text,out var value)=>Text(value,depth+1),BinaryExpressionSyntax b=>Text(b.Left,depth+1)+Text(b.Right,depth+1),_=>e.ToString()};
|
|
bool Definition(ExpressionSyntax e)=>e is IdentifierNameSyntax parameter&&commandParameters.Contains(parameter.Identifier.Text)||e is ObjectCreationExpressionSyntax o&&o.Type.ToString().EndsWith("CommandDefinition")||e is IdentifierNameSyntax n&&values.TryGetValue(n.Identifier.Text,out var v)&&Definition(v)||e is InvocationExpressionSyntax i&&helpers.Contains(i.Expression.ToString());
|
|
void Add(SyntaxNode n,string operation,string sql){var method=n.Ancestors().OfType<MethodDeclarationSyntax>().FirstOrDefault()?.Identifier.Text??"<initializer>";var type=n.Ancestors().OfType<TypeDeclarationSyntax>().FirstOrDefault()?.Identifier.Text??"";var hash=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(sql.Trim())));findings.Add(new(file,n.GetLocation().GetLineSpan().StartLinePosition.Line+1,type+"."+method,operation,hash));}
|
|
foreach(var n in syntax.DescendantNodes().OfType<InvocationExpressionSyntax>())
|
|
{
|
|
if(n.Expression is not MemberAccessExpressionSyntax member)continue;var name=member.Name.Identifier.Text;
|
|
if(!(name.StartsWith("Query")||name is "Execute" or "ExecuteAsync" or "ExecuteScalar" or "ExecuteScalarAsync" or "ExecuteReader" or "ExecuteReaderAsync")||n.ArgumentList.Arguments.Count==0)continue;
|
|
var staticDapper=member.Expression.ToString() is "SqlMapper" or "Dapper.SqlMapper";
|
|
var first=n.ArgumentList.Arguments.FirstOrDefault(a=>a.NameColon?.Name.Identifier.Text=="sql")??n.ArgumentList.Arguments[staticDapper&&n.ArgumentList.Arguments.Count>1?1:0];if(Definition(first.Expression))continue;
|
|
var stored=n.ArgumentList.Arguments.Any(a=>a.NameColon?.Name.Identifier.Text=="commandType"&&a.Expression.ToString().EndsWith("CommandType.StoredProcedure"));var text=Text(first.Expression);
|
|
if(!stored&&(staticDapper||member.Expression is IdentifierNameSyntax receiver&&connections.Contains(receiver.Identifier.Text)||Sql.IsMatch(text)||text.StartsWith("dbo.")||first.Expression is InterpolatedStringExpressionSyntax&&Sql.IsMatch(first.Expression.ToString())))Add(n,name,text);
|
|
}
|
|
foreach(var n in syntax.DescendantNodes().OfType<BaseObjectCreationExpressionSyntax>())
|
|
{
|
|
var type=n is ObjectCreationExpressionSyntax o?o.Type.ToString():n.Ancestors().OfType<MethodDeclarationSyntax>().FirstOrDefault()?.ReturnType.ToString();
|
|
if(type is null||!(type.EndsWith("SqlCommand")||type.EndsWith("CommandDefinition"))||n.ArgumentList?.Arguments.Count is not >0)continue;
|
|
if(!n.ToString().Contains("CommandType.StoredProcedure",StringComparison.Ordinal))Add(n,type,Text(n.ArgumentList.Arguments[0].Expression));
|
|
}
|
|
foreach(var n in syntax.DescendantNodes().OfType<AssignmentExpressionSyntax>().Where(n=>n.Left.ToString().EndsWith(".CommandText")))
|
|
if(Sql.IsMatch(Text(n.Right)) || !Regex.IsMatch(Text(n.Right),@"^dbo\.[A-Za-z_][A-Za-z0-9_]*$"))Add(n,"CommandText",Text(n.Right));
|
|
foreach(var n in syntax.DescendantNodes().OfType<UsingDirectiveSyntax>().Where(n=>n.Name?.ToString().Contains("EntityFramework",StringComparison.OrdinalIgnoreCase)==true))Add(n,"Entity Framework",n.ToString());
|
|
foreach(var n in syntax.DescendantNodes().OfType<BaseTypeSyntax>().Where(n=>n.Type.ToString().Split('.').Last() is "DbContext" or "IdentityDbContext"))Add(n,"EF DbContext",n.ToString());
|
|
return findings;
|
|
}
|
|
public static IReadOnlyList<Finding> Scan(string root)
|
|
{
|
|
var result=new List<Finding>();
|
|
foreach(var folder in new[]{"PlotLine","PlotDirector.WordCompanion","PlotDirector.NativeCompanion"})
|
|
foreach(var file in Directory.EnumerateFiles(Path.Combine(root,folder),"*.cs",SearchOption.AllDirectories).Where(f=>!f.Split(Path.DirectorySeparatorChar).Any(p=>p is "bin" or "obj" or "Tests")))result.AddRange(Inspect(File.ReadAllText(file),Path.GetRelativePath(root,file).Replace('\\','/')));
|
|
foreach(var file in Directory.EnumerateFiles(root,"*.csproj",SearchOption.AllDirectories).Where(f=>!f.Split(Path.DirectorySeparatorChar).Any(p=>p is "bin" or "obj" or ".git")&&!f.Contains(".Tests/")))
|
|
if(Regex.IsMatch(File.ReadAllText(file),@"PackageReference\s+Include\s*=\s*""(?:Microsoft\.)?EntityFramework",RegexOptions.IgnoreCase))result.Add(new(Path.GetRelativePath(root,file),1,"<project>","EF dependency",""));
|
|
return result;
|
|
}
|
|
public static void Run()
|
|
{
|
|
var root=Directory.GetCurrentDirectory();while(!File.Exists(Path.Combine(root,"PlotLine.slnx")))root=Directory.GetParent(root)?.FullName??throw new Exception("Repository root not found");
|
|
var actual=Scan(root);
|
|
if(actual.Count>0)throw new Exception(string.Join(Environment.NewLine,actual.Select(f =>
|
|
$"{f.File}:{f.Line} {f.Method}: {f.Operation} must use a parameterised stored procedure. Add a forward-only migration; executable application SQL has no exceptions.")));
|
|
var samples=new[]{("db.QueryAsync(\"SELECT * FROM dbo.Books\");",1),("db.ExecuteAsync($\"DELETE FROM dbo.Books WHERE BookID={id}\");",1),("var sql=\"UPDATE dbo.Books SET BookTitle=@title\";db.ExecuteAsync(sql);",1),("new SqlCommand(\"SELECT * FROM dbo.Books\",db);",1),("db.QueryAsync(\"dbo.Book_Get\",new {BookID=1},commandType:CommandType.StoredProcedure);",0),("using var db=factory.CreateConnection();db.ExecuteAsync(builder.ToString());",1),("// SELECT * FROM dbo.Books\nvar x=1;",0),("cmd.CommandText=builder.ToString();",1),("Dapper.SqlMapper.QueryAsync(db,\"SELECT * FROM dbo.Books\");",1),("CommandDefinition Command(string sql)=>new(sql,commandType:CommandType.StoredProcedure);db.QueryAsync(Command(\"dbo.Book_Get\"));",0)};
|
|
if(Inspect("using Microsoft.EntityFrameworkCore; class Example {}","sample.cs").Count!=1)throw new Exception("EF import detector self-test failed");
|
|
foreach(var (sample,count) in samples)if(Inspect("class Test {void Run(){"+sample+"}}","sample.cs").Count!=count)throw new Exception("SQL architecture detector self-test failed: "+sample);
|
|
}
|
|
}
|