|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.IO; |
| 4 | +using Microsoft.SqlServer.TransactSql.ScriptDom; |
| 5 | +using Newtonsoft.Json; |
| 6 | + |
| 7 | +namespace SqlParserApp |
| 8 | +{ |
| 9 | + class Program |
| 10 | + { |
| 11 | + static void Main(string[] args) |
| 12 | + { |
| 13 | + string sqlQuery = string.Empty; |
| 14 | + if (args.Length == 0) |
| 15 | + { |
| 16 | + Console.WriteLine("Please provide a SQL query string (--string) or file (--file) as an argument."); |
| 17 | + return; |
| 18 | + } |
| 19 | + if (args[0] == "--file") |
| 20 | + { |
| 21 | + if (args.Length < 2) |
| 22 | + { |
| 23 | + Console.WriteLine("Please provide a file path after --file."); |
| 24 | + return; |
| 25 | + } |
| 26 | + string filePath = args[1]; |
| 27 | + if (!File.Exists(filePath)) |
| 28 | + { |
| 29 | + Console.WriteLine($"File not found: {filePath}"); |
| 30 | + return; |
| 31 | + } |
| 32 | + sqlQuery = File.ReadAllText(filePath); |
| 33 | + } |
| 34 | + else if (args[0] == "--string") |
| 35 | + { |
| 36 | + sqlQuery = string.Join(" ", args); // Join the array elements into a single string |
| 37 | + } |
| 38 | + else |
| 39 | + { |
| 40 | + Console.WriteLine("Invalid argument. Use --file or --string."); |
| 41 | + } |
| 42 | + |
| 43 | + IList<ParseError> errors = ParseSqlQuery(sqlQuery); |
| 44 | + |
| 45 | + var errorList = new List<Dictionary<string, object>>(); |
| 46 | + |
| 47 | + foreach (var error in errors) |
| 48 | + { |
| 49 | + var errorDict = new Dictionary<string, object> |
| 50 | + { |
| 51 | + { "Line", error.Line }, |
| 52 | + { "Column", error.Column }, |
| 53 | + { "Error", error.Message } |
| 54 | + }; |
| 55 | + errorList.Add(errorDict); |
| 56 | + } |
| 57 | + |
| 58 | + string jsonOutput = JsonConvert.SerializeObject(errorList, Formatting.Indented); |
| 59 | + Console.WriteLine(jsonOutput); |
| 60 | + } |
| 61 | + |
| 62 | + static IList<ParseError> ParseSqlQuery(string sqlQuery) |
| 63 | + { |
| 64 | + TSql150Parser parser = new TSql150Parser(false); |
| 65 | + IList<ParseError> errors; |
| 66 | + using (TextReader reader = new StringReader(sqlQuery)) |
| 67 | + { |
| 68 | + parser.Parse(reader, out errors); |
| 69 | + } |
| 70 | + return errors; |
| 71 | + } |
| 72 | + } |
| 73 | +} |
0 commit comments