using Strata.SqlTools.Breakdowns.LinqToSql;
namespace Strata.SqlTools.Markdown.LinqToSql;
///
/// Generates Mermaid diagram markdown from LINQ to SQL QueryBreakdown objects.
/// Creates flowchart visualizations showing the LINQ query structure and flow.
///
public class QueryBreakdownGenerator
{
///
/// Generates a Mermaid flowchart diagram from a LINQ to SQL QueryBreakdown.
///
/// The LINQ QueryBreakdown to visualize.
/// Optional title for the diagram.
/// A string containing the Mermaid markdown diagram.
public static string GenerateMermaidDiagram(LinqQueryBreakdown queryBreakdown, string? title = null)
{
// Since LinqQueryBreakdown inherits from SqlServer.QueryBreakdown,
// we can use the base generator which works with the shared properties
return SqlServer.QueryBreakdownGenerator.GenerateMermaidDiagram(queryBreakdown, title);
}
///
/// Generates a Mermaid diagram showing the LINQ method call chain.
///
/// The LINQ QueryBreakdown to visualize.
/// Optional title for the diagram.
/// A string containing the Mermaid flowchart showing method calls.
public static string GenerateMethodChainDiagram(LinqQueryBreakdown queryBreakdown, string? title = null)
{
var sb = new System.Text.StringBuilder();
if (!string.IsNullOrWhiteSpace(title))
{
sb.AppendLine($"### {title}");
sb.AppendLine();
}
sb.AppendLine("```mermaid");
sb.AppendLine("flowchart LR");
sb.AppendLine();
if (queryBreakdown.MethodCallChain.Count == 0)
{
sb.AppendLine(" Start([IQueryable]) --> End([Result])");
}
else
{
sb.AppendLine(" Start([IQueryable])");
for (int i = 0; i < queryBreakdown.MethodCallChain.Count; i++)
{
var method = queryBreakdown.MethodCallChain[i];
var nodeId = $"M{i}";
var prevNodeId = i == 0 ? "Start" : $"M{i - 1}";
sb.AppendLine($" {nodeId}[\"{method}\"]");
sb.AppendLine($" {prevNodeId} --> {nodeId}");
}
var lastNodeId = $"M{queryBreakdown.MethodCallChain.Count - 1}";
sb.AppendLine($" {lastNodeId} --> End([Result])");
}
sb.AppendLine("```");
sb.AppendLine();
return sb.ToString();
}
///
/// Generates a combined diagram showing both the query structure and method chain.
///
/// The LINQ QueryBreakdown to visualize.
/// Optional title for the diagram.
/// A string containing both diagrams.
public static string GenerateCombinedDiagram(LinqQueryBreakdown queryBreakdown, string? title = null)
{
var sb = new System.Text.StringBuilder();
if (!string.IsNullOrWhiteSpace(title))
{
sb.AppendLine($"## {title}");
sb.AppendLine();
}
// Method chain
sb.AppendLine("### LINQ Method Chain");
sb.AppendLine();
sb.Append(GenerateMethodChainDiagram(queryBreakdown));
// SQL Structure
sb.AppendLine("### SQL Query Structure");
sb.AppendLine();
sb.Append(GenerateMermaidDiagram(queryBreakdown));
return sb.ToString();
}
}