using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Scorpiox.Ssms;
///
/// P/Invoke bindings for every scorpiox-ssms-core export (13).
///
/// THIS FILE IS THE REFERENCE for the future WinUI3 app — copy it verbatim.
/// It matches exports.json exactly (names, order, signatures).
///
/// Rules baked in here (all of them are load-bearing):
/// * Library name INCLUDES the ".dll" suffix — required for MSIX packaging.
/// On Linux, .NET's loader strips it and finds libscorpiox-ssms-core.so.
/// * CallingConvention.Cdecl — the engine is a plain C library.
/// * [MarshalAs(UnmanagedType.LPUTF8Str)] on every const char* PARAM.
/// Without it, Windows marshals as the ANSI code page (cp1252) and
/// silently mangles every non-ASCII byte before it reaches C.
/// * IntPtr for every const char* RETURN, then Marshal.PtrToStringUTF8.
/// Marshalling a char*-returning export directly to string aborts the
/// process on the Linux .NET 9 runtime ("free(): invalid pointer").
/// * Strings returned by ssms_core_* are malloc'd by the DLL and MUST be
/// released with ssms_core_free. Strings returned by
/// ssms_core_version/last_error are static/thread-local — NEVER free.
///
public static class SsmsInterop
{
/// Library name as passed to the loader (with .dll — MSIX needs it).
public const string DllName = "scorpiox-ssms-core.dll";
///
/// The ".dll" suffix is mandatory for MSIX packaging, but .NET on Linux
/// then looks for "scorpiox-ssms-core.dll.so" and fails. This resolver
/// maps the single advertised name onto the platform-native file
/// (libscorpiox-ssms-core.so on Linux, libscorpiox-ssms-core.dylib on
/// macOS, scorpiox-ssms-core.dll on Windows), probing the application
/// directory first so the dependency DLLs (libsybdb-5.dll, OpenSSL,
/// libiconv) resolve from the same folder.
///
/// A WinUI3 app targeting only Windows can skip this and use the plain
/// [DllImport("scorpiox-ssms-core.dll")] — the resolver is here so the
/// SAME Interop.cs runs on both platforms unmodified.
///
static SsmsInterop()
{
try { NativeLibrary.SetDllImportResolver(typeof(SsmsInterop).Assembly, Resolve); }
catch (InvalidOperationException) { /* a resolver is already registered */ }
}
static IntPtr Resolve(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
{
if (!string.Equals(libraryName, DllName, StringComparison.OrdinalIgnoreCase))
return IntPtr.Zero;
string stem = libraryName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)
? libraryName.Substring(0, libraryName.Length - 4)
: libraryName;
var candidates = new List();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
candidates.Add(stem + ".dll");
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
candidates.Add("lib" + stem + ".dylib");
else
candidates.Add("lib" + stem + ".so");
candidates.Add(stem + ".dll");
candidates.Add("lib" + stem + ".so");
candidates.Add(stem);
string? dir = null;
try { dir = Path.GetDirectoryName(typeof(SsmsInterop).Assembly.Location); }
catch { /* single-file publish has no on-disk location */ }
foreach (string candidate in candidates)
{
if (dir != null)
{
string full = Path.Combine(dir, candidate);
if (File.Exists(full) &&
NativeLibrary.TryLoad(full, assembly, searchPath, out IntPtr h))
return h;
}
if (NativeLibrary.TryLoad(candidate, assembly, searchPath, out IntPtr h2))
return h2;
}
return IntPtr.Zero;
}
// ── 1. ssms_core_version ──────────────────────────────────────────────
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ssms_core_version")]
private static extern IntPtr version_raw();
/// Semver of the engine. Static buffer — never free.
public static string Version => PtrToStringUTF8(version_raw());
// ── 2. ssms_core_last_error ───────────────────────────────────────────
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ssms_core_last_error")]
private static extern IntPtr last_error_raw();
///
/// Thread-local diagnostic for the most recent failure ("" when none).
/// Static buffer — never free, and copy immediately: it is only valid
/// until the next ssms_core_* call on this thread.
///
public static string LastError => PtrToStringUTF8(last_error_raw());
// ── 3. ssms_core_free ─────────────────────────────────────────────────
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ssms_core_free")]
public static extern void free(IntPtr ptr);
// ── 4. ssms_core_connect_test ─────────────────────────────────────────
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ssms_core_connect_test")]
public static extern IntPtr connect_test(
[MarshalAs(UnmanagedType.LPUTF8Str)] string host,
int port,
[MarshalAs(UnmanagedType.LPUTF8Str)] string user,
[MarshalAs(UnmanagedType.LPUTF8Str)] string pass,
[MarshalAs(UnmanagedType.LPUTF8Str)] string db,
int encrypt,
int timeout_s);
// ── 5. ssms_core_tree ─────────────────────────────────────────────────
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ssms_core_tree")]
public static extern IntPtr tree(
[MarshalAs(UnmanagedType.LPUTF8Str)] string conn_json,
[MarshalAs(UnmanagedType.LPUTF8Str)] string node_kind,
[MarshalAs(UnmanagedType.LPUTF8Str)] string db,
[MarshalAs(UnmanagedType.LPUTF8Str)] string schema,
[MarshalAs(UnmanagedType.LPUTF8Str)] string obj);
// ── 6. ssms_core_query ────────────────────────────────────────────────
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ssms_core_query")]
public static extern IntPtr query(
[MarshalAs(UnmanagedType.LPUTF8Str)] string conn_json,
[MarshalAs(UnmanagedType.LPUTF8Str)] string db,
[MarshalAs(UnmanagedType.LPUTF8Str)] string sql,
int max_rows,
int timeout_s);
// ── 7. ssms_core_kill_spid ────────────────────────────────────────────
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ssms_core_kill_spid")]
public static extern IntPtr kill_spid(
[MarshalAs(UnmanagedType.LPUTF8Str)] string conn_json,
int spid);
// ── 8. ssms_core_script_object ────────────────────────────────────────
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ssms_core_script_object")]
public static extern IntPtr script_object(
[MarshalAs(UnmanagedType.LPUTF8Str)] string conn_json,
[MarshalAs(UnmanagedType.LPUTF8Str)] string db,
[MarshalAs(UnmanagedType.LPUTF8Str)] string kind,
[MarshalAs(UnmanagedType.LPUTF8Str)] string schema,
[MarshalAs(UnmanagedType.LPUTF8Str)] string obj,
[MarshalAs(UnmanagedType.LPUTF8Str)] string action);
// ── 9. ssms_core_editgrid_load ────────────────────────────────────────
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ssms_core_editgrid_load")]
public static extern IntPtr editgrid_load(
[MarshalAs(UnmanagedType.LPUTF8Str)] string conn_json,
[MarshalAs(UnmanagedType.LPUTF8Str)] string db,
[MarshalAs(UnmanagedType.LPUTF8Str)] string schema,
[MarshalAs(UnmanagedType.LPUTF8Str)] string table,
int top_n);
// ── 10. ssms_core_editgrid_apply ──────────────────────────────────────
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ssms_core_editgrid_apply")]
public static extern IntPtr editgrid_apply(
[MarshalAs(UnmanagedType.LPUTF8Str)] string conn_json,
[MarshalAs(UnmanagedType.LPUTF8Str)] string db,
[MarshalAs(UnmanagedType.LPUTF8Str)] string schema,
[MarshalAs(UnmanagedType.LPUTF8Str)] string table,
[MarshalAs(UnmanagedType.LPUTF8Str)] string ops_json,
int dry_run);
// ── 11. ssms_core_activity ────────────────────────────────────────────
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ssms_core_activity")]
public static extern IntPtr activity(
[MarshalAs(UnmanagedType.LPUTF8Str)] string conn_json,
[MarshalAs(UnmanagedType.LPUTF8Str)] string view);
// ── 12. ssms_core_storage ─────────────────────────────────────────────
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ssms_core_storage")]
public static extern IntPtr storage(
[MarshalAs(UnmanagedType.LPUTF8Str)] string conn_json,
[MarshalAs(UnmanagedType.LPUTF8Str)] string db,
[MarshalAs(UnmanagedType.LPUTF8Str)] string action,
[MarshalAs(UnmanagedType.LPUTF8Str)] string arg);
// ── 13. ssms_core_admin ───────────────────────────────────────────────
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ssms_core_admin")]
public static extern IntPtr admin(
[MarshalAs(UnmanagedType.LPUTF8Str)] string conn_json,
[MarshalAs(UnmanagedType.LPUTF8Str)] string kind,
[MarshalAs(UnmanagedType.LPUTF8Str)] string db,
[MarshalAs(UnmanagedType.LPUTF8Str)] string arg);
// ── Helpers ───────────────────────────────────────────────────────────
/// Marshal a const char* return. Never frees.
public static string PtrToStringUTF8(IntPtr p) =>
p == IntPtr.Zero ? string.Empty : (Marshal.PtrToStringUTF8(p) ?? string.Empty);
///
/// Copy a malloc'd JSON return into a managed string AND release it.
/// Use for every export that returns char* (all the JSON ones).
///
public static string TakeJson(IntPtr p)
{
if (p == IntPtr.Zero) return "null";
string s = Marshal.PtrToStringUTF8(p) ?? "null";
free(p);
return s;
}
/// Call an export, take ownership of its JSON, return it as text.
public static string Query(IntPtr p) => TakeJson(p);
// ── Null-parameter overloads ──────────────────────────────────────────
//
// The engine tolerates NULL const char* and reports a JSON error. Passing
// C# null to a LPUTF8Str string parameter marshals as NULL, so these
// exist purely to make the intent explicit at the call site.
public static string CallTree(string connJson, string nodeKind, string? db, string? schema, string? obj) =>
TakeJson(tree(connJson, nodeKind, db ?? "", schema ?? "", obj ?? ""));
public static string CallQuery(string connJson, string? db, string sql, int maxRows, int timeoutS) =>
TakeJson(query(connJson, db ?? "", sql, maxRows, timeoutS));
public static string CallConnectTest(string host, int port, string user, string pass, string db, int encrypt, int timeoutS) =>
TakeJson(connect_test(host, port, user, pass, db, encrypt, timeoutS));
public static string CallScriptObject(string connJson, string? db, string kind, string? schema, string obj, string action) =>
TakeJson(script_object(connJson, db ?? "", kind, schema ?? "", obj, action));
public static string CallEditGridLoad(string connJson, string? db, string? schema, string table, int topN) =>
TakeJson(editgrid_load(connJson, db ?? "", schema ?? "", table, topN));
public static string CallEditGridApply(string connJson, string? db, string? schema, string table, string opsJson, bool dryRun) =>
TakeJson(editgrid_apply(connJson, db ?? "", schema ?? "", table, opsJson, dryRun ? 1 : 0));
public static string CallKillSpid(string connJson, int spid) => TakeJson(kill_spid(connJson, spid));
public static string CallActivity(string connJson, string view) => TakeJson(activity(connJson, view));
public static string CallStorage(string connJson, string? db, string action, string? arg) =>
TakeJson(storage(connJson, db ?? "", action, arg ?? ""));
public static string CallAdmin(string connJson, string kind, string? db, string? arg) =>
TakeJson(admin(connJson, kind, db ?? "", arg ?? ""));
}