Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions cli/docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,47 @@ Findings are logged one per line as `path:line:column [rule-id] message`, at
Exit code `0` if nothing at or above `--fail-on` was found; `1` otherwise (or
if a given `--path` doesn't exist).

### `syncsql parser`

Open a SQL file in a read-only, keyboard-driven terminal dashboard:

```bash
syncsql parser --file ./procedure.sql
syncsql parser --file ./package.sql --engine oracle
syncsql parser --file ./procedure.sql --plain
# From the repository, without installing:
dotnet run --project cli/src/SyncSql.Cli -- parser --file ./procedure.sql
```

SQL Server is the default dialect. Use `--engine oracle` for PL/SQL; the
command uses the existing ScriptDom and ANTLR grammars and lineage analyzers.
No database connection or server configuration is required.

The dashboard has seven views: syntax tree, tokens (including comments and
whitespace), referenced objects, alias bindings, column references,
diagnostics, and full source. Select a syntax node or token to see its SQL
and line/column location in the right pane. Objects include static/dynamic
origin information. References are inferred from the script, without catalog
resolution; syntax errors leave a partial tree available for inspection.

| Key | Action |
| --- | --- |
| Tab / Shift+Tab, Left / Right | Switch views |
| 1–7 | Jump to a view |
| Up / Down or k / j | Select a piece |
| Home / End | Select first / last piece |
| /, then Enter | Filter piece names and descriptions |
| Esc while filtering | Clear filter |
| PageUp / PageDown | Scroll the detail/source pane |
| h / l | Pan the detail pane horizontally |
| q / Esc / Ctrl+C | Exit |

Use a terminal of at least 70 columns by 12 rows. Resizing redraws the
dashboard. `--plain`, redirected input/output, or `TERM=dumb` prints all views
as text without interactive controls. Exit code is 1 for parse errors or an
unreadable file and 0 for a clean parse, including an empty file. The input
file is never modified.

## Configuration

`syncsql` reads the exact same `config/servers.json` schema as the
Expand Down
46 changes: 46 additions & 0 deletions cli/src/SyncSql.Cli/Commands/ParserCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using System.CommandLine;
using SyncSql.Cli.Parsing;

namespace SyncSql.Cli.Commands;

internal static class ParserCommand
{
public static Command Build(ParserTerminal? terminal = null)
{
terminal ??= new ParserTerminal();
Option<string> file = new("--file") { Required = true, Description = "SQL file to inspect (read only)." };
Option<string> engine = new("--engine") { Description = "SQL dialect: mssql (default) or oracle." };
engine.AcceptOnlyFromAmong("mssql", "oracle");
Option<bool> plain = new("--plain") { Description = "Print all pieces as text instead of opening the dashboard." };
Command command = new("parser", "Explore a SQL file's syntax tree, tokens, lineage, and diagnostics.") { file, engine, plain };
command.SetAction(async (result, cancellationToken) =>
{
try
{
string path = Path.GetFullPath(result.GetValue(file)!);
string sql = await File.ReadAllTextAsync(path, cancellationToken);
string dialect = result.GetValue(engine) ?? "mssql";
SqlInspection inspection = SqlInspection.Parse(path, sql, dialect);
if (UsePlainOutput(result.GetValue(plain), terminal.InputRedirected, terminal.OutputRedirected, terminal.TerminalType))
{
ParserDashboard.Print(inspection, terminal.Output);
}
else
{
ParserDashboard.Run(inspection, terminal, cancellationToken);
}

return inspection.HasErrors ? 1 : 0;
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
terminal.Error.WriteLine($"Cannot inspect SQL file: {ParserDashboard.Safe(exception.Message)}");
return 1;
}
});
return command;
}

internal static bool UsePlainOutput(bool requested, bool inputRedirected, bool outputRedirected, string? terminalType) =>
requested || inputRedirected || outputRedirected || string.Equals(terminalType, "dumb", StringComparison.Ordinal);
}
185 changes: 185 additions & 0 deletions cli/src/SyncSql.Cli/Parsing/ParserDashboard.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
using System.Text;

namespace SyncSql.Cli.Parsing;

internal static class ParserDashboard
{
// Never allow SQL text, filenames or diagnostics to inject terminal control sequences.
internal static string Safe(string value) => new(value.Select(c => char.IsControl(c) ? ' ' : c).ToArray());

public static void Print(SqlInspection inspection, TextWriter output)
{
output.WriteLine($"{Safe(inspection.Path)} ({inspection.Engine})");
foreach (SqlSection section in inspection.Sections)
{
output.WriteLine($"\n[{section.Name}] {section.Pieces.Count}");
foreach (SqlPiece piece in section.Pieces)
{
foreach (string line in inspection.Describe(piece).Split('\n'))
{
output.WriteLine(Safe(line));
}
}
}
}

public static void Run(SqlInspection inspection, ParserTerminal terminal, CancellationToken cancellationToken)
{
DashboardState state = new(inspection);
bool originalControlC = terminal.ControlCAsInput;
try
{
terminal.ControlCAsInput = true;
terminal.Output.Write("\u001b[?1049h\u001b[?25l");
int lastWidth = 0;
int lastHeight = 0;
bool redraw = true;
while (!cancellationToken.IsCancellationRequested)
{
int width = Math.Max(1, terminal.Width);
int height = Math.Max(1, terminal.Height);
if (redraw || width != lastWidth || height != lastHeight)
{
terminal.Output.Write(Render(state, width, height));
lastWidth = width;
lastHeight = height;
redraw = false;
}
if (terminal.KeyAvailable)
{
if (!state.Handle(terminal.ReadKey(), Math.Max(1, height - 7))) { break; }
redraw = true;
}
else
{
terminal.Wait(cancellationToken);
}
}
}
finally
{
try { terminal.Output.Write("\u001b[0m\u001b[?25h\u001b[?1049l"); }
finally { terminal.ControlCAsInput = originalControlC; }
}
}

internal static string Render(DashboardState state, int width, int height)
{
// Leave the final terminal column unused to avoid automatic line wrapping.
int columns = Math.Max(1, width - 1);
List<string> lines = [];
if (width < 70 || height < 12)
{
lines.Add("Resize terminal to at least 70 x 12. Press q to quit.");
}
else
{
SqlInspection inspection = state.Inspection;
lines.Add($" SYNCSQL / PARSER {inspection.Engine.ToUpperInvariant()} {(inspection.HasErrors ? "PARSE ERRORS - partial tree" : "PARSED")}");
lines.Add(" " + inspection.Path);
lines.Add(" " + string.Join(" ", inspection.Sections.Select((s, i) =>
$"{(i == state.Section ? ">" : "")}{i + 1}:{s.Name.Replace("Syntax tree", "Tree", StringComparison.Ordinal).Replace("Diagnostics", "Errors", StringComparison.Ordinal)}")));
int left = Math.Clamp(columns / 3, 24, 48);
int right = columns - left - 3;
lines.Add(Fit($" {inspection.Sections[state.Section].Name} / {state.Items.Count} pieces", left) + " | " + "DETAIL / SQL");
int rows = height - 7;
int start = state.Selected / rows * rows;
string[] details = state.Items.Count == 0 ? ["No pieces match this view."] :
inspection.Describe(state.Items[state.Selected]).Replace("\r", "", StringComparison.Ordinal).Split('\n');
state.DetailRow = Math.Clamp(state.DetailRow, 0, Math.Max(0, details.Length - rows));
for (int row = 0; row < rows; row++)
{
int index = start + row;
string label = index < state.Items.Count ?
$"{(index == state.Selected ? ">" : " ")} {state.Items[index].Name}" : "";
int detailIndex = state.DetailRow + row;
string detail = detailIndex < details.Length ? details[detailIndex] : "";
detail = detail[Math.Min(state.DetailColumn, detail.Length)..];
string line = Fit(label, left) + " | " + Fit(detail, right);
lines.Add(line);
}
lines.Add($" / Filter: {state.Filter}{(state.EditingFilter ? "_ (Enter to apply, Esc to clear)" : "")} | detail line {state.DetailRow + 1}/{details.Length}");
lines.Add(" Tab/Left/Right: view Up/Down/j/k: select 1-7: view /: filter");
lines.Add(" PgUp/PgDn: scroll detail h/l: pan detail Home/End: first/last q/Esc: quit");
}
StringBuilder frame = new("\u001b[H");
for (int row = 0; row < height; row++)
{
if (row > 0) { frame.Append("\r\n"); }
if (row < 4) { frame.Append("\u001b[36m"); }
frame.Append(Fit(row < lines.Count ? lines[row] : "", columns));
frame.Append("\u001b[0m");
}
return frame.ToString();
}

private static string Fit(string text, int width)
{
string safe = Safe(text);
return safe.Length > width ? safe[..width] : safe.PadRight(width);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Account for terminal display width when fitting rows

When a filename, identifier, or SQL line contains CJK characters, emoji, or combining marks, string.Length does not equal the number of terminal cells occupied. A row containing double-width glyphs can therefore exceed the reserved final column and wrap, corrupting the dashboard layout; truncation may also split a surrogate pair. Fit, truncate, pad, and horizontally pan content using terminal display-cell width rather than UTF-16 code-unit count.

Useful? React with 👍 / 👎.

}
}

internal sealed class DashboardState(SqlInspection inspection)
{
public SqlInspection Inspection { get; } = inspection;
public int Section { get; private set; }
public int Selected { get; private set; }
public int DetailRow { get; set; }
public int DetailColumn { get; private set; }
public string Filter { get; private set; } = "";
public bool EditingFilter { get; private set; }
public IReadOnlyList<SqlPiece> Items { get; private set; } = inspection.Sections[0].Pieces;

public bool Handle(ConsoleKeyInfo key, int pageSize)
{
if (key.Key == ConsoleKey.C && key.Modifiers.HasFlag(ConsoleModifiers.Control)) { return false; }
if (EditingFilter)
{
if (key.Key == ConsoleKey.Enter) { EditingFilter = false; }
else if (key.Key == ConsoleKey.Escape) { Filter = ""; EditingFilter = false; }
else if (key.Key == ConsoleKey.Backspace) { Filter = Filter[..Math.Max(0, Filter.Length - 1)]; }
else if (!char.IsControl(key.KeyChar)) { Filter += key.KeyChar; }
Refresh();
return true;
}
if (key.Key is ConsoleKey.Q or ConsoleKey.Escape) { return false; }
if (key.KeyChar == '/') { EditingFilter = true; return true; }
int section = Section;
if (key.Key == ConsoleKey.Tab) { section += key.Modifiers.HasFlag(ConsoleModifiers.Shift) ? -1 : 1; }
else if (key.Key == ConsoleKey.RightArrow) { section++; }
else if (key.Key == ConsoleKey.LeftArrow) { section--; }
else if (key.KeyChar is >= '1' and <= '7') { section = key.KeyChar - '1'; }
if (section != Section)
{
Section = (section + Inspection.Sections.Count) % Inspection.Sections.Count;
Filter = "";
Refresh();
return true;
}
int selected = Selected;
switch (key.Key)
{
case ConsoleKey.DownArrow: case ConsoleKey.J: selected++; break;
case ConsoleKey.UpArrow: case ConsoleKey.K: selected--; break;
case ConsoleKey.Home: selected = 0; break;
case ConsoleKey.End: selected = Items.Count - 1; break;
case ConsoleKey.PageDown: DetailRow += pageSize; break;
case ConsoleKey.PageUp: DetailRow = Math.Max(0, DetailRow - pageSize); break;
case ConsoleKey.H: DetailColumn = Math.Max(0, DetailColumn - 8); break;
case ConsoleKey.L: DetailColumn += 8; break;
}
selected = Math.Clamp(selected, 0, Math.Max(0, Items.Count - 1));
if (selected != Selected) { Selected = selected; DetailRow = 0; DetailColumn = 0; }
return true;
}

private void Refresh()
{
Items = Inspection.Sections[Section].Pieces.Where(p => p.Name.Contains(Filter, StringComparison.OrdinalIgnoreCase) ||
(p.Description?.Contains(Filter, StringComparison.OrdinalIgnoreCase) ?? false)).ToArray();
Selected = 0;
DetailRow = 0;
DetailColumn = 0;
}
}
21 changes: 21 additions & 0 deletions cli/src/SyncSql.Cli/Parsing/ParserTerminal.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
namespace SyncSql.Cli.Parsing;

// Keep the operating-system console boundary separate from navigation and lifecycle logic.
internal class ParserTerminal
{
public virtual TextWriter Output => Console.Out;
public virtual TextWriter Error => Console.Error;
public virtual bool InputRedirected => Console.IsInputRedirected;
public virtual bool OutputRedirected => Console.IsOutputRedirected;
public virtual string? TerminalType => Environment.GetEnvironmentVariable("TERM");
public virtual int Width => Console.WindowWidth;
public virtual int Height => Console.WindowHeight;
public virtual bool KeyAvailable => Console.KeyAvailable;
public virtual bool ControlCAsInput
{
get => Console.TreatControlCAsInput;
set => Console.TreatControlCAsInput = value;
}
public virtual ConsoleKeyInfo ReadKey() => Console.ReadKey(intercept: true);
public virtual void Wait(CancellationToken cancellationToken) => cancellationToken.WaitHandle.WaitOne(80);
}
Loading
Loading