Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f103bc4ec4 | ||
|
|
0267d52d28 | ||
|
|
e3dfc12abe | ||
|
|
52ac8f509e | ||
|
|
4a0e9d7d6b | ||
|
|
3c2ee7f9a7 | ||
|
|
c71e15c37f | ||
|
|
0711d06884 | ||
|
|
0dae811dd0 |
@@ -1,4 +1,6 @@
|
|||||||
using SQLLinter.Infrastructure.Configuration;
|
using SQLLinter.Infrastructure.Configuration;
|
||||||
|
using SQLLinter.Infrastructure.Diagram;
|
||||||
|
using SQLLinter.Infrastructure.Parser;
|
||||||
using SQLLinter.Infrastructure.Reporters;
|
using SQLLinter.Infrastructure.Reporters;
|
||||||
|
|
||||||
namespace SQLLinter.CLI
|
namespace SQLLinter.CLI
|
||||||
@@ -7,7 +9,7 @@ namespace SQLLinter.CLI
|
|||||||
{
|
{
|
||||||
static void Main(string[] args)
|
static void Main(string[] args)
|
||||||
{
|
{
|
||||||
var rep = new HTMLReporter();
|
var rep = new Reporter();
|
||||||
var con = new Config()
|
var con = new Config()
|
||||||
{
|
{
|
||||||
CompatibilityLevel = 170,
|
CompatibilityLevel = 170,
|
||||||
@@ -43,16 +45,27 @@ namespace SQLLinter.CLI
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
var linter = new Linter(con, rep);
|
//var linter = new Linter(con, rep);
|
||||||
|
var fragmentBuilder = new FragmentBuilder(rep, con.CompatibilityLevel);
|
||||||
|
var sqlStreamReaderBuilder = new SqlStreamReaderBuilder();
|
||||||
|
var bpmn = new BpmnDiagram();
|
||||||
|
|
||||||
using (StreamReader reader = new StreamReader(@"C:\Users\frost\Downloads\Telegram Desktop\tdostdetail.sql"))
|
var linter = new Linter(con, rep, fragmentBuilder, sqlStreamReaderBuilder);
|
||||||
|
|
||||||
|
var diagramer = new Diagramer(bpmn, fragmentBuilder, sqlStreamReaderBuilder);
|
||||||
|
|
||||||
|
using (StreamReader reader = new StreamReader(@"C:\Users\frost\Downloads\Telegram Desktop\test.sql"))
|
||||||
{
|
{
|
||||||
linter.Run("test.sql", reader.BaseStream);
|
linter.Run("test.sql", reader.BaseStream);
|
||||||
|
diagramer.Run("test.sql", reader.BaseStream);
|
||||||
}
|
}
|
||||||
|
|
||||||
//linter.Run(@"C:\Users\frost\Desktop\DISTR-2599\test.sql");
|
//linter.Run(@"C:\Users\frost\Desktop\DISTR-2599\test.sql");
|
||||||
|
|
||||||
rep.SaveReport(@"C:\Users\frost\Downloads\Telegram Desktop\test.html");
|
var formatter = new HtmlReportFormatter_v2();
|
||||||
|
var content = formatter.Format(rep.Violations, null);
|
||||||
|
|
||||||
|
File.WriteAllText(@"C:\Users\frost\Downloads\Telegram Desktop\test.html", content);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,14 +55,14 @@ public abstract class BaseRuleVisitor : TSqlFragmentVisitor, IRule
|
|||||||
_violations.Add(violation);
|
_violations.Add(violation);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void AddViolation(string RuleName, string Message, int Line, int Column)
|
protected void AddViolation(string RuleName, string Template, int Line, int Column, params string[] param)
|
||||||
{
|
{
|
||||||
_violations.Add(new(RuleName, Message, Line, Column));
|
_violations.Add(new(RuleName, Template, Line, Column, param));
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void AddViolation(TSqlFragment node, params string[] param)
|
protected void AddViolation(TSqlFragment node, params string[] param)
|
||||||
{
|
{
|
||||||
AddViolation(Name, this.GetText(param), GetLineNumber(node), GetColumnNumber(node));
|
_violations.Add(new(this.Name, this.Text, GetLineNumber(node), GetColumnNumber(node), param));
|
||||||
}
|
}
|
||||||
|
|
||||||
protected string GetText(params string[] param)
|
protected string GetText(params string[] param)
|
||||||
|
|||||||
@@ -4,5 +4,5 @@ public interface IReporter : IBaseReporter
|
|||||||
{
|
{
|
||||||
void ReportViolation(IRuleViolation violation);
|
void ReportViolation(IRuleViolation violation);
|
||||||
|
|
||||||
void ReportViolation(string fileName, int line, int column, RuleViolationSeverity severity, string ruleName, string violationText);
|
void ReportViolation(string fileName, int line, int column, RuleViolationSeverity severity, string ruleName, string template, params string[] param);
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
namespace SQLLinter.Common
|
namespace SQLLinter.Common
|
||||||
{
|
{
|
||||||
public record Violation(string RuleName, string Message, int Line, int Column);
|
public record Violation(string RuleName, string Template, int Line, int Column, string[] Params);
|
||||||
}
|
}
|
||||||
|
|||||||
9
SQLLinter/Core/Interfaces/ISqlDiagram.cs
Normal file
9
SQLLinter/Core/Interfaces/ISqlDiagram.cs
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
|
||||||
|
namespace SQLLinter.Core.Interfaces;
|
||||||
|
|
||||||
|
public interface ISqlDiagramProcessor
|
||||||
|
{
|
||||||
|
void ProcessList(List<string> filePaths);
|
||||||
|
void ProcessList(Dictionary<string, Stream> files);
|
||||||
|
void ProcessPath(string path);
|
||||||
|
}
|
||||||
41
SQLLinter/Diagramer.cs
Normal file
41
SQLLinter/Diagramer.cs
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
using SQLLinter.Common.Helpers;
|
||||||
|
using SQLLinter.Core.Interfaces;
|
||||||
|
using SQLLinter.Infrastructure.Diagram;
|
||||||
|
using SQLLinter.Infrastructure.Interfaces;
|
||||||
|
|
||||||
|
namespace SQLLinter;
|
||||||
|
|
||||||
|
public class Diagramer
|
||||||
|
{
|
||||||
|
private ISqlDiagramProcessor _diagramProcessor;
|
||||||
|
|
||||||
|
public Diagramer(BpmnDiagram bpmnDiagram
|
||||||
|
, IFragmentBuilder fragmentBuilder
|
||||||
|
, ISqlStreamReaderBuilder sqlStreamReaderBuilder
|
||||||
|
)
|
||||||
|
{
|
||||||
|
_diagramProcessor = new SqlDiagramProcessor(fragmentBuilder, bpmnDiagram, sqlStreamReaderBuilder);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Run(string filePath)
|
||||||
|
{
|
||||||
|
this.Run([filePath]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Run(List<string> filePaths)
|
||||||
|
{
|
||||||
|
List<string> files = FileHelpers.FindFilesWithMask(filePaths);
|
||||||
|
|
||||||
|
_diagramProcessor.ProcessList(filePaths);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Run(string fileName, Stream fileReader)
|
||||||
|
{
|
||||||
|
Run(new Dictionary<string, Stream> { [fileName] = fileReader });
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Run(Dictionary<string, Stream> files)
|
||||||
|
{
|
||||||
|
_diagramProcessor.ProcessList(files);
|
||||||
|
}
|
||||||
|
}
|
||||||
980
SQLLinter/Infrastructure/Diagram/BpmnBuilder.cs
Normal file
980
SQLLinter/Infrastructure/Diagram/BpmnBuilder.cs
Normal file
@@ -0,0 +1,980 @@
|
|||||||
|
using Microsoft.SqlServer.TransactSql.ScriptDom;
|
||||||
|
using SQLLinter.Core;
|
||||||
|
|
||||||
|
namespace SQLLinter.Infrastructure.Diagram;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Билдер диаграммы BPMN из T-SQL AST
|
||||||
|
/// </summary>
|
||||||
|
public static class BpmnBuilder
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Сборка диаграммы BPMN из T-SQL AST
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fragment"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static BpmnDiagram Build(TSqlFragment fragment) => Build(fragment, new());
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Сборка диаграммы BPMN из T-SQL AST с использованием существующей диаграммы
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fragment"></param>
|
||||||
|
/// <param name="diagram"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static BpmnDiagram Build(TSqlFragment fragment, BpmnDiagram diagram)
|
||||||
|
{
|
||||||
|
var visitor = new BpmnVisitor(diagram);
|
||||||
|
fragment.Accept(visitor);
|
||||||
|
visitor.Diagram.AddMissingProcessEdges();
|
||||||
|
return visitor.Diagram;
|
||||||
|
}
|
||||||
|
|
||||||
|
private class BpmnVisitor : TSqlFragmentVisitor
|
||||||
|
{
|
||||||
|
public BpmnDiagram Diagram { get; } = new BpmnDiagram();
|
||||||
|
|
||||||
|
private Dictionary<string, string> _lastNodeByProcess = new();
|
||||||
|
private Stack<BpmnProcess> _processStack = new Stack<BpmnProcess>();
|
||||||
|
private int _nodeCounter = 0;
|
||||||
|
private const int MaxConditionLength = 50;
|
||||||
|
|
||||||
|
public BpmnVisitor() : this(new BpmnDiagram()) { }
|
||||||
|
|
||||||
|
public BpmnVisitor(BpmnDiagram diagram)
|
||||||
|
{
|
||||||
|
Diagram = diagram;
|
||||||
|
_nodeCounter = diagram.Processes.Sum(p => p.Nodes.Count()) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private string NewId() => "n" + (_nodeCounter++);
|
||||||
|
|
||||||
|
private void AddNode(BpmnProcess proc, BpmnNode node, string? edgeLabel = null)
|
||||||
|
{
|
||||||
|
if (proc == null) return;
|
||||||
|
|
||||||
|
if (string.IsNullOrEmpty(node.Id)) node.Id = NewId();
|
||||||
|
proc.Nodes.Add(node);
|
||||||
|
|
||||||
|
if (_lastNodeByProcess.TryGetValue(proc.Id, out var last) && !string.IsNullOrEmpty(last))
|
||||||
|
{
|
||||||
|
proc.Edges.Add(new BpmnEdge
|
||||||
|
{
|
||||||
|
From = last,
|
||||||
|
To = node.Id,
|
||||||
|
Label = edgeLabel ?? string.Empty
|
||||||
|
});
|
||||||
|
}
|
||||||
|
_lastNodeByProcess[proc.Id] = node.Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void AddNodeToCurrent(string label, BpmnNodeType type, Dictionary<string, string>? properties = null)
|
||||||
|
{
|
||||||
|
if (_processStack.Count == 0) return;
|
||||||
|
var currentProcess = _processStack.Peek();
|
||||||
|
var node = new BpmnNode
|
||||||
|
{
|
||||||
|
Id = NewId(),
|
||||||
|
Label = label,
|
||||||
|
Type = type
|
||||||
|
};
|
||||||
|
|
||||||
|
if (properties != null)
|
||||||
|
{
|
||||||
|
node.Properties = new Dictionary<string, string>(properties);
|
||||||
|
}
|
||||||
|
|
||||||
|
AddNode(currentProcess, node);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ProcessProcedureOrFunction(TSqlStatement node, string objectType)
|
||||||
|
{
|
||||||
|
// Извлечение имени объекта на основе AST
|
||||||
|
var name = FindSchemaObjectName(node) ?? ($"{objectType}" + Diagram.Processes.Count);
|
||||||
|
var pid = SanitizeId(name);
|
||||||
|
var proc = new BpmnProcess { Id = pid, Name = $"{name} ({objectType})" };
|
||||||
|
|
||||||
|
// создать начальный узел
|
||||||
|
var start = new BpmnNode { Id = pid + "_start", Label = "Начало", Type = BpmnNodeType.Start };
|
||||||
|
proc.Nodes.Add(start);
|
||||||
|
_lastNodeByProcess[proc.Id] = start.Id;
|
||||||
|
|
||||||
|
Diagram.Processes.Add(proc);
|
||||||
|
|
||||||
|
// Помещаем процесс в стек
|
||||||
|
_processStack.Push(proc);
|
||||||
|
|
||||||
|
// Используем специальный visitor для поиска StatementList
|
||||||
|
var statementCollector = new StatementListCollector();
|
||||||
|
node.Accept(statementCollector);
|
||||||
|
|
||||||
|
if (statementCollector.FoundStatementList != null)
|
||||||
|
{
|
||||||
|
statementCollector.FoundStatementList.Accept(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
// после посещения тела добавляем конечный узел
|
||||||
|
var end = new BpmnNode { Id = pid + "_end", Label = "Конец", Type = BpmnNodeType.End };
|
||||||
|
AddNode(proc, end);
|
||||||
|
|
||||||
|
// Убираем процесс из стека
|
||||||
|
_processStack.Pop();
|
||||||
|
}
|
||||||
|
|
||||||
|
private class StatementListCollector : TSqlFragmentVisitor
|
||||||
|
{
|
||||||
|
public StatementList? FoundStatementList { get; private set; }
|
||||||
|
|
||||||
|
public override void Visit(StatementList node)
|
||||||
|
{
|
||||||
|
if (FoundStatementList == null)
|
||||||
|
{
|
||||||
|
FoundStatementList = node;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void ExplicitVisit(CreateProcedureStatement node) => ProcessProcedureOrFunction(node, "процедура");
|
||||||
|
public override void ExplicitVisit(CreateOrAlterProcedureStatement node) => ProcessProcedureOrFunction(node, "процедура");
|
||||||
|
public override void ExplicitVisit(AlterProcedureStatement node) => ProcessProcedureOrFunction(node, "процедура");
|
||||||
|
|
||||||
|
public override void ExplicitVisit(CreateFunctionStatement node) => ProcessProcedureOrFunction(node, "функция");
|
||||||
|
public override void ExplicitVisit(CreateOrAlterFunctionStatement node) => ProcessProcedureOrFunction(node, "функция");
|
||||||
|
public override void ExplicitVisit(AlterFunctionStatement node) => ProcessProcedureOrFunction(node, "функция");
|
||||||
|
|
||||||
|
public override void ExplicitVisit(CreateTriggerStatement node) => ProcessProcedureOrFunction(node, "триггер");
|
||||||
|
public override void ExplicitVisit(CreateOrAlterTriggerStatement node) => ProcessProcedureOrFunction(node, "триггер");
|
||||||
|
public override void ExplicitVisit(AlterTriggerStatement node) => ProcessProcedureOrFunction(node, "триггер");
|
||||||
|
|
||||||
|
public override void Visit(ExecuteStatement node)
|
||||||
|
{
|
||||||
|
if (_processStack.Count == 0) return;
|
||||||
|
var currentProcess = _processStack.Peek();
|
||||||
|
|
||||||
|
// Извлечение на основе AST для вызываемого процесса
|
||||||
|
var called = FindProcedureNameFromExecute(node);
|
||||||
|
var label = called != null ? $"EXEC {called}" : "EXEC";
|
||||||
|
|
||||||
|
// задача в текущем процессе
|
||||||
|
var task = new BpmnNode { Id = NewId(), Label = label!, Type = BpmnNodeType.Subprocess, SubprocessId = called is null ? string.Empty : SanitizeId(called), };
|
||||||
|
AddNode(currentProcess, task);
|
||||||
|
|
||||||
|
// Обходим параметры вызова
|
||||||
|
if (node.ExecuteSpecification != null)
|
||||||
|
{
|
||||||
|
node.ExecuteSpecification.Accept(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(FunctionCall node)
|
||||||
|
{
|
||||||
|
if (_processStack.Count == 0) return;
|
||||||
|
var currentProcess = _processStack.Peek();
|
||||||
|
|
||||||
|
// Извлекаем имя функции
|
||||||
|
var functionName = node.FunctionName?.Value ?? "unknown";
|
||||||
|
var schemaPrefix = "";
|
||||||
|
|
||||||
|
// Проверяем, есть ли схема в имени через MultiPartIdentifier
|
||||||
|
if (node.CallTarget is MultiPartIdentifierCallTarget multiPartCallTarget)
|
||||||
|
{
|
||||||
|
schemaPrefix = GetMultiPartIdentifierName(multiPartCallTarget.MultiPartIdentifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
var fullFunctionName = !string.IsNullOrEmpty(schemaPrefix)
|
||||||
|
? $"{schemaPrefix}.{functionName}"
|
||||||
|
: functionName;
|
||||||
|
|
||||||
|
// Проверяем, является ли это пользовательской функцией
|
||||||
|
var isUserFunction = IsUserDefinedFunction(fullFunctionName);
|
||||||
|
|
||||||
|
var label = isUserFunction ? $"FUNC {fullFunctionName}" : $"{functionName}()";
|
||||||
|
var nodeType = isUserFunction ? BpmnNodeType.Subprocess : BpmnNodeType.Task;
|
||||||
|
|
||||||
|
var funcNode = new BpmnNode
|
||||||
|
{
|
||||||
|
Id = NewId(),
|
||||||
|
Label = label,
|
||||||
|
Type = nodeType,
|
||||||
|
SubprocessId = isUserFunction ? SanitizeId(fullFunctionName) : string.Empty,
|
||||||
|
};
|
||||||
|
AddNode(currentProcess, funcNode);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsUserDefinedFunction(string functionName)
|
||||||
|
{
|
||||||
|
// Проверяем, есть ли такая функция в нашей диаграмме
|
||||||
|
var isInDiagram = Diagram.Processes.Any(p =>
|
||||||
|
p.Name.Contains(functionName, StringComparison.OrdinalIgnoreCase));
|
||||||
|
|
||||||
|
// Если функция есть в диаграмме, это пользовательская функция
|
||||||
|
if (isInDiagram) return true;
|
||||||
|
|
||||||
|
// Если функция не встроенная и имеет префикс схемы (например, dbo.), считаем ее пользовательской
|
||||||
|
if (functionName.Contains('.') && !Constants.SystemFunctions.Contains(functionName.Split('.')[1]))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return !Constants.SystemFunctions.Contains(functionName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(IfStatement node)
|
||||||
|
{
|
||||||
|
if (_processStack.Count == 0) return;
|
||||||
|
var currentProcess = _processStack.Peek();
|
||||||
|
|
||||||
|
// Извлекаем условие IF
|
||||||
|
var conditionText = GetConditionText(node.Predicate);
|
||||||
|
var truncatedCondition = TruncateText(conditionText, MaxConditionLength);
|
||||||
|
|
||||||
|
var properties = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["condition"] = conditionText,
|
||||||
|
["condition_display"] = truncatedCondition
|
||||||
|
};
|
||||||
|
|
||||||
|
// Создаем узел шлюза для IF с условием
|
||||||
|
var gid = new BpmnNode
|
||||||
|
{
|
||||||
|
Id = NewId(),
|
||||||
|
Label = $"IF ({truncatedCondition})",
|
||||||
|
Type = BpmnNodeType.Gateway,
|
||||||
|
Properties = properties
|
||||||
|
};
|
||||||
|
AddNode(currentProcess, gid);
|
||||||
|
|
||||||
|
// Создаем узел ENDIF для объединения веток
|
||||||
|
var endid = new BpmnNode { Id = NewId(), Label = "ENDIF", Type = BpmnNodeType.Gateway };
|
||||||
|
currentProcess.Nodes.Add(endid);
|
||||||
|
|
||||||
|
// Обработка THEN ветки
|
||||||
|
if (node.ThenStatement != null)
|
||||||
|
{
|
||||||
|
_lastNodeByProcess[currentProcess.Id] = gid.Id;
|
||||||
|
var thenNode = new BpmnNode { Id = NewId(), Label = "THEN", Type = BpmnNodeType.Task };
|
||||||
|
AddNode(currentProcess, thenNode, edgeLabel: $"Да");
|
||||||
|
|
||||||
|
// Ручной обход THEN ветки
|
||||||
|
TraverseStatement(node.ThenStatement, currentProcess);
|
||||||
|
|
||||||
|
// После обработки THEN ветки добавляем край к ENDIF
|
||||||
|
if (_lastNodeByProcess.TryGetValue(currentProcess.Id, out var thenLastNode))
|
||||||
|
{
|
||||||
|
currentProcess.Edges.Add(new BpmnEdge
|
||||||
|
{
|
||||||
|
From = thenLastNode,
|
||||||
|
To = endid.Id
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Обработка ELSE ветки
|
||||||
|
if (node.ElseStatement != null)
|
||||||
|
{
|
||||||
|
_lastNodeByProcess[currentProcess.Id] = gid.Id;
|
||||||
|
var elseNode = new BpmnNode { Id = NewId(), Label = "ELSE", Type = BpmnNodeType.Task };
|
||||||
|
AddNode(currentProcess, elseNode, edgeLabel: $"Нет");
|
||||||
|
|
||||||
|
// Ручной обход ELSE ветки
|
||||||
|
TraverseStatement(node.ElseStatement, currentProcess);
|
||||||
|
|
||||||
|
// После обработки ELSE ветки добавляем край к ENDIF
|
||||||
|
if (_lastNodeByProcess.TryGetValue(currentProcess.Id, out var elseLastNode))
|
||||||
|
{
|
||||||
|
currentProcess.Edges.Add(new BpmnEdge
|
||||||
|
{
|
||||||
|
From = elseLastNode,
|
||||||
|
To = endid.Id
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Восстанавливаем последний узел после обработки IF
|
||||||
|
_lastNodeByProcess[currentProcess.Id] = endid.Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(MergeStatement node)
|
||||||
|
{
|
||||||
|
if (_processStack.Count == 0) return;
|
||||||
|
var currentProcess = _processStack.Peek();
|
||||||
|
|
||||||
|
var target = node.MergeSpecification.Target != null ? FindTargetNameForDml(node.MergeSpecification.Target) : "?";
|
||||||
|
var label = $"MERGE -> {target}";
|
||||||
|
|
||||||
|
AddNodeToCurrent(label, BpmnNodeType.Task);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(SetVariableStatement node)
|
||||||
|
{
|
||||||
|
if (_processStack.Count == 0) return;
|
||||||
|
var currentProcess = _processStack.Peek();
|
||||||
|
|
||||||
|
// Получаем имя переменной
|
||||||
|
var variableName = node.Variable?.Name ?? "?";
|
||||||
|
|
||||||
|
// Получаем текст выражения
|
||||||
|
var expressionText = GetExpressionText(node.Expression);
|
||||||
|
var truncatedExpression = TruncateText(expressionText, MaxConditionLength);
|
||||||
|
|
||||||
|
// Определяем оператор присваивания на основе AssignmentKind
|
||||||
|
string assignmentOp = "=";
|
||||||
|
|
||||||
|
assignmentOp = node.AssignmentKind switch
|
||||||
|
{
|
||||||
|
AssignmentKind.Equals => "=",
|
||||||
|
AssignmentKind.AddEquals => "+=",
|
||||||
|
AssignmentKind.SubtractEquals => "-=",
|
||||||
|
AssignmentKind.MultiplyEquals => "*=",
|
||||||
|
AssignmentKind.DivideEquals => "/=",
|
||||||
|
AssignmentKind.ModEquals => "%=",
|
||||||
|
AssignmentKind.BitwiseAndEquals => "&=",
|
||||||
|
AssignmentKind.BitwiseOrEquals => "|=",
|
||||||
|
AssignmentKind.BitwiseXorEquals => "^=",
|
||||||
|
_ => "="
|
||||||
|
};
|
||||||
|
|
||||||
|
// Проверяем, содержит ли выражение вызов функции
|
||||||
|
var containsFunctionCall = false;
|
||||||
|
if (node.Expression != null)
|
||||||
|
{
|
||||||
|
var functionFinder = new FunctionCallFinder();
|
||||||
|
node.Expression.Accept(functionFinder);
|
||||||
|
containsFunctionCall = functionFinder.FunctionCalls.Any(fc => IsUserDefinedFunction(fc.FunctionName?.Value ?? ""));
|
||||||
|
}
|
||||||
|
|
||||||
|
var label = $"SET {variableName} {assignmentOp} {truncatedExpression}";
|
||||||
|
|
||||||
|
var properties = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["variable"] = variableName,
|
||||||
|
["expression"] = expressionText,
|
||||||
|
["expression_display"] = truncatedExpression,
|
||||||
|
["assignment_kind"] = node.AssignmentKind.ToString(),
|
||||||
|
["contains_function_call"] = containsFunctionCall.ToString()
|
||||||
|
};
|
||||||
|
|
||||||
|
AddNodeToCurrent(label, BpmnNodeType.Task, properties);
|
||||||
|
|
||||||
|
// Обходим выражение для поиска вызовов функций
|
||||||
|
if (node.Expression != null)
|
||||||
|
{
|
||||||
|
node.Expression.Accept(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(SetCommandStatement node)
|
||||||
|
{
|
||||||
|
if (_processStack.Count == 0) return;
|
||||||
|
var currentProcess = _processStack.Peek();
|
||||||
|
|
||||||
|
var commandText = GetCommandText(node);
|
||||||
|
var truncatedCommand = TruncateText(commandText, MaxConditionLength);
|
||||||
|
|
||||||
|
var label = $"SET {truncatedCommand}";
|
||||||
|
|
||||||
|
var properties = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["command"] = commandText,
|
||||||
|
["command_display"] = truncatedCommand
|
||||||
|
};
|
||||||
|
|
||||||
|
AddNodeToCurrent(label, BpmnNodeType.Task, properties);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(GoToStatement node)
|
||||||
|
{
|
||||||
|
if (_processStack.Count == 0) return;
|
||||||
|
var currentProcess = _processStack.Peek();
|
||||||
|
|
||||||
|
var label = node.LabelName?.Value ?? "?";
|
||||||
|
var gotoNode = new BpmnNode
|
||||||
|
{
|
||||||
|
Id = NewId(),
|
||||||
|
Label = $"GOTO {label}",
|
||||||
|
Type = BpmnNodeType.Task
|
||||||
|
};
|
||||||
|
AddNode(currentProcess, gotoNode);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(TryCatchStatement node)
|
||||||
|
{
|
||||||
|
if (_processStack.Count == 0) return;
|
||||||
|
var currentProcess = _processStack.Peek();
|
||||||
|
|
||||||
|
var tryNode = new BpmnNode { Id = NewId(), Label = "TRY", Type = BpmnNodeType.Gateway };
|
||||||
|
var catchNode = new BpmnNode { Id = NewId(), Label = "CATCH", Type = BpmnNodeType.Gateway };
|
||||||
|
var endTryCatch = new BpmnNode { Id = NewId(), Label = "END TRY/CATCH", Type = BpmnNodeType.Gateway };
|
||||||
|
|
||||||
|
AddNode(currentProcess, tryNode);
|
||||||
|
currentProcess.Nodes.Add(catchNode);
|
||||||
|
currentProcess.Nodes.Add(endTryCatch);
|
||||||
|
|
||||||
|
// TRY блок
|
||||||
|
if (node.TryStatements != null)
|
||||||
|
{
|
||||||
|
_lastNodeByProcess[currentProcess.Id] = tryNode.Id;
|
||||||
|
foreach (var statement in node.TryStatements.Statements)
|
||||||
|
{
|
||||||
|
statement.Accept(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ребро от последнего узла TRY к endTryCatch
|
||||||
|
if (_lastNodeByProcess.TryGetValue(currentProcess.Id, out var tryLast))
|
||||||
|
{
|
||||||
|
currentProcess.Edges.Add(new BpmnEdge
|
||||||
|
{
|
||||||
|
From = tryLast,
|
||||||
|
To = endTryCatch.Id
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CATCH блок
|
||||||
|
if (node.CatchStatements != null)
|
||||||
|
{
|
||||||
|
_lastNodeByProcess[currentProcess.Id] = catchNode.Id;
|
||||||
|
currentProcess.Edges.Add(new BpmnEdge
|
||||||
|
{
|
||||||
|
From = tryNode.Id,
|
||||||
|
To = catchNode.Id,
|
||||||
|
Label = "Ошибка"
|
||||||
|
});
|
||||||
|
|
||||||
|
foreach (var statement in node.CatchStatements.Statements)
|
||||||
|
{
|
||||||
|
statement.Accept(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ребро от последнего узла CATCH к endTryCatch
|
||||||
|
if (_lastNodeByProcess.TryGetValue(currentProcess.Id, out var catchLast))
|
||||||
|
{
|
||||||
|
currentProcess.Edges.Add(new BpmnEdge
|
||||||
|
{
|
||||||
|
From = catchLast,
|
||||||
|
To = endTryCatch.Id
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_lastNodeByProcess[currentProcess.Id] = endTryCatch.Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(WhileStatement node)
|
||||||
|
{
|
||||||
|
if (_processStack.Count == 0) return;
|
||||||
|
var currentProcess = _processStack.Peek();
|
||||||
|
|
||||||
|
// Извлекаем условие WHILE
|
||||||
|
var conditionText = GetConditionText(node.Predicate);
|
||||||
|
var truncatedCondition = TruncateText(conditionText, MaxConditionLength);
|
||||||
|
|
||||||
|
var properties = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["condition"] = conditionText,
|
||||||
|
["condition_display"] = truncatedCondition,
|
||||||
|
["loop_type"] = "WHILE"
|
||||||
|
};
|
||||||
|
|
||||||
|
// Узел начала цикла
|
||||||
|
var loopStart = new BpmnNode
|
||||||
|
{
|
||||||
|
Id = NewId(),
|
||||||
|
Label = $"WHILE ({truncatedCondition})",
|
||||||
|
Type = BpmnNodeType.Hexagon,
|
||||||
|
Properties = properties
|
||||||
|
};
|
||||||
|
AddNode(currentProcess, loopStart);
|
||||||
|
|
||||||
|
// Сохраняем текущий последний узел
|
||||||
|
var savedLastNode = _lastNodeByProcess[currentProcess.Id];
|
||||||
|
|
||||||
|
// Обработка тела цикла
|
||||||
|
if (node.Statement != null)
|
||||||
|
{
|
||||||
|
// Добавляем ребро от gateway к первому узлу тела цикла
|
||||||
|
var bodyStartNode = new BpmnNode
|
||||||
|
{
|
||||||
|
Id = NewId(),
|
||||||
|
Label = "Тело цикла",
|
||||||
|
Type = BpmnNodeType.Task
|
||||||
|
};
|
||||||
|
AddNode(currentProcess, bodyStartNode, "Вход");
|
||||||
|
|
||||||
|
// Обход тела цикла
|
||||||
|
TraverseStatement(node.Statement, currentProcess);
|
||||||
|
|
||||||
|
// Добавляем ребро возврата в начало цикла от последнего узла тела
|
||||||
|
if (_lastNodeByProcess.TryGetValue(currentProcess.Id, out var loopBodyLast))
|
||||||
|
{
|
||||||
|
currentProcess.Edges.Add(new BpmnEdge
|
||||||
|
{
|
||||||
|
From = loopBodyLast,
|
||||||
|
To = loopStart.Id,
|
||||||
|
Label = "Повтор"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Узел конца цикла (выход, когда условие ложно)
|
||||||
|
var loopEnd = new BpmnNode { Id = NewId(), Label = "END WHILE", Type = BpmnNodeType.Gateway };
|
||||||
|
currentProcess.Nodes.Add(loopEnd);
|
||||||
|
|
||||||
|
// Ребро выхода из цикла
|
||||||
|
currentProcess.Edges.Add(new BpmnEdge
|
||||||
|
{
|
||||||
|
From = loopStart.Id,
|
||||||
|
To = loopEnd.Id,
|
||||||
|
Label = "Выход"
|
||||||
|
});
|
||||||
|
|
||||||
|
// Восстанавливаем последний узел
|
||||||
|
_lastNodeByProcess[currentProcess.Id] = loopEnd.Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(BreakStatement node)
|
||||||
|
{
|
||||||
|
if (_processStack.Count == 0) return;
|
||||||
|
var currentProcess = _processStack.Peek();
|
||||||
|
|
||||||
|
var breakNode = new BpmnNode
|
||||||
|
{
|
||||||
|
Id = NewId(),
|
||||||
|
Label = "BREAK",
|
||||||
|
Type = BpmnNodeType.Task
|
||||||
|
};
|
||||||
|
AddNode(currentProcess, breakNode);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(ContinueStatement node)
|
||||||
|
{
|
||||||
|
if (_processStack.Count == 0) return;
|
||||||
|
var currentProcess = _processStack.Peek();
|
||||||
|
|
||||||
|
var continueNode = new BpmnNode
|
||||||
|
{
|
||||||
|
Id = NewId(),
|
||||||
|
Label = "CONTINUE",
|
||||||
|
Type = BpmnNodeType.Task
|
||||||
|
};
|
||||||
|
AddNode(currentProcess, continueNode);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(ReturnStatement node)
|
||||||
|
{
|
||||||
|
if (_processStack.Count == 0) return;
|
||||||
|
var currentProcess = _processStack.Peek();
|
||||||
|
|
||||||
|
var label = "RETURN";
|
||||||
|
if (node.Expression != null)
|
||||||
|
{
|
||||||
|
var exprText = GetExpressionText(node.Expression);
|
||||||
|
var truncatedExpr = TruncateText(exprText, MaxConditionLength);
|
||||||
|
label = $"RETURN {truncatedExpr}";
|
||||||
|
}
|
||||||
|
|
||||||
|
var returnNode = new BpmnNode
|
||||||
|
{
|
||||||
|
Id = NewId(),
|
||||||
|
Label = label,
|
||||||
|
Type = BpmnNodeType.Task
|
||||||
|
};
|
||||||
|
AddNode(currentProcess, returnNode);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(DeclareVariableStatement node)
|
||||||
|
{
|
||||||
|
if (_processStack.Count == 0) return;
|
||||||
|
var currentProcess = _processStack.Peek();
|
||||||
|
|
||||||
|
var declarations = new List<string>();
|
||||||
|
foreach (var declaration in node.Declarations)
|
||||||
|
{
|
||||||
|
var varName = declaration.VariableName?.Value ?? "?";
|
||||||
|
var dataType = declaration.DataType?.Name?.BaseIdentifier?.Value ?? "?";
|
||||||
|
declarations.Add($"{varName} {dataType}");
|
||||||
|
}
|
||||||
|
|
||||||
|
var label = "DECLARE";
|
||||||
|
if (declarations.Count > 0)
|
||||||
|
{
|
||||||
|
var declText = string.Join(", ", declarations);
|
||||||
|
var truncatedDecl = TruncateText(declText, MaxConditionLength);
|
||||||
|
label = $"DECLARE {truncatedDecl}";
|
||||||
|
}
|
||||||
|
|
||||||
|
AddNodeToCurrent(label, BpmnNodeType.Task);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(BeginEndBlockStatement node)
|
||||||
|
{
|
||||||
|
if (_processStack.Count == 0) return;
|
||||||
|
var currentProcess = _processStack.Peek();
|
||||||
|
|
||||||
|
// Просто обходим все операторы внутри блока
|
||||||
|
if (node.StatementList != null)
|
||||||
|
{
|
||||||
|
foreach (var statement in node.StatementList.Statements)
|
||||||
|
{
|
||||||
|
statement.Accept(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void TraverseStatement(TSqlFragment statement, BpmnProcess process)
|
||||||
|
{
|
||||||
|
if (statement is StatementList statementList)
|
||||||
|
{
|
||||||
|
foreach (var stmt in statementList.Statements)
|
||||||
|
{
|
||||||
|
stmt.Accept(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (statement is BeginEndBlockStatement beginEnd)
|
||||||
|
{
|
||||||
|
// Для блоков BEGIN...END обходим внутренние statements
|
||||||
|
if (beginEnd.StatementList != null)
|
||||||
|
{
|
||||||
|
foreach (var stmt in beginEnd.StatementList.Statements)
|
||||||
|
{
|
||||||
|
stmt.Accept(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
statement.Accept(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(SelectStatement node)
|
||||||
|
{
|
||||||
|
if (_processStack.Count == 0) return;
|
||||||
|
var currentProcess = _processStack.Peek();
|
||||||
|
|
||||||
|
var label = "SELECT";
|
||||||
|
if (node.QueryExpression is QuerySpecification qs && qs.SelectElements != null)
|
||||||
|
{
|
||||||
|
label = $"SELECT ({qs.SelectElements.Count} полей)";
|
||||||
|
}
|
||||||
|
|
||||||
|
AddNodeToCurrent(label, BpmnNodeType.Task);
|
||||||
|
|
||||||
|
// Обходим все элементы SELECT для поиска вызовов функций
|
||||||
|
if (node.QueryExpression != null)
|
||||||
|
{
|
||||||
|
node.QueryExpression.Accept(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(InsertStatement node)
|
||||||
|
{
|
||||||
|
if (_processStack.Count == 0) return;
|
||||||
|
var currentProcess = _processStack.Peek();
|
||||||
|
|
||||||
|
var target = FindTargetNameForDml(node);
|
||||||
|
var label = "INSERT" + (string.IsNullOrEmpty(target) ? string.Empty : $" -> {target}");
|
||||||
|
AddNodeToCurrent(label, BpmnNodeType.Task);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(UpdateStatement node)
|
||||||
|
{
|
||||||
|
if (_processStack.Count == 0) return;
|
||||||
|
var currentProcess = _processStack.Peek();
|
||||||
|
|
||||||
|
var target = FindTargetNameForDml(node);
|
||||||
|
var label = "UPDATE" + (string.IsNullOrEmpty(target) ? string.Empty : $" -> {target}");
|
||||||
|
AddNodeToCurrent(label, BpmnNodeType.Task);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(DeleteStatement node)
|
||||||
|
{
|
||||||
|
if (_processStack.Count == 0) return;
|
||||||
|
var currentProcess = _processStack.Peek();
|
||||||
|
|
||||||
|
var target = FindTargetNameForDml(node);
|
||||||
|
var label = "DELETE" + (string.IsNullOrEmpty(target) ? string.Empty : $" -> {target}");
|
||||||
|
AddNodeToCurrent(label, BpmnNodeType.Task);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Вспомогательные методы для извлечения текста
|
||||||
|
private string GetConditionText(BooleanExpression expression)
|
||||||
|
{
|
||||||
|
if (expression == null) return "";
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Пробуем получить через ScriptTokenStream
|
||||||
|
var tokens = expression.ScriptTokenStream;
|
||||||
|
if (tokens != null && expression.FirstTokenIndex >= 0 &&
|
||||||
|
expression.LastTokenIndex >= expression.FirstTokenIndex)
|
||||||
|
{
|
||||||
|
var text = string.Join("",
|
||||||
|
tokens.Skip(expression.FirstTokenIndex)
|
||||||
|
.Take(expression.LastTokenIndex - expression.FirstTokenIndex + 1)
|
||||||
|
.Select(t => t.Text));
|
||||||
|
return text.Trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback: используем ToString()
|
||||||
|
return expression.ToString()?.Trim() ?? "";
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private string GetExpressionText(ScalarExpression expression)
|
||||||
|
{
|
||||||
|
if (expression == null) return "";
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var tokens = expression.ScriptTokenStream;
|
||||||
|
if (tokens != null && expression.FirstTokenIndex >= 0 && expression.LastTokenIndex >= expression.FirstTokenIndex)
|
||||||
|
{
|
||||||
|
var text = string.Join("",
|
||||||
|
tokens.Skip(expression.FirstTokenIndex)
|
||||||
|
.Take(expression.LastTokenIndex - expression.FirstTokenIndex + 1)
|
||||||
|
.Select(t => t.Text));
|
||||||
|
return text.Trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// Игнорируем ошибки парсинга
|
||||||
|
}
|
||||||
|
|
||||||
|
return expression.ToString() ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
|
private string GetCommandText(SetCommandStatement node)
|
||||||
|
{
|
||||||
|
if (node == null) return "";
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var tokens = node.ScriptTokenStream;
|
||||||
|
if (tokens != null && node.FirstTokenIndex >= 0 && node.LastTokenIndex >= node.FirstTokenIndex)
|
||||||
|
{
|
||||||
|
var text = string.Join("",
|
||||||
|
tokens.Skip(node.FirstTokenIndex)
|
||||||
|
.Take(node.LastTokenIndex - node.FirstTokenIndex + 1)
|
||||||
|
.Select(t => t.Text));
|
||||||
|
return text.Trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// Игнорируем ошибки парсинга
|
||||||
|
}
|
||||||
|
|
||||||
|
return node.ToString() ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
|
private string TruncateText(string text, int maxLength)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(text)) return "";
|
||||||
|
if (text.Length <= maxLength) return text;
|
||||||
|
|
||||||
|
return text.Substring(0, maxLength - 3) + "...";
|
||||||
|
}
|
||||||
|
|
||||||
|
// AST helpers
|
||||||
|
private static string? FindSchemaObjectName(TSqlFragment fragment)
|
||||||
|
{
|
||||||
|
var finder = new SchemaNameFinder();
|
||||||
|
fragment.Accept(finder);
|
||||||
|
return finder.FoundName;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? FindProcedureNameFromExecute(ExecuteStatement node)
|
||||||
|
{
|
||||||
|
// Prefer ProcedureReference inside the statement
|
||||||
|
var finder = new ProcedureReferenceFinder();
|
||||||
|
node.Accept(finder);
|
||||||
|
return finder.FoundName;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? FindTargetNameForDml(TSqlFragment fragment)
|
||||||
|
{
|
||||||
|
var finder = new TargetTableFinder();
|
||||||
|
fragment.Accept(finder);
|
||||||
|
return finder.FoundName;
|
||||||
|
}
|
||||||
|
|
||||||
|
private class SchemaNameFinder : TSqlFragmentVisitor
|
||||||
|
{
|
||||||
|
public string? FoundName { get; private set; }
|
||||||
|
|
||||||
|
public override void Visit(SchemaObjectName node)
|
||||||
|
{
|
||||||
|
if (FoundName == null)
|
||||||
|
{
|
||||||
|
FoundName = GetSchemaObjectName(node);
|
||||||
|
}
|
||||||
|
base.Visit(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(ProcedureReferenceName node)
|
||||||
|
{
|
||||||
|
if (FoundName == null && node.ProcedureReference?.Name != null)
|
||||||
|
{
|
||||||
|
FoundName = GetSchemaObjectName(node.ProcedureReference.Name);
|
||||||
|
}
|
||||||
|
base.Visit(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string GetSchemaObjectName(SchemaObjectName node)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (node.Identifiers != null && node.Identifiers.Count > 0)
|
||||||
|
{
|
||||||
|
return string.Join('.', node.Identifiers.Select(id => "[" + id.Value + "]"));
|
||||||
|
}
|
||||||
|
return "[" + (node.ToString() ?? "unknown") + "]";
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return "[unknown]";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class ProcedureReferenceFinder : TSqlFragmentVisitor
|
||||||
|
{
|
||||||
|
public string? FoundName { get; private set; }
|
||||||
|
public override void Visit(ProcedureReference node)
|
||||||
|
{
|
||||||
|
if (FoundName == null)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (node.Name != null)
|
||||||
|
{
|
||||||
|
if (node.Name.Identifiers != null && node.Name.Identifiers.Count > 0)
|
||||||
|
FoundName = string.Join('.', node.Name.Identifiers.Select(id => "[" + id.Value + "]"));
|
||||||
|
else
|
||||||
|
FoundName = "[" + node.Name.ToString() + "]";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
FoundName = "[" + node.Name.ToString() + "]";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
base.Visit(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(ExecuteSpecification node)
|
||||||
|
{
|
||||||
|
base.Visit(node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class TargetTableFinder : TSqlFragmentVisitor
|
||||||
|
{
|
||||||
|
public string? FoundName { get; private set; }
|
||||||
|
private int _bestDepth = int.MaxValue;
|
||||||
|
private int _depth = 0;
|
||||||
|
|
||||||
|
public override void Visit(TSqlFragment node)
|
||||||
|
{
|
||||||
|
_depth++;
|
||||||
|
base.Visit(node);
|
||||||
|
_depth--;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(NamedTableReference node)
|
||||||
|
{
|
||||||
|
if (node == null) return;
|
||||||
|
int depth = _depth;
|
||||||
|
if (depth < _bestDepth)
|
||||||
|
{
|
||||||
|
_bestDepth = depth;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (node.SchemaObject != null && node.SchemaObject.Identifiers != null && node.SchemaObject.Identifiers.Count > 0)
|
||||||
|
FoundName = string.Join('.', node.SchemaObject.Identifiers.Select(id => "[" + id.Value + "]"));
|
||||||
|
else
|
||||||
|
FoundName = "[" + node.SchemaObject?.ToString() ?? node.ToString() + "]";
|
||||||
|
|
||||||
|
if (node.Alias != null && !string.IsNullOrWhiteSpace(node.Alias.Value))
|
||||||
|
FoundName += " AS [" + node.Alias.Value + "]";
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
FoundName = "[" + node.SchemaObject?.ToString() ?? node.ToString() + "]";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
base.Visit(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(VariableTableReference node)
|
||||||
|
{
|
||||||
|
if (node == null) return;
|
||||||
|
int depth = _depth;
|
||||||
|
if (depth < _bestDepth)
|
||||||
|
{
|
||||||
|
_bestDepth = depth;
|
||||||
|
FoundName = node.Variable?.ToString();
|
||||||
|
}
|
||||||
|
base.Visit(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(QueryDerivedTable node)
|
||||||
|
{
|
||||||
|
if (node == null) return;
|
||||||
|
int depth = _depth;
|
||||||
|
if (depth < _bestDepth && node.Alias != null && !string.IsNullOrWhiteSpace(node.Alias.Value))
|
||||||
|
{
|
||||||
|
_bestDepth = depth;
|
||||||
|
FoundName = node.Alias.Value + " (derived)";
|
||||||
|
}
|
||||||
|
|
||||||
|
// still traverse inside
|
||||||
|
base.Visit(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Visit(CommonTableExpression node)
|
||||||
|
{
|
||||||
|
// CTE definitions: prefer not to pick CTE as target unless no other table found
|
||||||
|
base.Visit(node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string SanitizeId(string s)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(s)) return "id";
|
||||||
|
var sb = new System.Text.StringBuilder();
|
||||||
|
foreach (var ch in s)
|
||||||
|
{
|
||||||
|
if (char.IsLetterOrDigit(ch)) sb.Append(ch);
|
||||||
|
else sb.Append('_');
|
||||||
|
}
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private class FunctionCallFinder : TSqlFragmentVisitor
|
||||||
|
{
|
||||||
|
public List<FunctionCall> FunctionCalls { get; } = new List<FunctionCall>();
|
||||||
|
|
||||||
|
public override void Visit(FunctionCall node)
|
||||||
|
{
|
||||||
|
FunctionCalls.Add(node);
|
||||||
|
base.Visit(node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private string GetMultiPartIdentifierName(MultiPartIdentifier identifier)
|
||||||
|
{
|
||||||
|
if (identifier != null && identifier.Identifiers != null && identifier.Identifiers.Count > 0)
|
||||||
|
{
|
||||||
|
return string.Join(".", identifier.Identifiers.Select(id => id.Value));
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
95
SQLLinter/Infrastructure/Diagram/MermaidRenderer.cs
Normal file
95
SQLLinter/Infrastructure/Diagram/MermaidRenderer.cs
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace SQLLinter.Infrastructure.Diagram;
|
||||||
|
|
||||||
|
public static class MermaidRenderer
|
||||||
|
{
|
||||||
|
public static string ToMermaidContent(BpmnDiagram diagram)
|
||||||
|
{
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
sb.AppendLine("flowchart TB");
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Рендер каждого процесса как subgraph
|
||||||
|
// -----------------------------------------
|
||||||
|
foreach (var proc in diagram.Processes)
|
||||||
|
{
|
||||||
|
var procId = SanitizeId(proc.Id);
|
||||||
|
sb.AppendLine($" subgraph {procId} [\"{Escape(proc.Name)}\"]");
|
||||||
|
sb.AppendLine(" direction TB");
|
||||||
|
|
||||||
|
foreach (var node in proc.Nodes)
|
||||||
|
{
|
||||||
|
var nid = SanitizeId(node.Id);
|
||||||
|
var label = Escape(node.Label);
|
||||||
|
|
||||||
|
label = node.Type switch
|
||||||
|
{
|
||||||
|
BpmnNodeType.Start => $@"((""{label}""))",
|
||||||
|
BpmnNodeType.Task => $@"[""{label}""]",
|
||||||
|
BpmnNodeType.Subprocess => $@"[[""{label}""]]",
|
||||||
|
BpmnNodeType.Gateway => $@"{{""{label}""}}",
|
||||||
|
BpmnNodeType.Hexagon => $@"{{{{""{label}""}}}}",
|
||||||
|
BpmnNodeType.End => $@"((""{label}""))",
|
||||||
|
_ => $@">""{label}""]"
|
||||||
|
};
|
||||||
|
|
||||||
|
sb.AppendLine($" {nid}{label}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Edges внутри процесса
|
||||||
|
foreach (var e in proc.Edges)
|
||||||
|
{
|
||||||
|
var from = SanitizeId(e.From);
|
||||||
|
var to = SanitizeId(e.To);
|
||||||
|
var arrow = e.ArrowType switch
|
||||||
|
{
|
||||||
|
BpmnArrowType.Dashed => "-.->",
|
||||||
|
_ => "-->",
|
||||||
|
};
|
||||||
|
var lbl = string.IsNullOrWhiteSpace(e.Label) ? string.Empty : $" |{Escape(e.Label)}|";
|
||||||
|
|
||||||
|
sb.AppendLine($" {from} {arrow}{lbl} {to}");
|
||||||
|
}
|
||||||
|
|
||||||
|
sb.AppendLine(" end");
|
||||||
|
sb.AppendLine();
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Рендер глобальных связей между процессами
|
||||||
|
// -----------------------------------------
|
||||||
|
foreach (var e in diagram.GlobalEdges)
|
||||||
|
{
|
||||||
|
var from = SanitizeId(e.From);
|
||||||
|
var to = SanitizeId(e.To);
|
||||||
|
var arrow = e.ArrowType switch
|
||||||
|
{
|
||||||
|
BpmnArrowType.Dashed => "-.->",
|
||||||
|
_ => "-->",
|
||||||
|
};
|
||||||
|
var lbl = string.IsNullOrWhiteSpace(e.Label) ? string.Empty : $" |{Escape(e.Label)}|";
|
||||||
|
sb.AppendLine($" {from} {arrow}{lbl} {to}");
|
||||||
|
}
|
||||||
|
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Escape(string s)
|
||||||
|
{
|
||||||
|
if (s == null) return string.Empty;
|
||||||
|
return s.Replace("\"", "\\\"").Replace("\n", " ").Replace("\r", " ");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string SanitizeId(string s)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(s)) return "id";
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
foreach (var ch in s)
|
||||||
|
{
|
||||||
|
if (char.IsLetterOrDigit(ch)) sb.Append(ch);
|
||||||
|
else sb.Append('_');
|
||||||
|
}
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
12
SQLLinter/Infrastructure/Diagram/Models/BpmnArrowType.cs
Normal file
12
SQLLinter/Infrastructure/Diagram/Models/BpmnArrowType.cs
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
namespace SQLLinter.Infrastructure.Diagram;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Типы связей между узлами BPMN
|
||||||
|
/// </summary>
|
||||||
|
public enum BpmnArrowType
|
||||||
|
{
|
||||||
|
/// <summary> Обычная связь </summary>
|
||||||
|
Default,
|
||||||
|
/// <summary> Пунктирная связь (например, для вызова подпроцесса) </summary>
|
||||||
|
Dashed,
|
||||||
|
}
|
||||||
13
SQLLinter/Infrastructure/Diagram/Models/BpmnDiagram.cs
Normal file
13
SQLLinter/Infrastructure/Diagram/Models/BpmnDiagram.cs
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
namespace SQLLinter.Infrastructure.Diagram;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Диаграмма BPMN, объединяющая процессы
|
||||||
|
/// </summary>
|
||||||
|
public class BpmnDiagram
|
||||||
|
{
|
||||||
|
/// <summary> Процессы диаграммы </summary>
|
||||||
|
public List<BpmnProcess> Processes { get; set; } = new();
|
||||||
|
|
||||||
|
/// <summary> Глобальные связи между процессами </summary>
|
||||||
|
public List<BpmnEdge> GlobalEdges { get; set; } = new();
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
namespace SQLLinter.Infrastructure.Diagram;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Расширения для диаграммы BPMN
|
||||||
|
/// </summary>
|
||||||
|
public static class BpmnDiagramExtensions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Добавления отсутсвующих связей между процессами и их подпроцессами
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="diagram"></param>
|
||||||
|
public static void AddMissingProcessEdges(this BpmnDiagram diagram)
|
||||||
|
{
|
||||||
|
foreach (var subprocess in diagram.Processes
|
||||||
|
.SelectMany(p => p.Nodes.Select(n => new { node = n, procId = p.Id }))
|
||||||
|
.Where(n => n.node.Type == BpmnNodeType.Subprocess && !string.IsNullOrEmpty(n.node.SubprocessId) && n.node.SubprocessId != n.procId)
|
||||||
|
.Select(n => n.node)
|
||||||
|
)
|
||||||
|
{
|
||||||
|
if (diagram.Processes.Any(p => p.Id == subprocess.SubprocessId)
|
||||||
|
&& !diagram.GlobalEdges.Any(t => t.From == subprocess.Id && t.To == subprocess.SubprocessId)
|
||||||
|
)
|
||||||
|
{
|
||||||
|
// Добавить пунктирный край от узла подпроцесса к началу подпроцесса
|
||||||
|
diagram.GlobalEdges.Add(new BpmnEdge
|
||||||
|
{
|
||||||
|
From = subprocess.Id,
|
||||||
|
To = subprocess.SubprocessId + "_start",
|
||||||
|
ArrowType = BpmnArrowType.Dashed,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
19
SQLLinter/Infrastructure/Diagram/Models/BpmnEdge.cs
Normal file
19
SQLLinter/Infrastructure/Diagram/Models/BpmnEdge.cs
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
namespace SQLLinter.Infrastructure.Diagram;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Связь между узлами BPMN
|
||||||
|
/// </summary>
|
||||||
|
public class BpmnEdge
|
||||||
|
{
|
||||||
|
/// <summary> Идентификатор узла-источника </summary>
|
||||||
|
public string From { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary> Идентификатор узла-приемника </summary>
|
||||||
|
public string To { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary> Метка/название связи </summary>
|
||||||
|
public string Label { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary> Тип стрелки связи </summary>
|
||||||
|
public BpmnArrowType ArrowType { get; set; } = BpmnArrowType.Default;
|
||||||
|
}
|
||||||
22
SQLLinter/Infrastructure/Diagram/Models/BpmnNode.cs
Normal file
22
SQLLinter/Infrastructure/Diagram/Models/BpmnNode.cs
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
namespace SQLLinter.Infrastructure.Diagram;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Узел BPMN
|
||||||
|
/// </summary>
|
||||||
|
public class BpmnNode
|
||||||
|
{
|
||||||
|
///<summary> Уникальный идентификатор узла </summary>
|
||||||
|
public string Id { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
///<summary> Метка/название узла </summary>
|
||||||
|
public string Label { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
///<summary> Тип узла </summary>
|
||||||
|
public BpmnNodeType Type { get; set; }
|
||||||
|
|
||||||
|
/// <summary> Идентификатор подпроцесса (если тип узла - Subprocess) </summary>
|
||||||
|
public string SubprocessId { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary> Дополнительные свойства узла </summary>
|
||||||
|
public Dictionary<string, string> Properties { get; set; } = new();
|
||||||
|
}
|
||||||
20
SQLLinter/Infrastructure/Diagram/Models/BpmnNodeType.cs
Normal file
20
SQLLinter/Infrastructure/Diagram/Models/BpmnNodeType.cs
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
namespace SQLLinter.Infrastructure.Diagram;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Типы узлов BPMN
|
||||||
|
/// </summary>
|
||||||
|
public enum BpmnNodeType
|
||||||
|
{
|
||||||
|
/// <summary> Стартовый узел процесса </summary>
|
||||||
|
Start,
|
||||||
|
/// <summary> Конечный узел процесса </summary>
|
||||||
|
End,
|
||||||
|
/// <summary> Задача </summary>
|
||||||
|
Task,
|
||||||
|
/// <summary> Шлюз (разветвление/объединение) </summary>
|
||||||
|
Gateway,
|
||||||
|
/// <summary> Шлюз (разветвление/объединение) </summary>
|
||||||
|
Hexagon,
|
||||||
|
/// <summary> Подпроцесс (вызов другого процесса) </summary>
|
||||||
|
Subprocess,
|
||||||
|
}
|
||||||
19
SQLLinter/Infrastructure/Diagram/Models/BpmnProcess.cs
Normal file
19
SQLLinter/Infrastructure/Diagram/Models/BpmnProcess.cs
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
namespace SQLLinter.Infrastructure.Diagram;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Процесс BPMN
|
||||||
|
/// </summary>
|
||||||
|
public class BpmnProcess
|
||||||
|
{
|
||||||
|
/// <summary> Уникальный идентификатор процесса </summary>
|
||||||
|
public string Id { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary> Название процесса </summary>
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary> Узлы процесса </summary>
|
||||||
|
public List<BpmnNode> Nodes { get; set; } = new();
|
||||||
|
|
||||||
|
/// <summary> Связи процесса </summary>
|
||||||
|
public List<BpmnEdge> Edges { get; set; } = new();
|
||||||
|
}
|
||||||
72
SQLLinter/Infrastructure/Diagram/SqlDiagramProcessor.cs
Normal file
72
SQLLinter/Infrastructure/Diagram/SqlDiagramProcessor.cs
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
using SQLLinter.Core.Interfaces;
|
||||||
|
using SQLLinter.Infrastructure.Interfaces;
|
||||||
|
using SQLLinter.Infrastructure.Parser;
|
||||||
|
|
||||||
|
namespace SQLLinter.Infrastructure.Diagram;
|
||||||
|
|
||||||
|
public class SqlDiagramProcessor : ISqlDiagramProcessor
|
||||||
|
{
|
||||||
|
private readonly BpmnDiagram _bpmnDiagram;
|
||||||
|
private readonly IFragmentBuilder _fragmentBuilder;
|
||||||
|
private readonly ISqlStreamReaderBuilder _sqlStreamReaderBuilder;
|
||||||
|
|
||||||
|
public SqlDiagramProcessor(IFragmentBuilder fragmentBuilder, BpmnDiagram bpmnDiagram)
|
||||||
|
: this(fragmentBuilder, bpmnDiagram, new SqlStreamReaderBuilder()) { }
|
||||||
|
|
||||||
|
public SqlDiagramProcessor(IFragmentBuilder fragmentBuilder, BpmnDiagram bpmnDiagram, ISqlStreamReaderBuilder sqlStreamReaderBuilder)
|
||||||
|
{
|
||||||
|
_fragmentBuilder = fragmentBuilder;
|
||||||
|
_bpmnDiagram = bpmnDiagram;
|
||||||
|
_sqlStreamReaderBuilder = sqlStreamReaderBuilder;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ProcessList(List<string> filePaths)
|
||||||
|
{
|
||||||
|
foreach (var path in filePaths)
|
||||||
|
{
|
||||||
|
ProcessFile(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ProcessPath(string path)
|
||||||
|
{
|
||||||
|
ProcessFile(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ProcessFile(string filePath)
|
||||||
|
{
|
||||||
|
var fileStream = GetFileContents(filePath);
|
||||||
|
HandleProcessing(filePath, fileStream);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ProcessList(Dictionary<string, Stream> files)
|
||||||
|
{
|
||||||
|
foreach (var file in files)
|
||||||
|
{
|
||||||
|
HandleProcessing(file.Key, file.Value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void HandleProcessing(string filePath, Stream fileStream)
|
||||||
|
{
|
||||||
|
var fragment = _fragmentBuilder.GetFragment(filePath, GetSqlTextReader(fileStream), out var errors);
|
||||||
|
|
||||||
|
if (fragment == null || errors.Count > 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
BpmnBuilder.Build(fragment, _bpmnDiagram);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Stream GetFileContents(string filePath)
|
||||||
|
{
|
||||||
|
return File.OpenRead(filePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
private StreamReader GetSqlTextReader(Stream sqlFileStream)
|
||||||
|
{
|
||||||
|
return _sqlStreamReaderBuilder.CreateReader(sqlFileStream);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,20 +8,14 @@ public class SqlFileProcessor : ISqlFileProcessor
|
|||||||
{
|
{
|
||||||
private readonly IRuleVisitor ruleVisitor;
|
private readonly IRuleVisitor ruleVisitor;
|
||||||
|
|
||||||
private readonly IReporter reporter;
|
|
||||||
|
|
||||||
private readonly IPluginHandler pluginHandler;
|
|
||||||
|
|
||||||
private readonly IRuleExceptionFinder ruleExceptionFinder;
|
private readonly IRuleExceptionFinder ruleExceptionFinder;
|
||||||
|
|
||||||
public SqlFileProcessor(
|
public SqlFileProcessor(
|
||||||
IRuleVisitor ruleVisitor,
|
IRuleVisitor ruleVisitor,
|
||||||
IPluginHandler pluginHandler,
|
IPluginHandler pluginHandler
|
||||||
IReporter reporter)
|
)
|
||||||
{
|
{
|
||||||
this.ruleVisitor = ruleVisitor;
|
this.ruleVisitor = ruleVisitor;
|
||||||
this.pluginHandler = pluginHandler;
|
|
||||||
this.reporter = reporter;
|
|
||||||
ruleExceptionFinder = new RuleExceptionFinder(pluginHandler.RuleWithNames);
|
ruleExceptionFinder = new RuleExceptionFinder(pluginHandler.RuleWithNames);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ public class SqlRuleVisitor : IRuleVisitor
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
violations.ForEach(t => _reporter.ReportViolation(filePath, t.Line, t.Column, rule.Severity, t.RuleName, t.Message));
|
violations.ForEach(t => _reporter.ReportViolation(filePath, t.Line, t.Column, rule.Severity, t.RuleName, t.Template, t.Params));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static bool VisitorIsBlackListedForDynamicSql(IRule visitor)
|
private static bool VisitorIsBlackListedForDynamicSql(IRule visitor)
|
||||||
@@ -109,7 +109,15 @@ public class SqlRuleVisitor : IRuleVisitor
|
|||||||
|
|
||||||
if (!globalRulesOnLine.Any())
|
if (!globalRulesOnLine.Any())
|
||||||
{
|
{
|
||||||
_reporter.ReportViolation(new RuleViolation(sqlPath, "invalid-syntax", error.Message, error.Line, error.Column, RuleViolationSeverity.Critical));
|
_reporter.ReportViolation(new RuleViolation()
|
||||||
|
{
|
||||||
|
FileName = sqlPath,
|
||||||
|
RuleName = "invalid-syntax",
|
||||||
|
Text = error.Message,
|
||||||
|
Line = error.Line,
|
||||||
|
Column = error.Column,
|
||||||
|
Severity = RuleViolationSeverity.Critical
|
||||||
|
});
|
||||||
if (updatedExitCode)
|
if (updatedExitCode)
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
namespace SQLLinter.Infrastructure.Reporters;
|
|
||||||
|
|
||||||
public class FileReporter : Reporter
|
|
||||||
{
|
|
||||||
public virtual void SaveReport(string path)
|
|
||||||
{
|
|
||||||
File.WriteAllText(path, GetContent());
|
|
||||||
}
|
|
||||||
|
|
||||||
public virtual string GetContent()
|
|
||||||
{
|
|
||||||
return string.Join(Environment.NewLine, this.Violations);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
325
SQLLinter/Infrastructure/Reporters/HtmlMinifier.cs
Normal file
325
SQLLinter/Infrastructure/Reporters/HtmlMinifier.cs
Normal file
@@ -0,0 +1,325 @@
|
|||||||
|
using System.Text;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
public static class HtmlMinifier
|
||||||
|
{
|
||||||
|
public static string MinifyHtml(string html)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(html))
|
||||||
|
return html;
|
||||||
|
|
||||||
|
// Вырезаем чувствительные теги
|
||||||
|
var placeholders = new Dictionary<string, string>();
|
||||||
|
html = ExtractTag(html, "pre", placeholders);
|
||||||
|
html = ExtractTag(html, "code", placeholders);
|
||||||
|
html = ExtractTag(html, "textarea", placeholders);
|
||||||
|
|
||||||
|
// Минификация CSS и JS
|
||||||
|
html = MinifyCssInHtml(html);
|
||||||
|
html = MinifyJavaScriptInHtml(html);
|
||||||
|
|
||||||
|
// Удаление HTML комментариев
|
||||||
|
html = Regex.Replace(html,
|
||||||
|
@"<!--(?!\[if|\s*\[endif).*?-->",
|
||||||
|
"",
|
||||||
|
RegexOptions.Singleline | RegexOptions.Compiled);
|
||||||
|
|
||||||
|
// Удаление лишних пробелов между тегами
|
||||||
|
html = Regex.Replace(html, @">\s+<", "><");
|
||||||
|
|
||||||
|
// Collapse whitespace
|
||||||
|
html = Regex.Replace(html, @"\s{2,}", " ");
|
||||||
|
|
||||||
|
// Возвращаем чувствительные блоки
|
||||||
|
foreach (var kv in placeholders)
|
||||||
|
html = html.Replace(kv.Key, kv.Value);
|
||||||
|
|
||||||
|
return html.Trim();
|
||||||
|
}
|
||||||
|
private static string ExtractTag(string html, string tag, Dictionary<string, string> dict)
|
||||||
|
{
|
||||||
|
return Regex.Replace(html,
|
||||||
|
$@"<{tag}[^>]*>[\s\S]*?<\/{tag}>",
|
||||||
|
m =>
|
||||||
|
{
|
||||||
|
var key = $"__PLACEHOLDER_{dict.Count}__";
|
||||||
|
dict[key] = m.Value;
|
||||||
|
return key;
|
||||||
|
},
|
||||||
|
RegexOptions.IgnoreCase | RegexOptions.Compiled);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string MinifyCssInHtml(string html)
|
||||||
|
{
|
||||||
|
// Находим все теги <style>
|
||||||
|
var styleRegex = new Regex(@"<style[^>]*>([\s\S]*?)</style>",
|
||||||
|
RegexOptions.Compiled);
|
||||||
|
|
||||||
|
return styleRegex.Replace(html, match =>
|
||||||
|
{
|
||||||
|
var css = match.Groups[1].Value;
|
||||||
|
var minifiedCss = MinifyCss(css);
|
||||||
|
return $"<style>{minifiedCss}</style>";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string MinifyCss(string css)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(css))
|
||||||
|
return css;
|
||||||
|
|
||||||
|
// 1. Удаление комментариев
|
||||||
|
css = Regex.Replace(css, @"/\*[\s\S]*?\*/", "",
|
||||||
|
RegexOptions.Compiled);
|
||||||
|
|
||||||
|
// 2. Удаление лишних пробелов и переносов
|
||||||
|
css = Regex.Replace(css, @"\s+", " ",
|
||||||
|
RegexOptions.Compiled);
|
||||||
|
css = Regex.Replace(css, @"\s*{\s*", "{",
|
||||||
|
RegexOptions.Compiled);
|
||||||
|
css = Regex.Replace(css, @"\s*}\s*", "}",
|
||||||
|
RegexOptions.Compiled);
|
||||||
|
css = Regex.Replace(css, @"\s*:\s*", ":",
|
||||||
|
RegexOptions.Compiled);
|
||||||
|
css = Regex.Replace(css, @"\s*;\s*", ";",
|
||||||
|
RegexOptions.Compiled);
|
||||||
|
css = Regex.Replace(css, @"\s*,\s*", ",",
|
||||||
|
RegexOptions.Compiled);
|
||||||
|
|
||||||
|
// 3. Удаление последней точки с запятой перед }
|
||||||
|
css = Regex.Replace(css, @";}", "}",
|
||||||
|
RegexOptions.Compiled);
|
||||||
|
|
||||||
|
// 4. Удаление пробелов вокруг селекторов
|
||||||
|
css = Regex.Replace(css, @"\s*>\s*", ">",
|
||||||
|
RegexOptions.Compiled);
|
||||||
|
css = Regex.Replace(css, @"\s*\+\s*", "+",
|
||||||
|
RegexOptions.Compiled);
|
||||||
|
css = Regex.Replace(css, @"\s*~\s*", "~",
|
||||||
|
RegexOptions.Compiled);
|
||||||
|
|
||||||
|
// 5. Удаление пробелов в значениях
|
||||||
|
css = Regex.Replace(css, @"(\d)\s+(px|em|rem|%|pt|pc|in|cm|mm|ex|ch|vw|vh|vmin|vmax)",
|
||||||
|
"$1$2", RegexOptions.Compiled);
|
||||||
|
|
||||||
|
// 6. Удаление ведущих нулей
|
||||||
|
css = Regex.Replace(css, @"(?<=[ :\(,])0?\.(\d+)", ".$1",
|
||||||
|
RegexOptions.Compiled);
|
||||||
|
|
||||||
|
css = Regex.Replace(css, @"url\(\s*(.*?)\s*\)", "url($1)");
|
||||||
|
|
||||||
|
return css.Trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string MinifyJavaScriptInHtml(string html)
|
||||||
|
{
|
||||||
|
// Находим все теги <script>
|
||||||
|
var scriptRegex = new Regex(@"<script[^>]*>([\s\S]*?)</script>",
|
||||||
|
RegexOptions.Compiled);
|
||||||
|
|
||||||
|
return scriptRegex.Replace(html, match =>
|
||||||
|
{
|
||||||
|
var scriptContent = match.Groups[1].Value;
|
||||||
|
|
||||||
|
// Пропускаем script с type="application/json" или src
|
||||||
|
var tag = match.Value;
|
||||||
|
if (tag.Contains("type=\"application/json\"") ||
|
||||||
|
tag.Contains("src=") ||
|
||||||
|
scriptContent.Trim().Length == 0)
|
||||||
|
return match.Value;
|
||||||
|
|
||||||
|
var minifiedJs = MinifyJavaScript(scriptContent);
|
||||||
|
|
||||||
|
if (tag.Contains("type=\"module\""))
|
||||||
|
return $"<script type=\"module\">{minifiedJs}</script>";
|
||||||
|
else
|
||||||
|
return $"<script>{minifiedJs}</script>";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string MinifyJavaScript(string js)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(js))
|
||||||
|
return js;
|
||||||
|
|
||||||
|
var sb = new StringBuilder(js.Length);
|
||||||
|
int i = 0;
|
||||||
|
int len = js.Length;
|
||||||
|
|
||||||
|
bool inSingle = false;
|
||||||
|
bool inDouble = false;
|
||||||
|
bool inTemplate = false;
|
||||||
|
bool inLineComment = false;
|
||||||
|
bool inBlockComment = false;
|
||||||
|
|
||||||
|
while (i < len)
|
||||||
|
{
|
||||||
|
char c = js[i];
|
||||||
|
char next = i + 1 < len ? js[i + 1] : '\0';
|
||||||
|
|
||||||
|
// -----------------------------
|
||||||
|
// LINE COMMENT //
|
||||||
|
// -----------------------------
|
||||||
|
if (inLineComment)
|
||||||
|
{
|
||||||
|
if (c == '\n' || c == '\r')
|
||||||
|
{
|
||||||
|
inLineComment = false;
|
||||||
|
sb.Append(' ');
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------
|
||||||
|
// BLOCK COMMENT /* ... */ //
|
||||||
|
// -----------------------------
|
||||||
|
if (inBlockComment)
|
||||||
|
{
|
||||||
|
if (c == '*' && next == '/')
|
||||||
|
{
|
||||||
|
inBlockComment = false;
|
||||||
|
i += 2;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------
|
||||||
|
// STRING: '...' //
|
||||||
|
// -----------------------------
|
||||||
|
if (inSingle)
|
||||||
|
{
|
||||||
|
sb.Append(c);
|
||||||
|
if (c == '\\')
|
||||||
|
{
|
||||||
|
if (i + 1 < len) sb.Append(js[i + 1]);
|
||||||
|
i += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '\'') inSingle = false;
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------
|
||||||
|
// STRING: "..." //
|
||||||
|
// -----------------------------
|
||||||
|
if (inDouble)
|
||||||
|
{
|
||||||
|
sb.Append(c);
|
||||||
|
if (c == '\\')
|
||||||
|
{
|
||||||
|
if (i + 1 < len) sb.Append(js[i + 1]);
|
||||||
|
i += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '"') inDouble = false;
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------
|
||||||
|
// TEMPLATE: `...` //
|
||||||
|
// -----------------------------
|
||||||
|
if (inTemplate)
|
||||||
|
{
|
||||||
|
sb.Append(c);
|
||||||
|
if (c == '\\')
|
||||||
|
{
|
||||||
|
if (i + 1 < len) sb.Append(js[i + 1]);
|
||||||
|
i += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '`') inTemplate = false;
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------
|
||||||
|
// NORMAL CODE //
|
||||||
|
// -----------------------------
|
||||||
|
|
||||||
|
// Start of line comment
|
||||||
|
if (c == '/' && next == '/')
|
||||||
|
{
|
||||||
|
inLineComment = true;
|
||||||
|
i += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start of block comment
|
||||||
|
if (c == '/' && next == '*')
|
||||||
|
{
|
||||||
|
inBlockComment = true;
|
||||||
|
i += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start of strings
|
||||||
|
if (c == '\'')
|
||||||
|
{
|
||||||
|
inSingle = true;
|
||||||
|
sb.Append(c);
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '"')
|
||||||
|
{
|
||||||
|
inDouble = true;
|
||||||
|
sb.Append(c);
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '`')
|
||||||
|
{
|
||||||
|
inTemplate = true;
|
||||||
|
sb.Append(c);
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collapse whitespace in code
|
||||||
|
if (char.IsWhiteSpace(c))
|
||||||
|
{
|
||||||
|
sb.Append(' ');
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
sb.Append(c);
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------
|
||||||
|
// FINAL WHITESPACE MINIFICATION
|
||||||
|
// -----------------------------
|
||||||
|
var result = sb.ToString();
|
||||||
|
|
||||||
|
// Удаляем повторяющиеся пробелы
|
||||||
|
result = Regex.Replace(result, @"\s+", " ");
|
||||||
|
|
||||||
|
// Убираем пробелы вокруг операторов
|
||||||
|
result = Regex.Replace(result, @"\s*([=+\-*/%&|^<>!?:,;{}()\[\]])\s*", "$1");
|
||||||
|
|
||||||
|
return result.Trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string CompressJson(string json)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(json))
|
||||||
|
return json;
|
||||||
|
|
||||||
|
// Удаление пробелов и переносов из JSON
|
||||||
|
json = Regex.Replace(json, @"(""[^""\\]*(?:\\.[^""\\]*)*"")|\s+",
|
||||||
|
match => match.Groups[1].Success ? match.Groups[1].Value : "",
|
||||||
|
RegexOptions.Compiled);
|
||||||
|
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,16 @@
|
|||||||
using SQLLinter.Common;
|
using SQLLinter.Common;
|
||||||
|
using SQLLinter.Infrastructure.Diagram;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
namespace SQLLinter.Infrastructure.Reporters;
|
namespace SQLLinter.Infrastructure.Reporters;
|
||||||
|
|
||||||
public class HTMLReporter : FileReporter
|
public class HtmlReportFormatter_v1 : IReportFormatter
|
||||||
{
|
{
|
||||||
public string GetContent()
|
public string Format(List<IRuleViolation> violations)
|
||||||
|
=> Format(violations, null);
|
||||||
|
|
||||||
|
public string Format(List<IRuleViolation> violations, BpmnDiagram? diagram)
|
||||||
{
|
{
|
||||||
var violations = Violations;
|
|
||||||
if (violations.Count == 0)
|
if (violations.Count == 0)
|
||||||
{
|
{
|
||||||
return "<p><em>Нет нарушений</em></p>";
|
return "<p><em>Нет нарушений</em></p>";
|
||||||
@@ -34,14 +37,14 @@ public class HTMLReporter : FileReporter
|
|||||||
sb.AppendLine("td.line, td.column { width: 60px; text-align: center; }");
|
sb.AppendLine("td.line, td.column { width: 60px; text-align: center; }");
|
||||||
sb.AppendLine("td.rule { width: 300px; text-align: left; }");
|
sb.AppendLine("td.rule { width: 300px; text-align: left; }");
|
||||||
sb.AppendLine("td.index { width: 40px; text-align: center; }");
|
sb.AppendLine("td.index { width: 40px; text-align: center; }");
|
||||||
sb.AppendLine(".critical { border-left: 4px solid #d13438; padding: 10px; margin-bottom: 20px; background-color: #fde7e9; }");
|
sb.AppendLine(".critical { border-left: 4px solid #d13438; padding: 10px; margin-bottom: 20px; margin-top: 20px; background-color: #fde7e9; }");
|
||||||
sb.AppendLine(".warning { border-left: 4px solid #ffaa44; padding: 10px; margin-bottom: 20px; background-color: #fff4ce; }");
|
sb.AppendLine(".warning { border-left: 4px solid #ffaa44; padding: 10px; margin-bottom: 20px; background-color: #fff4ce; }");
|
||||||
sb.AppendLine(".info { border-left: 4px solid #0078d4; padding: 10px; margin-bottom: 20px; background-color: #deecf9; }");
|
sb.AppendLine(".info { border-left: 4px solid #0078d4; padding: 10px; margin-bottom: 20px; background-color: #deecf9; }");
|
||||||
sb.AppendLine(".tabs { position: fixed; bottom: 0; left: 0; right: 0; background-color: #ffffff; border-top: 1px solid #ccc; padding: 10px; display: flex; overflow-x: auto; scrollbar-width: thin; justify-content: flex-start; box-shadow: 0 -2px 6px rgba(0,0,0,0.1); }");
|
sb.AppendLine(".tabs { position: fixed; bottom: 0; left: 0; right: 0; background-color: #ffffff; border-top: 1px solid #ccc; padding: 10px; display: flex; overflow-x: auto; scrollbar-width: thin; justify-content: flex-start; box-shadow: 0 -2px 6px rgba(0,0,0,0.1); }");
|
||||||
sb.AppendLine(".tab { margin-right: 10px; padding: 8px 16px; border-radius: 4px; background-color: #f3f2f1; cursor: pointer; transition: background-color 0.2s; }");
|
sb.AppendLine(".tab { margin-right: 10px; padding: 8px 16px; border-radius: 4px; background-color: #f3f2f1; cursor: pointer; transition: background-color 0.2s; }");
|
||||||
sb.AppendLine(".tab:hover { background-color: #e1dfdd; }");
|
sb.AppendLine(".tab:hover { background-color: #e1dfdd; }");
|
||||||
sb.AppendLine(".tab.active { background-color: #0078d4; color: white; }");
|
sb.AppendLine(".tab.active { background-color: #0078d4; color: white; }");
|
||||||
sb.AppendLine(".file-report { display: none; padding: 20px 0; }");
|
sb.AppendLine(".file-report { display: none; padding: 0 0; }");
|
||||||
sb.AppendLine(".file-report.active { display: block; }");
|
sb.AppendLine(".file-report.active { display: block; }");
|
||||||
|
|
||||||
// Тёмная тема
|
// Тёмная тема
|
||||||
@@ -140,6 +143,6 @@ public class HTMLReporter : FileReporter
|
|||||||
sb.AppendLine("</body>");
|
sb.AppendLine("</body>");
|
||||||
sb.AppendLine("</html>");
|
sb.AppendLine("</html>");
|
||||||
|
|
||||||
return sb.ToString();
|
return HtmlMinifier.MinifyHtml(sb.ToString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
282
SQLLinter/Infrastructure/Reporters/HtmlReportFormatter_v2.cs
Normal file
282
SQLLinter/Infrastructure/Reporters/HtmlReportFormatter_v2.cs
Normal file
@@ -0,0 +1,282 @@
|
|||||||
|
using SQLLinter.Common;
|
||||||
|
using SQLLinter.Infrastructure.Diagram;
|
||||||
|
using SQLLinter.Infrastructure.Rules.RuleViolations;
|
||||||
|
using System.Data;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace SQLLinter.Infrastructure.Reporters;
|
||||||
|
|
||||||
|
public class HtmlReportFormatter_v2 : IReportFormatter
|
||||||
|
{
|
||||||
|
public string Format(List<IRuleViolation> violations)
|
||||||
|
=> Format(violations, null);
|
||||||
|
|
||||||
|
public string Format(List<IRuleViolation> violations, BpmnDiagram? diagram)
|
||||||
|
{
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
GenerateBeginningHtml(sb);
|
||||||
|
|
||||||
|
// Подготовка данных для передачи в JS
|
||||||
|
var reportData = PrepareReportData(violations, diagram);
|
||||||
|
var jsonData = JsonSerializer.Serialize(reportData, new JsonSerializerOptions
|
||||||
|
{
|
||||||
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||||
|
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
|
||||||
|
});
|
||||||
|
|
||||||
|
if (violations.Count == 0 && diagram == null)
|
||||||
|
{
|
||||||
|
// Случай без нарушений
|
||||||
|
sb.AppendLine("<div class=\"no-violations\">");
|
||||||
|
sb.AppendLine("<div class=\"no-violations-content\">");
|
||||||
|
sb.AppendLine("<div class=\"no-violations-icon\">✅</div>");
|
||||||
|
sb.AppendLine("<h3 class=\"no-violations-title\">Проверка завершена</h3>");
|
||||||
|
sb.AppendLine("<p class=\"no-violations-description\">Нарушений правил SQL не обнаружено.</p>");
|
||||||
|
sb.AppendLine("</div>");
|
||||||
|
sb.AppendLine("</div>");
|
||||||
|
|
||||||
|
GenerateEndingHtml(sb, false, HtmlMinifier.CompressJson(jsonData));
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Основной контейнер для отчета
|
||||||
|
sb.AppendLine("""
|
||||||
|
<div id="reports-container"></div>
|
||||||
|
<div id="tabs-container" class="tabs-container">
|
||||||
|
<div class="tabs" id="tabs-list"></div>
|
||||||
|
</div>
|
||||||
|
""");
|
||||||
|
|
||||||
|
GenerateEndingHtml(sb, diagram != null, jsonData);
|
||||||
|
|
||||||
|
var html = HtmlMinifier.MinifyHtml(sb.ToString());
|
||||||
|
return html;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ReportData PrepareReportData(List<IRuleViolation> violations, BpmnDiagram? diagram)
|
||||||
|
{
|
||||||
|
var reportData = new ReportData();
|
||||||
|
|
||||||
|
// Группировка по файлам
|
||||||
|
var groupedByFile = violations
|
||||||
|
.GroupBy(v => v.FileName)
|
||||||
|
.OrderBy(g => g.Key)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
foreach (var fileGroup in groupedByFile)
|
||||||
|
{
|
||||||
|
var fileData = new FileReport
|
||||||
|
{
|
||||||
|
Name = fileGroup.Key,
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
// Группировка по severity
|
||||||
|
var severityGroups = fileGroup
|
||||||
|
.GroupBy(v => v.Severity)
|
||||||
|
.OrderByDescending(g => g.Key)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
foreach (var violation in fileGroup.Select(t => t).OrderBy(v => v.Line).ThenBy(v => v.Column))
|
||||||
|
{
|
||||||
|
int ruleId;
|
||||||
|
List<string> args = new();
|
||||||
|
|
||||||
|
if (violation is RuleTemplateViolation templateRule)
|
||||||
|
{
|
||||||
|
args = templateRule.Params.Select(p => EscapeHtml(p)).ToList();
|
||||||
|
|
||||||
|
if (reportData.Rules.Any(t => t.Value.Name == templateRule.RuleName))
|
||||||
|
{
|
||||||
|
ruleId = reportData.Rules.First(t => t.Value.Name == templateRule.RuleName).Key;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ruleId = reportData.Rules.Count + 1;
|
||||||
|
reportData.Rules.Add(ruleId, new Rule
|
||||||
|
{
|
||||||
|
Name = templateRule.RuleName,
|
||||||
|
Template = templateRule.RuleTemplate
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ruleId = reportData.Rules.Count + 1;
|
||||||
|
reportData.Rules.Add(ruleId, new Rule
|
||||||
|
{
|
||||||
|
Name = violation.RuleName,
|
||||||
|
Template = violation.Text,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
var v = new Violation()
|
||||||
|
{
|
||||||
|
RuleId = ruleId,
|
||||||
|
Args = args,
|
||||||
|
Column = violation.Column,
|
||||||
|
Line = violation.Line,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (violation.Severity == RuleViolationSeverity.Critical)
|
||||||
|
{
|
||||||
|
v.Index = fileData.Violations.Critical.Count + 1;
|
||||||
|
fileData.Violations.Critical.Add(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
else if (violation.Severity == RuleViolationSeverity.Warning)
|
||||||
|
{
|
||||||
|
v.Index = fileData.Violations.Warning.Count + 1;
|
||||||
|
fileData.Violations.Warning.Add(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
else if (violation.Severity == RuleViolationSeverity.Info)
|
||||||
|
{
|
||||||
|
v.Index = fileData.Violations.Info.Count + 1;
|
||||||
|
fileData.Violations.Info.Add(v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
reportData.Files.Add(fileData);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Добавление диаграммы, если есть
|
||||||
|
if (diagram != null)
|
||||||
|
{
|
||||||
|
reportData.Diagram = new Diagram
|
||||||
|
{
|
||||||
|
Content = MermaidRenderer.ToMermaidContent(diagram),
|
||||||
|
HasDiagram = true
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return reportData;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void GenerateBeginningHtml(StringBuilder sb)
|
||||||
|
{
|
||||||
|
sb.AppendLine("""
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Отчёт по SQL‑проверкам</title>
|
||||||
|
<style>
|
||||||
|
""");
|
||||||
|
|
||||||
|
sb.AppendLine(LoadResource("HtmlFormatter.css"));
|
||||||
|
sb.AppendLine("</style></head><body><main id=\"main-content\">");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void GenerateEndingHtml(StringBuilder sb, bool hasDiagram, string jsonData)
|
||||||
|
{
|
||||||
|
// Вставка JSON данных
|
||||||
|
sb.AppendLine($"""
|
||||||
|
<script id="report-data" type="application/json">
|
||||||
|
{jsonData}
|
||||||
|
</script>
|
||||||
|
""");
|
||||||
|
|
||||||
|
sb.AppendLine("""
|
||||||
|
<script type="module">
|
||||||
|
""");
|
||||||
|
|
||||||
|
// Загружаем основной JS
|
||||||
|
sb.AppendLine(LoadResource("HtmlFormatter.js"));
|
||||||
|
|
||||||
|
sb.AppendLine("""
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
""");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string LoadResource(string endsWith)
|
||||||
|
{
|
||||||
|
var assembly = Assembly.GetExecutingAssembly();
|
||||||
|
var name = assembly.GetManifestResourceNames()
|
||||||
|
.First(n => n.EndsWith(endsWith, StringComparison.OrdinalIgnoreCase));
|
||||||
|
using var stream = assembly.GetManifestResourceStream(name);
|
||||||
|
using var reader = new StreamReader(stream);
|
||||||
|
return reader.ReadToEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string EscapeHtml(string text)
|
||||||
|
{
|
||||||
|
return System.Net.WebUtility.HtmlEncode(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Классы для сериализации
|
||||||
|
private class ReportData
|
||||||
|
{
|
||||||
|
[JsonPropertyName("f")] // files
|
||||||
|
public List<FileReport> Files { get; set; } = new();
|
||||||
|
|
||||||
|
[JsonPropertyName("r")] // rules
|
||||||
|
public Dictionary<int, Rule> Rules { get; set; } = new();
|
||||||
|
|
||||||
|
[JsonPropertyName("d")] // diagram
|
||||||
|
public Diagram Diagram { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
private class FileReport
|
||||||
|
{
|
||||||
|
[JsonPropertyName("n")] // name
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[JsonPropertyName("v")] // violations
|
||||||
|
public Violations Violations { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Violations
|
||||||
|
{
|
||||||
|
[JsonPropertyName("c")] // critical
|
||||||
|
public List<Violation> Critical { get; set; } = new();
|
||||||
|
|
||||||
|
[JsonPropertyName("w")] // warning
|
||||||
|
public List<Violation> Warning { get; set; } = new();
|
||||||
|
|
||||||
|
[JsonPropertyName("i")] // info
|
||||||
|
public List<Violation> Info { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Violation
|
||||||
|
{
|
||||||
|
[JsonPropertyName("i")] // index
|
||||||
|
public int Index { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("l")] // line
|
||||||
|
public int Line { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("c")] // column
|
||||||
|
public int Column { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("r")] // ruleId
|
||||||
|
public int RuleId { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("a")] // args (optional)
|
||||||
|
public List<string>? Args { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Rule
|
||||||
|
{
|
||||||
|
[JsonPropertyName("n")] // name
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[JsonPropertyName("t")] // template
|
||||||
|
public string Template { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Diagram
|
||||||
|
{
|
||||||
|
[JsonPropertyName("c")] // content
|
||||||
|
public string Content { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[JsonPropertyName("h")] // hasDiagram
|
||||||
|
public bool HasDiagram { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
10
SQLLinter/Infrastructure/Reporters/IReportFormatter.cs
Normal file
10
SQLLinter/Infrastructure/Reporters/IReportFormatter.cs
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
using SQLLinter.Common;
|
||||||
|
using SQLLinter.Infrastructure.Diagram;
|
||||||
|
|
||||||
|
namespace SQLLinter.Infrastructure.Reporters;
|
||||||
|
|
||||||
|
public interface IReportFormatter
|
||||||
|
{
|
||||||
|
string Format(List<IRuleViolation> violations);
|
||||||
|
string Format(List<IRuleViolation> violations, BpmnDiagram? diagram);
|
||||||
|
}
|
||||||
@@ -1,12 +1,13 @@
|
|||||||
using System.Text;
|
using SQLLinter.Common;
|
||||||
|
using SQLLinter.Infrastructure.Diagram;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
namespace SQLLinter.Infrastructure.Reporters;
|
namespace SQLLinter.Infrastructure.Reporters;
|
||||||
|
|
||||||
public class MarkdownFileReporter : FileReporter
|
public class MarkdownReportFormatter : IReportFormatter
|
||||||
{
|
{
|
||||||
public override string GetContent()
|
public string Format(List<IRuleViolation> violations)
|
||||||
{
|
{
|
||||||
var violations = Violations;
|
|
||||||
if (violations.Count == 0)
|
if (violations.Count == 0)
|
||||||
{
|
{
|
||||||
return "_Нет нарушений_";
|
return "_Нет нарушений_";
|
||||||
@@ -50,4 +51,9 @@ public class MarkdownFileReporter : FileReporter
|
|||||||
return sb.ToString();
|
return sb.ToString();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public string Format(List<IRuleViolation> violations, BpmnDiagram diagram)
|
||||||
|
{
|
||||||
|
throw new NotImplementedException();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -7,15 +7,22 @@ namespace SQLLinter.Infrastructure.Reporters;
|
|||||||
public class Reporter : IReporter
|
public class Reporter : IReporter
|
||||||
{
|
{
|
||||||
private readonly List<string> _log = new();
|
private readonly List<string> _log = new();
|
||||||
|
private readonly bool _useLogging;
|
||||||
|
|
||||||
public int? FixedCount { get; set; }
|
public int? FixedCount { get; set; }
|
||||||
|
|
||||||
private readonly ConcurrentBag<IRuleViolation> ruleViolations = new();
|
private readonly ConcurrentBag<IRuleViolation> ruleViolations = new();
|
||||||
|
|
||||||
public List<IRuleViolation> Violations => ruleViolations.ToList();
|
public List<IRuleViolation> Violations => ruleViolations.ToList();
|
||||||
|
|
||||||
|
public Reporter(bool useLogging = false)
|
||||||
|
{
|
||||||
|
_useLogging = useLogging;
|
||||||
|
}
|
||||||
|
|
||||||
public virtual void Report(string message)
|
public virtual void Report(string message)
|
||||||
{
|
{
|
||||||
_log.Add(message);
|
if (_useLogging) _log.Add(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<string> GetLog() => _log;
|
public List<string> GetLog() => _log;
|
||||||
@@ -34,8 +41,17 @@ public class Reporter : IReporter
|
|||||||
Report(violation.ToString());
|
Report(violation.ToString());
|
||||||
}
|
}
|
||||||
|
|
||||||
public void ReportViolation(string fileName, int line, int column, RuleViolationSeverity severity, string ruleName, string violationText)
|
public void ReportViolation(string fileName, int line, int column, RuleViolationSeverity severity, string ruleName, string template, params string[] param)
|
||||||
{
|
{
|
||||||
ReportViolation(new RuleViolation(fileName, ruleName, violationText, line, column, severity));
|
ReportViolation(new RuleTemplateViolation()
|
||||||
|
{
|
||||||
|
FileName = fileName,
|
||||||
|
RuleName = ruleName,
|
||||||
|
RuleTemplate = template,
|
||||||
|
Line = line,
|
||||||
|
Column = column,
|
||||||
|
Severity = severity,
|
||||||
|
Params = param.ToList(),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
1210
SQLLinter/Infrastructure/Reporters/Static/HtmlFormatter.css
Normal file
1210
SQLLinter/Infrastructure/Reporters/Static/HtmlFormatter.css
Normal file
File diff suppressed because it is too large
Load Diff
1614
SQLLinter/Infrastructure/Reporters/Static/HtmlFormatter.js
Normal file
1614
SQLLinter/Infrastructure/Reporters/Static/HtmlFormatter.js
Normal file
File diff suppressed because it is too large
Load Diff
@@ -19,7 +19,7 @@ public class ConditionalBeginEndRule : BaseRuleVisitor, IRule
|
|||||||
{
|
{
|
||||||
if (node.ThenStatement is not BeginEndBlockStatement)
|
if (node.ThenStatement is not BeginEndBlockStatement)
|
||||||
{
|
{
|
||||||
AddViolation(Name, Text, GetLineNumber(node), GetColumnNumber(node));
|
AddViolation(node);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (node.ElseStatement != null && node.ElseStatement is not BeginEndBlockStatement && node.ElseStatement is not IfStatement)
|
if (node.ElseStatement != null && node.ElseStatement is not BeginEndBlockStatement && node.ElseStatement is not IfStatement)
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ public class IndexHintRule : BaseRuleVisitor
|
|||||||
{
|
{
|
||||||
if (node.HintKind == TableHintKind.Index)
|
if (node.HintKind == TableHintKind.Index)
|
||||||
{
|
{
|
||||||
AddViolation(Name, Text, GetLineNumber(node), GetColumnNumber(node));
|
AddViolation(node);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ public class InsertValuesInsteadOfSelectRule : BaseRuleVisitor
|
|||||||
// Если в SELECT нет таблиц (т.е. просто SELECT 1,2,3)
|
// Если в SELECT нет таблиц (т.е. просто SELECT 1,2,3)
|
||||||
if (query.FromClause == null || query.FromClause.TableReferences.Count == 0)
|
if (query.FromClause == null || query.FromClause.TableReferences.Count == 0)
|
||||||
{
|
{
|
||||||
AddViolation(Name, Text, GetLineNumber(node), GetColumnNumber(node));
|
AddViolation(node);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ public class KeywordCapitalizationRule : BaseRuleVisitor, IRule
|
|||||||
var tabsOnLine = ColumnNumberCalculator.CountTabsBeforeToken(token.Line, index, node.ScriptTokenStream);
|
var tabsOnLine = ColumnNumberCalculator.CountTabsBeforeToken(token.Line, index, node.ScriptTokenStream);
|
||||||
var column = ColumnNumberCalculator.GetColumnNumberBeforeToken(tabsOnLine, token);
|
var column = ColumnNumberCalculator.GetColumnNumberBeforeToken(tabsOnLine, token);
|
||||||
|
|
||||||
AddViolation(Name, GetText(token.Text), GetLineNumber(token), column + dynamicSQLAdjustment);
|
AddViolation(Name, Text, GetLineNumber(token), column + dynamicSQLAdjustment, token.Text);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ public class MultiTableAliasRule : BaseRuleVisitor, IRule
|
|||||||
tableName = SQLHelpers.ObjectGetFullName(namedTable.SchemaObject);
|
tableName = SQLHelpers.ObjectGetFullName(namedTable.SchemaObject);
|
||||||
}
|
}
|
||||||
|
|
||||||
AddViolation(Name, GetText(tableName), GetLineNumber(childNode), column + dynamicSqlAdjustment);
|
AddViolation(Name, Text, GetLineNumber(childNode), column + dynamicSqlAdjustment, tableName);
|
||||||
}
|
}
|
||||||
|
|
||||||
var childTableJoinVisitor = new ChildTableJoinVisitor();
|
var childTableJoinVisitor = new ChildTableJoinVisitor();
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ public class ProcedureLoggingReturnRule : BaseRuleVisitor
|
|||||||
|
|
||||||
if ((hasDebugLog || hasLabelFinish) || hasReturn)
|
if ((hasDebugLog || hasLabelFinish) || hasReturn)
|
||||||
{
|
{
|
||||||
returnPositions.ForEach(t => AddViolation(Name, GetText(name), t.Line, t.Column));
|
returnPositions.ForEach(t => AddViolation(Name, Text, t.Line, t.Column, name));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,46 +4,25 @@ namespace SQLLinter.Infrastructure.Rules.RuleViolations
|
|||||||
{
|
{
|
||||||
public class RuleViolation : IRuleViolation
|
public class RuleViolation : IRuleViolation
|
||||||
{
|
{
|
||||||
public RuleViolation(string fileName, string ruleName, string text, int startLine, int startColumn, RuleViolationSeverity severity)
|
required public string FileName { get; init; }
|
||||||
{
|
|
||||||
FileName = fileName;
|
required public int Column { get; set; }
|
||||||
RuleName = ruleName;
|
|
||||||
Text = text;
|
required public int Line { get; set; }
|
||||||
Line = startLine;
|
|
||||||
Column = startColumn;
|
required public string RuleName { get; init; }
|
||||||
Severity = severity;
|
|
||||||
|
required public RuleViolationSeverity Severity { get; init; }
|
||||||
|
|
||||||
|
virtual public string Text { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public RuleViolation(string fileName, string ruleName, int startLine, int startColumn)
|
public class RuleTemplateViolation : RuleViolation
|
||||||
{
|
{
|
||||||
FileName = fileName;
|
override public string Text => string.Format(RuleTemplate, Params.ToArray());
|
||||||
RuleName = ruleName;
|
|
||||||
Line = startLine;
|
|
||||||
Column = startColumn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public RuleViolation(string ruleName, int startLine, int startColumn)
|
required public string RuleTemplate { get; init; }
|
||||||
{
|
|
||||||
RuleName = ruleName;
|
|
||||||
Line = startLine;
|
|
||||||
Column = startColumn;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int Column { get; set; }
|
public List<string> Params { get; set; } = new();
|
||||||
|
|
||||||
public string FileName { get; set; }
|
|
||||||
|
|
||||||
public int Line { get; set; }
|
|
||||||
|
|
||||||
public string RuleName { get; set; }
|
|
||||||
|
|
||||||
public RuleViolationSeverity Severity { get; set; }
|
|
||||||
|
|
||||||
public string Text { get; set; }
|
|
||||||
|
|
||||||
public override string ToString()
|
|
||||||
{
|
|
||||||
return $@"{Severity.ToString().ToUpper()}: L{Line} C{Column} {FileName} ""{Text}""";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using SQLLinter.Common;
|
using SQLLinter.Common;
|
||||||
using SQLLinter.Common.Helpers;
|
using SQLLinter.Common.Helpers;
|
||||||
using SQLLinter.Core.Interfaces;
|
using SQLLinter.Core.Interfaces;
|
||||||
|
using SQLLinter.Infrastructure.Interfaces;
|
||||||
using SQLLinter.Infrastructure.Parser;
|
using SQLLinter.Infrastructure.Parser;
|
||||||
using SQLLinter.Infrastructure.Plugins;
|
using SQLLinter.Infrastructure.Plugins;
|
||||||
|
|
||||||
@@ -15,20 +16,25 @@ public class Linter
|
|||||||
private ISqlFileProcessor _fileProcessor;
|
private ISqlFileProcessor _fileProcessor;
|
||||||
|
|
||||||
public Linter(IConfig config, IReporter reporter)
|
public Linter(IConfig config, IReporter reporter)
|
||||||
|
: this(config
|
||||||
|
, reporter
|
||||||
|
, new FragmentBuilder(reporter, config.CompatibilityLevel)
|
||||||
|
, new SqlStreamReaderBuilder()
|
||||||
|
)
|
||||||
|
{ }
|
||||||
|
|
||||||
|
public Linter(IConfig config, IReporter reporter, IFragmentBuilder fragmentBuilder, ISqlStreamReaderBuilder sqlStreamReaderBuilder)
|
||||||
{
|
{
|
||||||
this._config = config;
|
this._config = config;
|
||||||
this._reporter = reporter;
|
this._reporter = reporter;
|
||||||
|
|
||||||
this._pluginHandler = new PluginHandler(reporter, config);
|
|
||||||
|
|
||||||
_reporter.Report($"Загрузка SQL Linter...");
|
_reporter.Report($"Загрузка SQL Linter...");
|
||||||
|
|
||||||
var fragmentBuilder = new FragmentBuilder(reporter, _config.CompatibilityLevel);
|
|
||||||
_pluginHandler = new PluginHandler(_reporter, _config);
|
_pluginHandler = new PluginHandler(_reporter, _config);
|
||||||
|
|
||||||
var ruleVisitor = new SqlRuleVisitor(_pluginHandler, fragmentBuilder, _reporter);
|
var ruleVisitor = new SqlRuleVisitor(_pluginHandler, fragmentBuilder, _reporter, sqlStreamReaderBuilder);
|
||||||
|
|
||||||
_fileProcessor = new SqlFileProcessor(ruleVisitor, _pluginHandler, reporter);
|
_fileProcessor = new SqlFileProcessor(ruleVisitor, _pluginHandler);
|
||||||
|
|
||||||
_reporter.Report($"SQL Linter загружен...");
|
_reporter.Report($"SQL Linter загружен...");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,15 @@
|
|||||||
<PackageLicenseExpression>MIT</PackageLicenseExpression>
|
<PackageLicenseExpression>MIT</PackageLicenseExpression>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Remove="Infrastructure\Reporters\Static\HtmlFormatter.css" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<EmbeddedResource Include="Infrastructure\Reporters\Static\HtmlFormatter.css" />
|
||||||
|
<EmbeddedResource Include="Infrastructure\Reporters\Static\HtmlFormatter.js" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.SqlServer.TransactSql.ScriptDom" Version="170.128.0" />
|
<PackageReference Include="Microsoft.SqlServer.TransactSql.ScriptDom" Version="170.128.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
Reference in New Issue
Block a user