Files
SQLVision/SQLVision/Services/SqlCommentParser.cs
2026-01-05 00:37:54 +03:00

107 lines
3.7 KiB
C#

using SQLVision.Enums;
using SQLVision.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
namespace SQLVision.Services;
public sealed class SqlCommentParser
{
private static readonly Regex DescriptionRegex =
new(@"--\s*@description\s+""(.+)""", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex ParamRegex =
new(@"--\s*@param\s+(\w+)\s+(\w+)\s+""(.+?)""(?:\s+default=""(.*?)"")?(?:\s+@table\s+""(.+?)"")?(?:\s+dependsOn=""(.*?)"")?",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex OutputRegex =
new(@"--\s*@output\s+([\w:]+)\s+""(.+?)""",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
public ScriptMetadata Parse(string filePath)
{
var text = File.ReadAllText(filePath);
var lines = text.Split(Environment.NewLine);
string? description = null;
var parameters = new List<ParameterDefinition>();
var outputs = new List<OutputDefinition>();
foreach (var line in lines)
{
var descMatch = DescriptionRegex.Match(line);
if (descMatch.Success)
{
description = descMatch.Groups[1].Value;
continue;
}
var paramMatch = ParamRegex.Match(line);
if (paramMatch.Success)
{
var name = paramMatch.Groups[1].Value;
var typeStr = paramMatch.Groups[2].Value;
var displayName = paramMatch.Groups[3].Value;
var defaultValue = paramMatch.Groups[4].Success ? paramMatch.Groups[4].Value : null;
var tableQuery = paramMatch.Groups[5].Success ? paramMatch.Groups[5].Value : null;
var dependsOn = paramMatch.Groups[6].Success ? paramMatch.Groups[6].Value : null;
var parameterType = typeStr.ToLower() switch
{
"int" => ParameterType.Int,
"string" => ParameterType.String,
"datetime" => ParameterType.DateTime,
"bool" => ParameterType.Bool,
"table" => ParameterType.Table,
_ => ParameterType.String
};
parameters.Add(new ParameterDefinition
{
Name = name,
Type = parameterType,
DisplayName = displayName,
DefaultValue = defaultValue,
TableQuery = tableQuery,
DependsOn = dependsOn
});
continue;
}
var outputMatch = OutputRegex.Match(line);
if (outputMatch.Success)
{
var typeStr = outputMatch.Groups[1].Value;
var title = outputMatch.Groups[2].Value;
var outputType = typeStr.ToLower() switch
{
"table" => OutputType.Table,
"chart:line" => OutputType.ChartLine,
"chart:bar" => OutputType.ChartBar,
"chart:pie" => OutputType.ChartPie,
_ => OutputType.Table
};
outputs.Add(new OutputDefinition
{
Type = outputType,
Title = title
});
}
}
return new ScriptMetadata
{
FilePath = filePath,
Name = Path.GetFileNameWithoutExtension(filePath),
Description = description,
Parameters = parameters,
Outputs = outputs
};
}
}