using System; using System.Collections.Generic; using System.Text.Json; using System.Runtime.InteropServices; namespace Scorpiox.Ssms; /// /// CLI + permanent test harness for scorpiox-ssms-core.dll / /// libscorpiox-ssms-core.so. /// /// scorpiox-ssms-core-console --test /// scorpiox-ssms-core-console --test --live /// scorpiox-ssms-core-console version /// scorpiox-ssms-core-console connect-test [db] /// scorpiox-ssms-core-console query [max_rows] [timeout_s] /// scorpiox-ssms-core-console tree [db] [schema] [obj] /// scorpiox-ssms-core-console script /// scorpiox-ssms-core-console editgrid-load [top_n] /// scorpiox-ssms-core-console editgrid-apply
[dry_run] /// scorpiox-ssms-core-console activity /// scorpiox-ssms-core-console storage [arg] /// scorpiox-ssms-core-console admin [db] [arg] /// scorpiox-ssms-core-console kill /// /// --test exits 0 only when EVERY assertion passes. Live credentials come /// ONLY from the environment (SSMS_TEST_HOST / _PORT / _USER / _PASS / _DB); /// nothing in this file contains a hostname, IP address or password. /// public static class Program { static int s_pass, s_fail, s_skip; static void Check(bool ok, string name, string? detail = null) { if (ok) { s_pass++; Console.WriteLine($"PASS {name}"); } else { s_fail++; Console.WriteLine($"FAIL {name}{(detail is null ? "" : " << " + Trunc(detail, 220))}"); } } static void Skip(string name, string why) { s_skip++; Console.WriteLine($"SKIP {name} ({why})"); } static string Trunc(string s, int n) => s.Length <= n ? s : s.Substring(0, n) + "…"; static bool JsonHas(string json, string needle) => json.IndexOf(needle, StringComparison.Ordinal) >= 0; // A target that cannot be a TDS listener — used to prove a failed // connect returns clean JSON instead of crashing or exiting the process. const string DeadHost = "127.0.0.1"; const int DeadPort = 1; static readonly string DeadConn = "{\"host\":\"127.0.0.1\",\"port\":1,\"user\":\"sa\",\"password\":\"x\",\"timeout_s\":2}"; public static int Main(string[] args) { if (args.Length == 0) { Usage(); return 2; } string cmd = args[0]; if (cmd == "--test") return RunAllTests(args); if (cmd == "--help" || cmd == "-h") { Usage(); return 0; } return RunCli(cmd, args); } // ── TEST MODE ───────────────────────────────────────────────────────── static int RunAllTests(string[] args) { bool live = false; for (int i = 1; i < args.Length; i++) if (args[i] == "--live") live = true; Console.WriteLine($"scorpiox-ssms-core.console — engine {SsmsInterop.Version}"); Console.WriteLine($"runtime : {Environment.Version} / {(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "Windows" : RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "macOS" : "Linux")} {RuntimeInformation.OSArchitecture}"); Console.WriteLine(); // ── version / last_error / free contract ────────────────────────── Check(!string.IsNullOrEmpty(SsmsInterop.Version), "version is non-empty", SsmsInterop.Version); Check(SsmsInterop.Version.Split('.').Length >= 2, "version looks like semver", SsmsInterop.Version); Check(SsmsInterop.Version == SsmsInterop.Version, "version is stable across calls"); Check(SsmsInterop.LastError != null, "last_error never null"); // free(IntPtr.Zero) must be NULL-safe try { SsmsInterop.free(IntPtr.Zero); Check(true, "free(IntPtr.Zero) is NULL-safe"); } catch (Exception e) { Check(false, "free(IntPtr.Zero) is NULL-safe", e.Message); } // ── NULL / empty parameter rejection on EVERY export ────────────── // Each of these would be a segfault in a naive implementation. Check(JsonHas(S(SsmsInterop.connect_test("h", 1433, "", "", "", 0, 2)), "\"ok\":false"), "connect_test empty user -> ok:false"); Check(JsonHas(S(SsmsInterop.connect_test("", 1433, "sa", "", "", 0, 2)), "\"ok\":false"), "connect_test empty host -> ok:false"); Check(JsonHas(SsmsInterop.CallTree("", "databases", null, null, null), "\"ok\":false"), "tree empty conn -> ok:false"); Check(JsonHas(SsmsInterop.CallTree("{}", "", null, null, null), "\"ok\":false"), "tree empty node_kind -> ok:false"); Check(JsonHas(SsmsInterop.CallQuery("", null, "SELECT 1", 10, 5), "\"ok\":false"), "query empty conn -> ok:false"); Check(JsonHas(SsmsInterop.CallQuery("{}", null, "", 10, 5), "\"ok\":false"), "query empty sql -> ok:false"); Check(JsonHas(SsmsInterop.CallKillSpid("", 54), "\"ok\":false"), "kill_spid empty conn -> ok:false"); Check(JsonHas(SsmsInterop.CallScriptObject("", null, "table", "dbo", "t", "create"), "\"ok\":false"), "script_object empty conn -> ok:false"); Check(JsonHas(SsmsInterop.CallScriptObject("{}", null, "", "dbo", "t", "create"), "\"ok\":false"), "script_object empty kind -> ok:false"); Check(JsonHas(SsmsInterop.CallScriptObject("{}", null, "table", "dbo", "", "create"), "\"ok\":false"), "script_object empty obj -> ok:false"); Check(JsonHas(SsmsInterop.CallScriptObject("{}", null, "table", "dbo", "t", ""), "\"ok\":false"), "script_object empty action -> ok:false"); Check(JsonHas(SsmsInterop.CallEditGridLoad("", null, "dbo", "t", 200), "\"ok\":false"), "editgrid_load empty conn -> ok:false"); Check(JsonHas(SsmsInterop.CallEditGridLoad("{}", null, "dbo", "", 200), "\"ok\":false"), "editgrid_load empty table -> ok:false"); Check(JsonHas(SsmsInterop.CallEditGridApply("", null, "dbo", "t", "[]", true), "\"ok\":false"), "editgrid_apply empty conn -> ok:false"); Check(JsonHas(SsmsInterop.CallEditGridApply("{}", null, "dbo", "t", "", true), "\"ok\":false"), "editgrid_apply empty ops -> ok:false"); Check(JsonHas(SsmsInterop.CallActivity("", "sessions"), "\"ok\":false"), "activity empty conn -> ok:false"); Check(JsonHas(SsmsInterop.CallActivity("{}", ""), "\"ok\":false"), "activity empty view -> ok:false"); Check(JsonHas(SsmsInterop.CallStorage("", null, "files", null), "\"ok\":false"), "storage empty conn -> ok:false"); Check(JsonHas(SsmsInterop.CallStorage("{}", null, "", null), "\"ok\":false"), "storage empty action -> ok:false"); Check(JsonHas(SsmsInterop.CallAdmin("", "jobs", null, null), "\"ok\":false"), "admin empty conn -> ok:false"); Check(JsonHas(SsmsInterop.CallAdmin("", "", null, null), "\"ok\":false"), "admin empty kind -> ok:false"); // ── malformed conn_json ─────────────────────────────────────────── Check(JsonHas(SsmsInterop.CallQuery("not json at all", null, "SELECT 1", 10, 5), "valid JSON"), "query malformed JSON -> names JSON"); Check(JsonHas(SsmsInterop.CallQuery("[1,2,3]", null, "SELECT 1", 10, 5), "\"ok\":false"), "query array conn -> ok:false"); Check(JsonHas(SsmsInterop.CallQuery("{\"user\":\"sa\"}", null, "SELECT 1", 10, 5), "host"), "query missing host -> error names host"); Check(JsonHas(SsmsInterop.CallQuery("{\"host\":\"h\"}", null, "SELECT 1", 10, 5), "user"), "query missing user -> error names user"); // ── unknown enumerations ────────────────────────────────────────── Check(JsonHas(SsmsInterop.CallTree(DeadConn, "no_such_node_kind", null, null, null), "\"ok\":false"), "tree unknown node_kind -> ok:false"); Check(JsonHas(SsmsInterop.CallActivity(DeadConn, "no_such_view"), "unknown activity view"), "activity unknown view -> named"); Check(JsonHas(SsmsInterop.CallStorage(DeadConn, "db", "no_such_action", null), "unknown storage action"), "storage unknown action -> named"); Check(JsonHas(SsmsInterop.CallAdmin(DeadConn, "no_such_kind", null, null), "unknown admin kind"), "admin unknown kind -> named"); Check(JsonHas(SsmsInterop.CallScriptObject(DeadConn, "db", "table", "dbo", "t", "no_such_action"), "unknown action"), "script_object unknown action -> named"); // ── dead host: clean JSON, never exit()/crash ───────────────────── string r; r = SsmsInterop.CallConnectTest(DeadHost, DeadPort, "sa", "x", "", 0, 2); Check(JsonHas(r, "\"ok\":false"), "connect_test dead host -> ok:false", r); Check(JsonHas(r, "elapsed_ms"), "connect_test dead host reports elapsed_ms", r); Check(JsonHas(r, "error"), "connect_test dead host reports error", r); Check(JsonHas(r, "server_version"), "connect_test dead host has server_version field", r); Check(JsonHas(r, "spid"), "connect_test dead host has spid field", r); Check(JsonHas(SsmsInterop.CallQuery(DeadConn, "master", "SELECT 1", 10, 2), "\"ok\":false"), "query dead host -> ok:false"); Check(JsonHas(SsmsInterop.CallTree(DeadConn, "databases", null, null, null), "\"ok\":false"), "tree dead host -> ok:false"); Check(JsonHas(SsmsInterop.CallActivity(DeadConn, "sessions"), "\"ok\":false"), "activity dead host -> ok:false"); Check(JsonHas(SsmsInterop.CallStorage(DeadConn, "master", "files", null), "\"ok\":false"), "storage dead host -> ok:false"); Check(JsonHas(SsmsInterop.CallAdmin(DeadConn, "logins", null, null), "\"ok\":false"), "admin dead host -> ok:false"); Check(JsonHas(SsmsInterop.CallKillSpid(DeadConn, 54), "\"ok\":false"), "kill_spid dead host -> ok:false"); Check(JsonHas(SsmsInterop.CallScriptObject(DeadConn, "master", "table", "dbo", "t", "create"), "\"ok\":false"), "script_object dead host -> ok:false"); Check(JsonHas(SsmsInterop.CallEditGridLoad(DeadConn, "master", "dbo", "t", 10), "\"ok\":false"), "editgrid_load dead host -> ok:false"); Check(JsonHas(SsmsInterop.CallEditGridApply(DeadConn, "master", "dbo", "t", "[{\"op\":\"insert\",\"values\":{\"a\":1}}]", true), "\"ok\":false"), "editgrid_apply dead host -> ok:false"); // last_error must carry a diagnostic after a failure SsmsInterop.CallQuery(DeadConn, "master", "SELECT 1", 10, 2); string le = SsmsInterop.LastError; Check(!string.IsNullOrEmpty(le), "last_error populated after failure", le ?? ""); Console.WriteLine($" last_error: {Trunc(le, 160)}"); // ── ops validation that needs no server ─────────────────────────── Check(JsonHas(SsmsInterop.CallEditGridApply(DeadConn, "db", "dbo", "t", "not json", true), "not valid JSON"), "editgrid_apply malformed ops JSON -> named"); Check(JsonHas(SsmsInterop.CallEditGridApply(DeadConn, "db", "dbo", "t", "[]", true), "non-empty"), "editgrid_apply empty ops array -> named"); // ── the JSON contract is valid JSON on every path ───────────────── string[] probes = new[] { SsmsInterop.CallQuery(DeadConn, null, "SELECT 1", 10, 2), SsmsInterop.CallTree(DeadConn, "databases", null, null, null), SsmsInterop.CallActivity(DeadConn, "sessions"), SsmsInterop.CallAdmin(DeadConn, "jobs", null, null), SsmsInterop.CallStorage(DeadConn, null, "files", null), SsmsInterop.CallConnectTest(DeadHost, DeadPort, "sa", "x", "", 0, 2), }; int okJson = 0; foreach (var p in probes) if (p.StartsWith("{") && p.EndsWith("}")) okJson++; Check(okJson == probes.Length, $"all {probes.Length} error paths return a JSON object", $"{okJson}/{probes.Length}"); // ── no double-free / leak crash across many calls ───────────────── try { for (int i = 0; i < 500; i++) SsmsInterop.free(SsmsInterop.query(DeadConn, "master", "SELECT 1", 1, 1)); Check(true, "500 query/free cycles survive"); } catch (Exception e) { Check(false, "500 query/free cycles survive", e.Message); } // ── LIVE SQL probe ──────────────────────────────────────────────── if (!live) { Skip("live SQL Server probe", "pass --live with SSMS_TEST_HOST/USER/PASS set"); } else { string host = Env("SSMS_TEST_HOST"); string user = Env("SSMS_TEST_USER"); string pass = Env("SSMS_TEST_PASS"); string db = Env("SSMS_TEST_DB"); int port = int.TryParse(Env("SSMS_TEST_PORT"), out int p) ? p : 1433; if (host.Length == 0 || user.Length == 0) { Skip("live SQL Server probe", "SSMS_TEST_HOST / SSMS_TEST_USER not set"); } else { RunLive(host, port, user, pass, db); } } Console.WriteLine(); Console.WriteLine($"{s_pass} PASS, {s_fail} FAIL, {s_skip} SKIP"); return s_fail == 0 ? 0 : 1; } static string Env(string name) => Environment.GetEnvironmentVariable(name) ?? ""; static void RunLive(string host, int port, string user, string pass, string db) { Console.WriteLine(); Console.WriteLine("── live probe ──────────────────────────────────────────────"); string ct = SsmsInterop.CallConnectTest(host, port, user, pass, db.Length > 0 ? db : "master", 0, 10); Check(JsonHas(ct, "\"ok\":true"), "live connect_test -> ok:true", ct); Check(JsonHas(ct, "server_version") && !JsonHas(ct, "\"server_version\":null"), "live connect_test reports server_version", ct); Check(JsonHas(ct, "\"spid\":") && !JsonHas(ct, "\"spid\":0"), "live connect_test reports a real spid", ct); Check(JsonHas(ct, "\"elapsed_ms\":"), "live connect_test reports elapsed_ms"); string conn = ToJson(host, port, user, pass, db.Length > 0 ? db : "master"); // GO batch splitter + multi-resultset + NULL vs "" + PRINT string multi = SsmsInterop.CallQuery(conn, db, "PRINT 'pico-print-marker'\n" + "SELECT CAST(NULL AS varchar(10)) AS the_null, CAST('' AS varchar(10)) AS the_empty, 42 AS n\n" + "GO\n" + "SELECT 'first' AS set_a\n" + "GO\n" + "SELECT 'second' AS set_b\n", 100, 20); Check(JsonHas(multi, "\"ok\":true"), "live GO/multi-resultset -> ok:true", multi); Check(JsonHas(multi, "\"batch\":1") && JsonHas(multi, "\"batch\":2") && JsonHas(multi, "\"batch\":3"), "live GO split produced 3 batches", multi); Check(JsonHas(multi, "pico-print-marker"), "live PRINT captured into messages", multi); Check(JsonHas(multi, "\"type\":\"print\""), "live PRINT message typed as print", multi); Check(JsonHas(multi, "[null,\"\",42]"), "live NULL vs empty string distinguished", multi); // regression: each result set must carry its OWN data, not the last row Check(JsonHas(multi, "\"set_a\"") && JsonHas(multi, "first") && JsonHas(multi, "\"set_b\"") && JsonHas(multi, "second"), "live multi-resultset rows are not cross-contaminated", multi); Check(JsonHas(multi, "\"columns\"") && JsonHas(multi, "\"nullable\""), "live result metadata has columns/nullable", multi); // multi-row: rows must be distinct (the non-copying yyjson trap) string rows = SsmsInterop.CallQuery(conn, db, "SELECT 1 AS n UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4", 100, 20); Check(JsonHas(rows, "[[1],[2],[3],[4]]"), "live multi-row values are distinct", rows); // server error surfaces number/severity/state/line string err = SsmsInterop.CallQuery(conn, db, "SELECT no_such_column AS x", 10, 20); Check(JsonHas(err, "\"ok\":false"), "live invalid column -> ok:false", err); Check(JsonHas(err, "\"number\":207"), "live error carries SQL number 207", err); Check(JsonHas(err, "\"severity\":16"), "live error carries severity 16", err); Check(JsonHas(err, "\"state\":") && JsonHas(err, "\"line\":"), "live error carries state and line", err); // max_rows truncation string trunc = SsmsInterop.CallQuery(conn, db, "SELECT 1 AS n UNION ALL SELECT 2 UNION ALL SELECT 3", 2, 20); Check(JsonHas(trunc, "\"truncated\":true"), "live max_rows truncates and flags it", trunc); // tree string dbs = SsmsInterop.CallTree(conn, "databases", null, null, null); Check(JsonHas(dbs, "\"ok\":true") && JsonHas(dbs, "\"kind\":\"db\""), "live tree databases returns nodes", Trunc(dbs, 300)); Check(JsonHas(dbs, "\"has_children\"") && JsonHas(dbs, "\"label\"") && JsonHas(dbs, "\"id\""), "live tree nodes match the /tree schema", Trunc(dbs, 300)); string sys = SsmsInterop.CallTree(conn, "system_databases", null, null, null); Check(JsonHas(sys, "master") && JsonHas(sys, "tempdb"), "live system_databases lists master/tempdb", Trunc(sys, 300)); string probeDb = db.Length > 0 ? db : "master"; // Discover a REAL table to point the column/grid/script probes at. // sys.objects and spt_values are VIEWS, and tree/editgrid read // sys.tables, so hard-coding a system object makes these rows fail // on every server. Discovering one keeps the live probe portable — // and SKIPs honestly when the login can see no tables. string tblSchema = "", tblName = ""; { string tbls = SsmsInterop.CallTree(conn, "tables", probeDb, null, null); int i = tbls.IndexOf("\"label\":\"", StringComparison.Ordinal); if (i >= 0) { i += 9; int j = tbls.IndexOf('"', i); if (j > i) { string label = tbls.Substring(i, j - i); // "schema.name" int dot = label.IndexOf('.'); if (dot > 0) { tblSchema = label.Substring(0, dot); tblName = label.Substring(dot + 1); } } } Console.WriteLine($" probe table: {(tblName.Length == 0 ? "(none visible)" : tblSchema + "." + tblName)} in {probeDb}"); } if (tblName.Length == 0) { Skip("live tree columns", "login sees no tables in " + probeDb); Skip("live tree indexes", "login sees no tables in " + probeDb); Skip("live script create on a real table", "login sees no tables in " + probeDb); Skip("live editgrid_load", "login sees no tables in " + probeDb); Skip("live editgrid_apply dry_run", "login sees no tables in " + probeDb); Skip("live editgrid quote escaping", "login sees no tables in " + probeDb); } else { string cols = SsmsInterop.CallTree(conn, "columns", probeDb, tblSchema, tblName); Check(JsonHas(cols, "\"ok\":true") && JsonHas(cols, "\"kind\":\"col\"") && JsonHas(cols, "NULL"), "live tree columns on " + tblSchema + "." + tblName + " returns columns", Trunc(cols, 300)); string idx = SsmsInterop.CallTree(conn, "indexes", probeDb, tblSchema, tblName); Check(JsonHas(idx, "\"ok\":true"), "live tree indexes on " + tblSchema + "." + tblName + " -> ok:true", Trunc(idx, 250)); string keys = SsmsInterop.CallTree(conn, "keys", probeDb, tblSchema, tblName); Check(JsonHas(keys, "\"ok\":true"), "live tree keys -> ok:true", Trunc(keys, 250)); string create = SsmsInterop.CallScriptObject(conn, probeDb, "table", tblSchema, tblName, "create"); Check(JsonHas(create, "CREATE TABLE") && JsonHas(create, "NOT NULL"), "live script create emits a CREATE TABLE for a real table", Trunc(create, 300)); string ins = SsmsInterop.CallScriptObject(conn, probeDb, "table", tblSchema, tblName, "insert"); Check(JsonHas(ins, "INSERT INTO") && JsonHas(ins, "VALUES"), "live script insert emits an INSERT template", Trunc(ins, 300)); // editgrid load against a real table string grid = SsmsInterop.CallEditGridLoad(conn, probeDb, tblSchema, tblName, 10); Check(JsonHas(grid, "\"ok\":true") && JsonHas(grid, "\"columns\"") && JsonHas(grid, "\"rows\""), "live editgrid_load returns columns + rows", Trunc(grid, 300)); Check(JsonHas(grid, "\"pk_columns\"") && JsonHas(grid, "\"read_only_reason\""), "live editgrid_load reports pk_columns and read_only_reason", Trunc(grid, 300)); // editgrid apply — dry_run ONLY, so nothing is written to the // server. Derive a REAL pk column (+ its value from row 0 when // the grid has rows) and a REAL editable column, so the DLL // sees a legitimate edit. Fake column names must be rejected // (that is what the malformed-op row below proves). string pkCol = "", colName = ""; string pkVal = "1", colVal = "\"x\""; bool havePk = false; try { using var gj = JsonDocument.Parse(grid); var groot = gj.RootElement; if (groot.TryGetProperty("pk_columns", out var pkArr) && pkArr.ValueKind == JsonValueKind.Array && pkArr.GetArrayLength() > 0) { pkCol = pkArr[0].GetString() ?? ""; havePk = pkCol.Length > 0; } if (havePk && groot.TryGetProperty("columns", out var ca)) { int pi = -1, ci = -1, k = 0; foreach (var c in ca.EnumerateArray()) { string nm = c.TryGetProperty("name", out var n) ? n.GetString() ?? "" : ""; bool idt = c.TryGetProperty("is_identity", out var ij) && ij.GetBoolean(); bool cmp = c.TryGetProperty("is_computed", out var cj) && cj.GetBoolean(); bool nnl = c.TryGetProperty("nullable", out var nj) && nj.GetBoolean(); if (pi < 0 && nm.Equals(pkCol, StringComparison.OrdinalIgnoreCase)) pi = k; if (ci < 0 && !nnl && !idt && !cmp && !nm.Equals(pkCol, StringComparison.OrdinalIgnoreCase)) ci = k; k++; } if (ci < 0) // no NOT NULL column: any non-pk editable one { k = 0; foreach (var c in ca.EnumerateArray()) { string nm = c.TryGetProperty("name", out var n) ? n.GetString() ?? "" : ""; bool idt = c.TryGetProperty("is_identity", out var ij) && ij.GetBoolean(); bool cmp = c.TryGetProperty("is_computed", out var cj) && cj.GetBoolean(); if (!idt && !cmp && !nm.Equals(pkCol, StringComparison.OrdinalIgnoreCase)) { ci = k; break; } k++; } } if (ci >= 0) colName = ca[ci].GetProperty("name").GetString() ?? ""; if (groot.TryGetProperty("rows", out var ra) && ra.ValueKind == JsonValueKind.Array && ra.GetArrayLength() > 0 && pi >= 0 && pi < ra[0].GetArrayLength()) { pkVal = ra[0][pi].GetRawText(); if (ci >= 0 && ci < ra[0].GetArrayLength()) { colVal = ra[0][ci].GetRawText(); if (colVal == "null") colVal = "\"x\""; } } } } catch { /* malformed grid → skips below */ } if (!havePk) { Skip("live editgrid_apply dry_run", tblSchema + "." + tblName + " has no PK (edits correctly refused)"); Skip("live editgrid quote escaping", "no PK on probe table"); } else if (colName.Length == 0) { Skip("live editgrid_apply dry_run", "no editable column in " + tblSchema + "." + tblName); Skip("live editgrid quote escaping", "no editable column"); } else { string ops = "[{\"op\":\"update\",\"pk\":{\"" + pkCol + "\":" + pkVal + "},\"values\":{\"" + colName + "\":" + colVal + "}}]"; string dry = SsmsInterop.CallEditGridApply(conn, probeDb, tblSchema, tblName, ops, true); Check(JsonHas(dry, "\"dry_run\":true") && JsonHas(dry, "\"statements\"") && JsonHas(dry, "UPDATE ") && JsonHas(dry, "\"ok\":true"), "live editgrid_apply honours dry_run and returns the generated T-SQL", Trunc(dry, 300)); // injection safety: a quote inside a value must not break out string injOps = "[{\"op\":\"update\",\"pk\":{\"" + pkCol + "\":" + pkVal + "},\"values\":{\"" + colName + "\":\"O'Brien\"}}]"; string inj = SsmsInterop.CallEditGridApply(conn, probeDb, tblSchema, tblName, injOps, true); Check(JsonHas(inj, "O''Brien"), "live editgrid_apply doubles single quotes (injection-safe)", Trunc(inj, 300)); } // a table with no PK must be refused, never silently edited string nopk = SsmsInterop.CallEditGridApply(conn, probeDb, tblSchema, tblName, "[{\"op\":\"nonsense\"}]", true); Check(JsonHas(nopk, "\"ok\":false"), "live editgrid_apply rejects a malformed operation", Trunc(nopk, 250)); } // activity string sess = SsmsInterop.CallActivity(conn, "sessions"); Check(JsonHas(sess, "\"ok\":true") && JsonHas(sess, "login_name"), "live activity sessions returns the session grid", Trunc(sess, 250)); // storage string files = SsmsInterop.CallStorage(conn, probeDb, "files", null); Check(JsonHas(files, "\"ok\":true") && JsonHas(files, "logical_name"), "live storage files returns the file grid", Trunc(files, 250)); // admin string admLogins = SsmsInterop.CallAdmin(conn, "logins", null, null); Check(JsonHas(admLogins, "\"ok\":true"), "live admin logins -> ok:true", Trunc(admLogins, 250)); } // ── CLI MODE ────────────────────────────────────────────────────────── static int RunCli(string cmd, string[] args) { string A(int i, string dflt = "") => i < args.Length ? args[i] : dflt; switch (cmd) { case "version": Console.WriteLine($"{{\"ok\":true,\"version\":\"{SsmsInterop.Version}\"}}"); return 0; case "connect-test": Print(SsmsInterop.CallConnectTest(A(1), int.TryParse(A(2), out var pt) ? pt : 1433, A(3), A(4), A(5), 0, int.TryParse(A(6), out var to) ? to : 10)); return 0; case "query": Print(SsmsInterop.CallQuery(A(1), A(2), A(3), int.TryParse(A(4), out var mr) ? mr : 1000, int.TryParse(A(5), out var ts) ? ts : 30)); return 0; case "tree": Print(SsmsInterop.CallTree(A(1), A(2, "databases"), A(3), A(4), A(5))); return 0; case "script": Print(SsmsInterop.CallScriptObject(A(1), A(2), A(3), A(4), A(5), A(6))); return 0; case "editgrid-load": Print(SsmsInterop.CallEditGridLoad(A(1), A(2), A(3), A(4), int.TryParse(A(5), out var tn) ? tn : 200)); return 0; case "editgrid-apply": Print(SsmsInterop.CallEditGridApply(A(1), A(2), A(3), A(4), A(5), A(6) == "1" || A(6).Equals("true", StringComparison.OrdinalIgnoreCase))); return 0; case "kill": Print(SsmsInterop.CallKillSpid(A(1), int.TryParse(A(2), out var sp) ? sp : 0)); return 0; case "activity": Print(SsmsInterop.CallActivity(A(1), A(2, "sessions"))); return 0; case "storage": Print(SsmsInterop.CallStorage(A(1), A(2), A(3), A(4))); return 0; case "admin": Print(SsmsInterop.CallAdmin(A(1), A(2), A(3), A(4))); return 0; default: Console.WriteLine($"{{\"ok\":false,\"error\":\"unknown command: {cmd}\"}}"); return 2; } } static void Print(string s) => Console.WriteLine(s); /// Marshal an IntPtr JSON return to a string and free it. static string S(IntPtr p) => SsmsInterop.TakeJson(p); // ── tiny JSON string escaper for building conn_json from argv ───────── static string ToJson(string host, int port, string user, string pass, string db) => "{\"host\":\"" + Esc(host) + "\",\"port\":" + port + ",\"user\":\"" + Esc(user) + "\",\"password\":\"" + Esc(pass) + "\",\"database\":\"" + Esc(db) + "\",\"timeout_s\":10}"; static string Esc(string s) { var sb = new System.Text.StringBuilder(s.Length + 8); foreach (char c in s) { switch (c) { case '"': sb.Append("\\\""); break; case '\\': sb.Append("\\\\"); break; case '\n': sb.Append("\\n"); break; case '\r': sb.Append("\\r"); break; case '\t': sb.Append("\\t"); break; default: if (c < 32) sb.Append("\\u").Append(((int)c).ToString("x4")); else sb.Append(c); break; } } return sb.ToString(); } static void Usage() { Console.WriteLine(@"scorpiox-ssms-core-console — P/Invoke harness for scorpiox-ssms-core --test run the full offline assertion suite (exit 1 on any FAIL) --test --live also probe a real SQL Server, using ONLY SSMS_TEST_HOST SSMS_TEST_PORT SSMS_TEST_USER SSMS_TEST_PASS SSMS_TEST_DB version connect-test [db] [timeout_s] query [max_rows] [timeout_s] tree [db] [schema] [obj] script editgrid-load
[top_n] editgrid-apply
[dry_run] kill activity storage [arg] admin [db] [arg] The native library is resolved from the application directory: Windows scorpiox-ssms-core.dll (+ libsybdb-5.dll, libssl-3-x64.dll, libcrypto-3-x64.dll, libiconv-2.dll, libcharset-1.dll) Linux libscorpiox-ssms-core.so"); } }