CSharp · Console
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
internal static class SqlCmdScriptParser
{
private static readonly Command[] ControlCommands =
{
new()
{
Id = "setvar",
Pattern = new(@":(?<command>setvar)\s+(?<name>\w+)\s+""(?<value>.*)"""),
IsFullLine = true,
MatchSubstitution =
(match, variables) =>
{
variables.Add(match.Groups["name"].Value, match.Groups["value"].Value);
return string.Empty;
},
},
new()
{
Id = "on error",
Pattern = new(@":(?<command>on error)\s+(?<value>exit|ignore)"),
IsFullLine = true,
MatchSubstitution = (_, _) => string.Empty,
},
new()
{
Id = "$",
Pattern = new(@"(?<command>\$)\((?<name>\w+)\)"),
IsFullLine = false,
MatchSubstitution =
(match, variables) =>
variables.GetValueOrDefault(match.Groups["name"].Value) ?? string.Empty,
},
};
private static readonly IReadOnlyDictionary<string, Command> ControlCommandsMap =
ControlCommands.ToDictionary(c => c.Id, StringComparer.OrdinalIgnoreCase);
private static readonly Regex ControlCommandsPattern = GetControlCommandsPattern();
private static readonly Regex BatchSeparatorPattern = new Regex("GO").ToFullLine();
public static IReadOnlyCollection<string> Parse(
string input, IReadOnlyDictionary<string, string> variables = null) =>
input
.SubstituteControlCommands(variables)
.SplitBatch();
private static Regex GetControlCommandsPattern()
{
var patterns = ControlCommands
.Select(c => c.IsFullLine ? c.Pattern.ToFullLine() : c.Pattern)
.Select(p => $"({p})")
.ToList();
var combinedPattern = string.Join("|", patterns);
return new Regex(combinedPattern, RegexOptions.Multiline | RegexOptions.Compiled);
}
private static Regex ToFullLine(this Regex source) =>
new($@"^\s*{source}\s*$\n?", RegexOptions.Multiline | RegexOptions.Compiled);
private static string SubstituteControlCommands(
this string input, IReadOnlyDictionary<string, string> variables)
{
var establishedVariables = new Dictionary<string, string>(
variables ?? new Dictionary<string, string>(), StringComparer.OrdinalIgnoreCase);
return ControlCommandsPattern
.Replace(input, match => SubstituteControlCommandMatch(match, establishedVariables));
}
private static string SubstituteControlCommandMatch(
Match match, Dictionary<string, string> variables)
{
var commandId = match.Groups["command"].Value;
var command = ControlCommandsMap.GetValueOrDefault(commandId)
?? throw new InvalidOperationException($"Unknown command: {commandId}");
return command.MatchSubstitution(match, variables);
}
private static IReadOnlyCollection<string> SplitBatch(this string input) =>
BatchSeparatorPattern.Split(input)
.Where(s => !string.IsNullOrEmpty(s))
.ToList();
private sealed class Command
{
public string Id { get; init; } = string.Empty;
public Regex Pattern { get; init; } = new(string.Empty);
public bool IsFullLine { get; init; }
public Func<Match, Dictionary<string, string>, string> MatchSubstitution { get; init; } =
(_, _) => string.Empty;
}
}
public static class Program
{
public static void Main()
{
var inputScript =
"""
/*
Deployment script for MessageQueue
This code was generated by a tool.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
*/
:setvar DatabaseName "MessageQueue"
:setvar DefaultFilePrefix "MessageQueue"
GO
:on error exit
GO
/*
Detect SQLCMD mode and disable script execution if SQLCMD mode is not supported.
To re-enable the script after enabling SQLCMD mode, execute the following:
SET NOEXEC OFF;
*/
:setvar __IsSqlCmdEnabled "True"
GO
IF N'$(__IsSqlCmdEnabled)' NOT LIKE N'True'
BEGIN
PRINT N'SQLCMD mode must be enabled to successfully execute this script.';
SET NOEXEC ON;
END
GO
USE [$(DatabaseName)];
GO
PRINT N'Creating SqlSchema [MessageQueue]...';
""";
// Set your variables here
var variables = new Dictionary<string, string>();
var batches = SqlCmdScriptParser.Parse(inputScript, variables);
var i = 0;
foreach (var batch in batches)
{
$"------------------ Batch {i++} ---------------".Dump();
Console.WriteLine(batch);
}
}
}