diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bd3104c..c24afef 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -101,6 +101,19 @@ jobs: go-version-file: go.mod - run: bun install --frozen-lockfile - run: bun run build:app + # The release binary is a GUI-subsystem program; AI clients still + # start it as `LowQuery.exe mcp` and talk over its stdin and stdout. + - name: lowquery mcp answers over stdio + shell: bash + run: | + printf '%s\n' \ + '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"ci","version":"0"}}}' \ + '{"jsonrpc":"2.0","method":"notifications/initialized"}' \ + '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' \ + | timeout 60 bin/LowQuery.exe mcp > mcp-out.txt + cat mcp-out.txt + grep -q '"serverInfo"' mcp-out.txt + grep -q '"list_connections"' mcp-out.txt lint: name: Rust format and lint @@ -225,8 +238,8 @@ jobs: - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: go-version-file: go.mod - - name: Go driver tests against a real server - run: go test -count=1 -v ./internal/drivers/oracle/... + - name: Go driver, transfer and MCP tests against a real server + run: go test -count=1 -v ./internal/drivers/oracle/... ./internal/transfer/... ./internal/mcp/... - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 with: @@ -279,8 +292,8 @@ jobs: - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: go-version-file: go.mod - - name: Go driver tests against a real server - run: go test -count=1 -v ./internal/drivers/mysql/... + - name: Go driver, transfer and MCP tests against a real server + run: go test -count=1 -v ./internal/drivers/mysql/... ./internal/transfer/... ./internal/mcp/... - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 with: @@ -321,8 +334,8 @@ jobs: - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: go-version-file: go.mod - - name: Go driver tests against a real server - run: go test -count=1 -v ./internal/drivers/sqlserver/... + - name: Go driver, transfer and MCP tests against a real server + run: go test -count=1 -v ./internal/drivers/sqlserver/... ./internal/transfer/... ./internal/mcp/... - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 with: @@ -362,8 +375,8 @@ jobs: - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: go-version-file: go.mod - - name: Go driver tests against a real server - run: go test -count=1 -v ./internal/drivers/redis/... + - name: Go driver, transfer and MCP tests against a real server + run: go test -count=1 -v ./internal/drivers/redis/... ./internal/transfer/... ./internal/mcp/... - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 with: @@ -406,8 +419,8 @@ jobs: - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: go-version-file: go.mod - - name: Go driver tests against a real server - run: go test -count=1 -v ./internal/drivers/cassandra/... + - name: Go driver, transfer and MCP tests against a real server + run: go test -count=1 -v ./internal/drivers/cassandra/... ./internal/transfer/... ./internal/mcp/... - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 with: diff --git a/internal/aisetup/aisetup.go b/internal/aisetup/aisetup.go new file mode 100644 index 0000000..78b9612 --- /dev/null +++ b/internal/aisetup/aisetup.go @@ -0,0 +1,386 @@ +// Package aisetup sets up AI clients to start "lowquery mcp": the command to +// run, the configuration each client expects, and adding LowQuery to the +// JSON configuration files of the clients that have one. +package aisetup + +import ( + "errors" + "io" + "io/fs" + "os" + "path/filepath" + "runtime" + "strings" + "unicode/utf8" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/ojson" +) + +// serverName is the name of the server entry in client configurations. +const serverName = "lowquery" + +type AiSetup struct { + // Executable that runs the MCP server ( mcp). + Command string `json:"command"` + Args []string `json:"args"` + Clients []AiClient `json:"clients"` +} + +type AiClient struct { + ID string `json:"id"` + Name string `json:"name"` + // Configuration file LowQuery can update, when the client has one. + ConfigPath *string `json:"configPath"` + // The client seems installed (its configuration folder exists). + Installed bool `json:"installed"` + // The configuration already starts this LowQuery. + Configured bool `json:"configured"` + // What to paste or run, for clients configured by hand. + Snippet string `json:"snippet"` + // "json", "toml" or "shell", for highlighting. + SnippetKind string `json:"snippetKind"` +} + +// jsonStyle is how a client's JSON file lists servers. +type jsonStyle int + +const ( + // { "mcpServers": { name: { command, args } } } (Claude Desktop, + // Cursor, Windsurf, Gemini CLI). + mcpServers jsonStyle = iota + // { "servers": { name: { type: "stdio", command, args } } } (VS Code). + vsCode +) + +type jsonClient struct { + id string + name string + style jsonStyle + // Candidate files in order; the first whose folder exists is used. + paths []string +} + +// dirs are the user folders clients keep their files in; tests replace +// them. +var dirs = struct { + home, config, localData func() string +}{userHome, userConfig, userLocalData} + +func userHome() string { + h, _ := os.UserHomeDir() + return h +} + +// userConfig is %APPDATA% on Windows, ~/Library/Application Support on +// macOS and $XDG_CONFIG_HOME (or ~/.config) elsewhere. +func userConfig() string { + switch runtime.GOOS { + case "windows", "darwin", "ios", "plan9": + d, _ := os.UserConfigDir() + return d + } + if d := os.Getenv("XDG_CONFIG_HOME"); filepath.IsAbs(d) { + return d + } + if h := userHome(); h != "" { + return filepath.Join(h, ".config") + } + return "" +} + +// userLocalData is %LOCALAPPDATA% on Windows (only used there). +func userLocalData() string { + if runtime.GOOS != "windows" { + return "" + } + return os.Getenv("LOCALAPPDATA") +} + +// serverCommand is the executable to start. An AppImage runs from a +// temporary mount, so its own path ($APPIMAGE) is the stable one. +func serverCommand() (string, error) { + if appimage := os.Getenv("APPIMAGE"); appimage != "" { + return appimage, nil + } + exe, err := os.Executable() + if err != nil { + return "", ioError(err) + } + return exe, nil +} + +func join(base string, parts ...string) string { + if base == "" { + // Like Rust's PathBuf::default().join: a relative path. + return filepath.Join(parts...) + } + return filepath.Join(append([]string{base}, parts...)...) +} + +func jsonClients() []jsonClient { + home := dirs.home() + config := dirs.config() + var claude []string + // The Microsoft Store build keeps its files in a virtualized folder. + if local := dirs.localData(); local != "" { + if entries, err := os.ReadDir(filepath.Join(local, "Packages")); err == nil { + for _, e := range entries { + if strings.HasPrefix(e.Name(), "Claude_") { + claude = append(claude, filepath.Join(local, "Packages", e.Name(), + "LocalCache", "Roaming", "Claude", "claude_desktop_config.json")) + } + } + } + } + claude = append(claude, join(config, "Claude", "claude_desktop_config.json")) + return []jsonClient{ + {"claude-desktop", "Claude Desktop", mcpServers, claude}, + {"cursor", "Cursor", mcpServers, []string{join(home, ".cursor", "mcp.json")}}, + {"vscode", "VS Code", vsCode, []string{join(config, "Code", "User", "mcp.json")}}, + {"windsurf", "Windsurf", mcpServers, []string{join(home, ".codeium", "windsurf", "mcp_config.json")}}, + {"gemini", "Gemini CLI", mcpServers, []string{join(home, ".gemini", "settings.json")}}, + } +} + +func exists(path string) bool { + _, err := os.Stat(path) + return err == nil +} + +// parentExists reports whether the folder of path exists. +func parentExists(path string) bool { + dir := filepath.Dir(path) + return dir != path && exists(dir) +} + +// pickPath is the first path whose folder exists, else the last one. +func pickPath(paths []string) string { + for _, p := range paths { + if parentExists(p) { + return p + } + } + if len(paths) == 0 { + return "" + } + return paths[len(paths)-1] +} + +func entry(style jsonStyle, command string) *ojson.Object { + e := ojson.NewObject() + if style == vsCode { + e.Set("type", "stdio") + } + e.Set("command", command) + e.Set("args", []any{"mcp"}) + return e +} + +func serversKey(style jsonStyle) string { + if style == vsCode { + return "servers" + } + return "mcpServers" +} + +func snippet(style jsonStyle, command string) string { + servers := ojson.NewObject() + servers.Set(serverName, entry(style, command)) + doc := ojson.NewObject() + doc.Set(serversKey(style), servers) + out, err := ojson.Pretty(doc) + if err != nil { + return "" + } + return string(out) +} + +// isConfigured reports whether the file's server entry already starts +// command. +func isConfigured(path string, style jsonStyle, command string) bool { + data, err := os.ReadFile(path) + if err != nil || !utf8.Valid(data) { + return false + } + doc, err := ojson.Parse(data) + if err != nil { + return false + } + c, ok := ojson.Obj(doc).Field(serversKey(style)).Field(serverName).Get("command").(string) + return ok && c == command +} + +func quoteShell(s string) string { + plain := true + for i := 0; i < len(s); i++ { + c := s[i] + if !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' || strings.IndexByte(`/\:._-`, c) >= 0) { + plain = false + break + } + } + if plain { + return s + } + return `"` + strings.ReplaceAll(s, `"`, `\"`) + `"` +} + +func tomlString(s string) string { + s = strings.ReplaceAll(s, `\`, `\\`) + return `"` + strings.ReplaceAll(s, `"`, `\"`) + `"` +} + +// Setup returns the MCP server command and the configuration of each AI +// client. +func Setup() (*AiSetup, error) { + command, err := serverCommand() + if err != nil { + return nil, err + } + var clients []AiClient + for _, c := range jsonClients() { + path := pickPath(c.paths) + client := AiClient{ + ID: c.id, + Name: c.name, + Snippet: snippet(c.style, command), + SnippetKind: "json", + } + if path != "" { + client.ConfigPath = &path + client.Installed = parentExists(path) + client.Configured = isConfigured(path, c.style, command) + } + clients = append(clients, client) + } + home := dirs.home() + claudeCode := AiClient{ + ID: "claude-code", + Name: "Claude Code", + Installed: exists(join(home, ".claude")), + Snippet: "claude mcp add --scope user " + serverName + " -- " + quoteShell(command) + " mcp", + SnippetKind: "shell", + } + clients = append(clients[:1], append([]AiClient{claudeCode}, clients[1:]...)...) + clients = append(clients, AiClient{ + ID: "codex", + Name: "Codex", + Installed: exists(join(home, ".codex")), + Snippet: "[mcp_servers." + serverName + "]\ncommand = " + tomlString(command) + "\nargs = [\"mcp\"]", + SnippetKind: "toml", + }) + return &AiSetup{Command: command, Args: []string{"mcp"}, Clients: clients}, nil +} + +// ConnectClient adds (or updates) the LowQuery entry in a client's JSON +// configuration, keeping everything else, and returns the file's path. The +// previous file is kept as .lowquery-backup. +func ConnectClient(id string) (string, error) { + command, err := serverCommand() + if err != nil { + return "", err + } + var client *jsonClient + for _, c := range jsonClients() { + if c.id == id { + client = &c + break + } + } + if client == nil { + return "", apperr.New(apperr.Invalid, "This client is configured by hand.") + } + path := pickPath(client.paths) + if path == "" { + return "", apperr.New(apperr.Invalid, "Could not find the client configuration folder.") + } + if err := writeEntry(path, client.style, command); err != nil { + return "", err + } + return path, nil +} + +func writeEntry(path string, style jsonStyle, command string) error { + var doc any + data, err := os.ReadFile(path) + switch { + case errors.Is(err, fs.ErrNotExist): + doc = ojson.NewObject() + case err != nil: + return ioError(err) + case !utf8.Valid(data): + return apperr.New(apperr.Internal, "stream did not contain valid UTF-8") + case strings.TrimSpace(string(data)) == "": + doc = ojson.NewObject() + default: + text := strings.TrimLeft(string(data), string(rune(0xFEFF))) + if doc, err = ojson.Parse([]byte(text)); err != nil { + return apperr.New(apperr.Invalid, + "The configuration file is not plain JSON (it may have comments). Add the snippet by hand.") + } + } + root := ojson.Obj(doc) + if root == nil { + return apperr.New(apperr.Invalid, "The configuration file does not hold a JSON object.") + } + key := serversKey(style) + if !root.Has(key) { + root.Set(key, ojson.NewObject()) + } + servers := root.Field(key) + if servers == nil { + return apperr.New(apperr.Invalid, "The servers section of the configuration is not an object.") + } + servers.Set(serverName, entry(style, command)) + if exists(path) { + if err := copyFile(path, path+".lowquery-backup"); err != nil { + return ioError(err) + } + } else if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return ioError(err) + } + out, err := ojson.Pretty(root) + if err != nil { + return apperr.Internalf("%v", err) + } + tmp := strings.TrimSuffix(path, filepath.Ext(path)) + ".lowquery-tmp" + if err := os.WriteFile(tmp, append(out, '\n'), 0o644); err != nil { + return ioError(err) + } + if err := os.Rename(tmp, path); err != nil { + return ioError(err) + } + return nil +} + +func copyFile(from, to string) error { + in, err := os.Open(from) + if err != nil { + return err + } + defer in.Close() + st, err := in.Stat() + if err != nil { + return err + } + out, err := os.OpenFile(to, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, st.Mode().Perm()) + if err != nil { + return err + } + if _, err := io.Copy(out, in); err != nil { + out.Close() + return err + } + return out.Close() +} + +// ioError is an I/O failure as the Rust io::Error read: the OS message +// without the operation and path. +func ioError(err error) error { + var pe *fs.PathError + if errors.As(err, &pe) { + err = pe.Err + } + return apperr.New(apperr.Internal, err.Error()) +} diff --git a/internal/aisetup/aisetup_test.go b/internal/aisetup/aisetup_test.go new file mode 100644 index 0000000..c41d764 --- /dev/null +++ b/internal/aisetup/aisetup_test.go @@ -0,0 +1,212 @@ +package aisetup + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/ojson" +) + +func readDoc(t *testing.T, path string) *ojson.Object { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + v, err := ojson.Parse(data) + if err != nil { + t.Fatal(err) + } + return ojson.Obj(v) +} + +func TestAddsEntryAndKeepsTheRest(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "claude_desktop_config.json") + if err := os.WriteFile(path, []byte(`{"theme":"dark","mcpServers":{"other":{"command":"x"}},"zeta":1}`), 0o644); err != nil { + t.Fatal(err) + } + exe := `C:\Apps\LowQuery\lowquery.exe` + if err := writeEntry(path, mcpServers, exe); err != nil { + t.Fatal(err) + } + doc := readDoc(t, path) + if strings.Join(doc.Keys(), ",") != "theme,mcpServers,zeta" { + t.Fatal(doc.Keys()) + } + servers := doc.Field("mcpServers") + if servers.Field("other").Get("command") != "x" { + t.Fatal("other server changed") + } + if args, _ := servers.Field("lowquery").Get("args").([]any); len(args) != 1 || args[0] != "mcp" { + t.Fatal(args) + } + if !isConfigured(path, mcpServers, exe) { + t.Fatal("not configured") + } + if _, err := os.Stat(filepath.Join(dir, "claude_desktop_config.json.lowquery-backup")); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(dir, "claude_desktop_config.lowquery-tmp")); err == nil { + t.Fatal("temporary file left behind") + } + + vs := filepath.Join(dir, "mcp.json") + if err := writeEntry(vs, vsCode, "/usr/bin/lowquery"); err != nil { + t.Fatal(err) + } + if readDoc(t, vs).Field("servers").Field("lowquery").Get("type") != "stdio" { + t.Fatal("no stdio type") + } + + if err := os.WriteFile(vs, []byte("{ // comment\n}"), 0o644); err != nil { + t.Fatal(err) + } + if e := apperr.From(writeEntry(vs, vsCode, "x")); e == nil || e.Kind != apperr.Invalid || !strings.Contains(e.Message, "comments") { + t.Fatal(e) + } + if err := os.WriteFile(vs, []byte("[1]"), 0o644); err != nil { + t.Fatal(err) + } + if e := apperr.From(writeEntry(vs, vsCode, "x")); e == nil || e.Message != "The configuration file does not hold a JSON object." { + t.Fatal(e) + } + if err := os.WriteFile(vs, []byte(`{"servers": 1}`), 0o644); err != nil { + t.Fatal(err) + } + if e := apperr.From(writeEntry(vs, vsCode, "x")); e == nil || e.Message != "The servers section of the configuration is not an object." { + t.Fatal(e) + } + // A BOM and an empty file are accepted; a missing folder is created. + if err := os.WriteFile(vs, []byte("\xEF\xBB\xBF{}"), 0o644); err != nil { + t.Fatal(err) + } + if err := writeEntry(vs, vsCode, "x"); err != nil { + t.Fatal(err) + } + if err := writeEntry(filepath.Join(dir, "new", "dir", "mcp.json"), vsCode, "x"); err != nil { + t.Fatal(err) + } +} + +func TestSnippetsQuotePaths(t *testing.T) { + if got := quoteShell("/usr/bin/lowquery"); got != "/usr/bin/lowquery" { + t.Fatal(got) + } + if got := quoteShell(`C:\Program Files\LowQuery\lowquery.exe`); got != `"C:\Program Files\LowQuery\lowquery.exe"` { + t.Fatal(got) + } + if got := tomlString(`C:\a`); got != `"C:\\a"` { + t.Fatal(got) + } + want := "{\n \"servers\": {\n \"lowquery\": {\n \"type\": \"stdio\",\n \"command\": \"C:\\\\a\",\n \"args\": [\n \"mcp\"\n ]\n }\n }\n}" + if got := snippet(vsCode, `C:\a`); got != want { + t.Fatalf("%s", got) + } +} + +// fakeDirs points the clients at folders in a temp dir. +func fakeDirs(t *testing.T) (home, config, local string) { + t.Helper() + root := t.TempDir() + home, config, local = filepath.Join(root, "home"), filepath.Join(root, "config"), filepath.Join(root, "local") + saved := dirs + dirs.home = func() string { return home } + dirs.config = func() string { return config } + dirs.localData = func() string { return local } + t.Cleanup(func() { dirs = saved }) + t.Setenv("APPIMAGE", "") + return +} + +func TestSetupListsClients(t *testing.T) { + home, config, local := fakeDirs(t) + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + // Cursor is installed and already configured; Claude Desktop comes + // from the Microsoft Store. + if err := os.MkdirAll(filepath.Join(home, ".cursor"), 0o755); err != nil { + t.Fatal(err) + } + if err := writeEntry(filepath.Join(home, ".cursor", "mcp.json"), mcpServers, exe); err != nil { + t.Fatal(err) + } + store := filepath.Join(local, "Packages", "Claude_pzs8sxrjxfjjc", "LocalCache", "Roaming", "Claude") + if err := os.MkdirAll(store, 0o755); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(home, ".claude"), 0o755); err != nil { + t.Fatal(err) + } + + s, err := Setup() + if err != nil { + t.Fatal(err) + } + if s.Command != exe || len(s.Args) != 1 || s.Args[0] != "mcp" { + t.Fatalf("%+v", s) + } + var ids []string + byID := map[string]AiClient{} + for _, c := range s.Clients { + ids = append(ids, c.ID) + byID[c.ID] = c + } + if strings.Join(ids, ",") != "claude-desktop,claude-code,cursor,vscode,windsurf,gemini,codex" { + t.Fatal(ids) + } + if c := byID["claude-desktop"]; !c.Installed || c.Configured || c.ConfigPath == nil || + *c.ConfigPath != filepath.Join(store, "claude_desktop_config.json") { + t.Fatalf("%+v", c) + } + if c := byID["cursor"]; !c.Installed || !c.Configured || c.SnippetKind != "json" { + t.Fatalf("%+v", c) + } + if c := byID["vscode"]; c.Installed || c.ConfigPath == nil || *c.ConfigPath != filepath.Join(config, "Code", "User", "mcp.json") { + t.Fatalf("%+v", c) + } + if c := byID["claude-code"]; !c.Installed || c.ConfigPath != nil || c.SnippetKind != "shell" || + !strings.HasPrefix(c.Snippet, "claude mcp add --scope user lowquery -- ") { + t.Fatalf("%+v", c) + } + if c := byID["codex"]; c.Installed || c.SnippetKind != "toml" || !strings.HasPrefix(c.Snippet, "[mcp_servers.lowquery]\ncommand = ") { + t.Fatalf("%+v", c) + } + + data, err := json.Marshal(byID["codex"]) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(data), `"configPath":null`) || !strings.Contains(string(data), `"snippetKind":"toml"`) { + t.Fatal(string(data)) + } + + t.Setenv("APPIMAGE", "/tmp/LowQuery.AppImage") + if s, _ := Setup(); s.Command != "/tmp/LowQuery.AppImage" { + t.Fatal(s.Command) + } +} + +func TestConnectClient(t *testing.T) { + home, _, _ := fakeDirs(t) + path, err := ConnectClient("gemini") + if err != nil { + t.Fatal(err) + } + if path != filepath.Join(home, ".gemini", "settings.json") { + t.Fatal(path) + } + exe, _ := os.Executable() + if !isConfigured(path, mcpServers, exe) { + t.Fatal("not configured") + } + if _, err := ConnectClient("codex"); apperr.From(err).Message != "This client is configured by hand." { + t.Fatal(err) + } +} diff --git a/internal/app/app.go b/internal/app/app.go index 48ef9e2..4611b74 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -13,14 +13,18 @@ import ( "github.com/LowBloat/LowQuery/internal/apperr" "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/engines" "github.com/LowBloat/LowQuery/internal/model" "github.com/LowBloat/LowQuery/internal/profiles" + "github.com/LowBloat/LowQuery/internal/transfer" ) type App struct { version string profiles *profiles.Store window Window + emit func(event string, data any) + jobs transfer.Jobs mu sync.RWMutex sessions map[string]drivers.Session @@ -44,6 +48,17 @@ func New(version string, store *profiles.Store) *App { // SetWindow connects the main window once it exists. func (a *App) SetWindow(w Window) { a.window = w } +// SetEmitter connects the function that sends events to the interface +// (transfer progress, for example). +func (a *App) SetEmitter(emit func(event string, data any)) { a.emit = emit } + +// Emit sends an event to the interface; without an emitter it does nothing. +func (a *App) Emit(event string, data any) { + if a.emit != nil { + a.emit(event, data) + } +} + func (a *App) session(id string) (drivers.Session, error) { a.mu.RLock() defer a.mu.RUnlock() @@ -83,7 +98,7 @@ func isAuthFailure(e *apperr.Error) bool { func openWithPassword(ctx context.Context, profile model.ConnectionProfile, password *string) (drivers.Session, error) { // SQLite files and Windows-authenticated SQL Server need no password. if profile.Engine == model.SQLite || (profile.Engine == model.SQLServer && profile.WindowsAuth) { - return openSession(ctx, profile, nil) + return engines.Open(ctx, profile, nil) } provided := password != nil if password == nil { @@ -93,7 +108,7 @@ func openWithPassword(ctx context.Context, profile model.ConnectionProfile, pass return nil, apperr.New(apperr.PasswordRequired, "Enter the password.") } hadPassword := password != nil - s, err := openSession(ctx, profile, password) + s, err := engines.Open(ctx, profile, password) if err != nil && !provided { if e := apperr.From(err); isAuthFailure(e) { msg := "Enter the password." diff --git a/internal/app/commands.go b/internal/app/commands.go index 4c02ed9..f55a80e 100644 --- a/internal/app/commands.go +++ b/internal/app/commands.go @@ -34,7 +34,7 @@ type sessionArgs struct { } func (a *App) commands() map[string]handler { - return map[string]handler{ + m := map[string]handler{ "list_profiles": command(func(ctx context.Context, _ none) ([]model.ConnectionProfile, error) { return a.profiles.List() }), @@ -201,6 +201,9 @@ func (a *App) commands() map[string]handler { return a.checkUpdate(ctx) }), } + a.transferCommands(m) + a.integrationCommands(m) + return m } // nonNil turns a nil list into an empty one, so the interface gets []. diff --git a/internal/app/integrations.go b/internal/app/integrations.go new file mode 100644 index 0000000..3b5d63b --- /dev/null +++ b/internal/app/integrations.go @@ -0,0 +1,53 @@ +package app + +import ( + "context" + + "github.com/LowBloat/LowQuery/internal/aisetup" + "github.com/LowBloat/LowQuery/internal/importers" + "github.com/LowBloat/LowQuery/internal/mcp" +) + +// integrationCommands adds the commands that deal with other tools: +// importing their connections and connecting AI clients to `lowquery mcp`. +func (a *App) integrationCommands(m map[string]handler) { + m["import_detect"] = command(func(ctx context.Context, _ none) ([]importers.ImportSource, error) { + return importers.Detect(), nil + }) + // Reads one tool file and lists what can be imported (without passwords). + m["import_preview"] = command(func(ctx context.Context, p struct { + Tool importers.ImportTool `json:"tool"` + Path string `json:"path"` + }) (*importers.ImportPreview, error) { + return importers.Preview(p.Tool, p.Path) + }) + m["import_apply"] = command(func(ctx context.Context, p struct { + Tool importers.ImportTool `json:"tool"` + Path string `json:"path"` + Keys []string `json:"keys"` + WithPasswords bool `json:"withPasswords"` + }) (*importers.ImportResult, error) { + return importers.Apply(a.profiles, p.Tool, p.Path, p.Keys, p.WithPasswords) + }) + m["ai_setup"] = command(func(ctx context.Context, _ none) (*aisetup.AiSetup, error) { + return aisetup.Setup() + }) + m["ai_connect_client"] = command(func(ctx context.Context, p struct { + ID string `json:"id"` + }) (string, error) { + return aisetup.ConnectClient(p.ID) + }) + // What agents did through `lowquery mcp`, newest first. + m["ai_activity"] = command(func(ctx context.Context, p struct { + Limit *int `json:"limit"` + }) ([]mcp.AuditEntry, error) { + limit := 200 + if p.Limit != nil { + limit = max(0, min(*p.Limit, 2000)) + } + return nonNil(mcp.ReadRecent(a.profiles.Dir(), limit)) + }) + m["ai_activity_clear"] = command(func(ctx context.Context, _ none) (any, error) { + return nil, mcp.ClearActivity(a.profiles.Dir()) + }) +} diff --git a/internal/app/transfer.go b/internal/app/transfer.go new file mode 100644 index 0000000..d2a52e3 --- /dev/null +++ b/internal/app/transfer.go @@ -0,0 +1,51 @@ +package app + +import ( + "context" + + "github.com/LowBloat/LowQuery/internal/transfer" +) + +// transferCommands adds the export and import commands. A job runs on a +// session the interface opened for it; cancelling it also stops the query +// running on the server. +func (a *App) transferCommands(m map[string]handler) { + m["transfer_export"] = command(func(ctx context.Context, p struct { + Request transfer.ExportRequest `json:"request"` + }) (*transfer.ExportSummary, error) { + s, err := a.session(p.Request.SessionID) + if err != nil { + return nil, err + } + jctx := a.jobs.Start(ctx, p.Request.JobID, s) + defer a.jobs.Finish(p.Request.JobID) + return transfer.Export(jctx, s, p.Request, a.reportProgress) + }) + m["transfer_import_preview"] = command(func(ctx context.Context, p struct { + Path string `json:"path"` + Options transfer.ReadOptions `json:"options"` + }) (*transfer.ImportPreview, error) { + return transfer.PreviewFile(p.Path, p.Options) + }) + m["transfer_import"] = command(func(ctx context.Context, p struct { + Request transfer.ImportRequest `json:"request"` + }) (*transfer.ImportSummary, error) { + s, err := a.session(p.Request.SessionID) + if err != nil { + return nil, err + } + jctx := a.jobs.Start(ctx, p.Request.JobID, s) + defer a.jobs.Finish(p.Request.JobID) + return transfer.Import(jctx, s, p.Request, a.reportProgress) + }) + m["transfer_cancel"] = command(func(ctx context.Context, p struct { + JobID string `json:"jobId"` + }) (any, error) { + if s, ok := a.jobs.Cancel(p.JobID); ok { + _ = s.Cancel(ctx) + } + return nil, nil + }) +} + +func (a *App) reportProgress(p transfer.Progress) { a.Emit(transfer.ProgressEvent, p) } diff --git a/internal/drivers/cassandra/cassandra_test.go b/internal/drivers/cassandra/cassandra_test.go index 2868f7f..72f5cce 100644 --- a/internal/drivers/cassandra/cassandra_test.go +++ b/internal/drivers/cassandra/cassandra_test.go @@ -207,7 +207,7 @@ func TestBlobPreviewIsCut(t *testing.T) { } func TestLiteralsFollowTheColumnType(t *testing.T) { - l := func(typ, v string) string { return cqlLiteral(typ, &v) } + l := func(typ, v string) string { return CQLLiteral(typ, &v) } eq(t, l("int", "42"), "42") eq(t, l("varint", "-12345678901234567890"), "-12345678901234567890") eq(t, l("double", "NaN"), "NaN") @@ -223,7 +223,7 @@ func TestLiteralsFollowTheColumnType(t *testing.T) { eq(t, l("uuid", "123e4567-e89b-12d3-a456-426614174000"), "123e4567-e89b-12d3-a456-426614174000") eq(t, l("blob", "0x00ff"), "0x00ff") eq(t, l("duration", "1mo2d"), "1mo2d") - eq(t, cqlLiteral("int", nil), "null") + eq(t, CQLLiteral("int", nil), "null") // Not a value of the type: quoted, so the server explains the error. eq(t, l("int", "abc"), "'abc'") eq(t, l("int", "1.2.3"), "'1.2.3'") diff --git a/internal/drivers/cassandra/edit.go b/internal/drivers/cassandra/edit.go index 98633c2..424cccd 100644 --- a/internal/drivers/cassandra/edit.go +++ b/internal/drivers/cassandra/edit.go @@ -153,7 +153,7 @@ func planChanges(target *model.EditTarget, changes []model.RowChange) ([]string, if key[i] == nil { return "", apperr.Invalidf("The key column %s is empty.", c.Name) } - parts[i] = quoteName(c.Name) + " = " + cqlLiteral(c.TypeName, key[i]) + parts[i] = quoteName(c.Name) + " = " + CQLLiteral(c.TypeName, key[i]) } return strings.Join(parts, " AND "), nil } @@ -177,7 +177,7 @@ func planChanges(target *model.EditTarget, changes []model.RowChange) ([]string, "Delete the row and insert it again.", c.Name) } } - sets = append(sets, quoteName(c.Name)+" = "+cqlLiteral(c.TypeName, v.Value)) + sets = append(sets, quoteName(c.Name)+" = "+CQLLiteral(c.TypeName, v.Value)) } where, err := condition(change.Key) if err != nil { @@ -204,7 +204,7 @@ func planChanges(target *model.EditTarget, changes []model.RowChange) ([]string, return nil, nil, err } names[i] = quoteName(c.Name) - literals[i] = cqlLiteral(c.TypeName, v.Value) + literals[i] = CQLLiteral(c.TypeName, v.Value) } statements = append(statements, "INSERT INTO "+table+" ("+strings.Join(names, ", ")+") VALUES ("+ strings.Join(literals, ", ")+")") diff --git a/internal/drivers/cassandra/values.go b/internal/drivers/cassandra/values.go index 3b3ea66..1db2ebd 100644 --- a/internal/drivers/cassandra/values.go +++ b/internal/drivers/cassandra/values.go @@ -809,12 +809,12 @@ func asciiLower(s string) string { return string(b) } -// cqlLiteral turns a cell's text into a CQL literal for a column of +// CQLLiteral turns a cell's text into a CQL literal for a column of // typeName (the type as system_schema writes it). Numbers, booleans, uuids, // blobs and durations are bare, text and temporal values quoted; // collections, tuples, vectors and UDTs are already CQL literals in cell // text and stay as they are. nil is null. -func cqlLiteral(typeName string, value *string) string { +func CQLLiteral(typeName string, value *string) string { if value == nil { return "null" } diff --git a/internal/drivers/redis/args.go b/internal/drivers/redis/args.go index 06cae85..92b26c0 100644 --- a/internal/drivers/redis/args.go +++ b/internal/drivers/redis/args.go @@ -28,10 +28,10 @@ func hexValue(c byte) (byte, bool) { return 0, false } -// splitArgs splits a command line into arguments the way redis-cli does: +// SplitArgs splits a command line into arguments the way redis-cli does: // double quotes take \n \r \t \b \a \\ \" and \xHH, single quotes only \', // and a closing quote must be followed by a space or the end. -func splitArgs(line string) ([][]byte, error) { +func SplitArgs(line string) ([][]byte, error) { b := []byte(line) invalidAt := func(message string, at int) error { e := apperr.New(apperr.Invalid, message) diff --git a/internal/drivers/redis/redis.go b/internal/drivers/redis/redis.go index b9fd7a7..7325d5c 100644 --- a/internal/drivers/redis/redis.go +++ b/internal/drivers/redis/redis.go @@ -366,7 +366,7 @@ func (s *Session) Execute(ctx context.Context, req model.ExecRequest) (*model.Ex var args [][]byte if !strings.HasPrefix(text, "#") && !strings.HasPrefix(text, "//") { var err error - if args, err = splitArgs(req.SQL); err != nil { + if args, err = SplitArgs(req.SQL); err != nil { return nil, err } } diff --git a/internal/drivers/redis/redis_test.go b/internal/drivers/redis/redis_test.go index ec9531a..f82d91c 100644 --- a/internal/drivers/redis/redis_test.go +++ b/internal/drivers/redis/redis_test.go @@ -10,7 +10,7 @@ import ( func args(t *testing.T, line string) []string { t.Helper() - raw, err := splitArgs(line) + raw, err := SplitArgs(line) if err != nil { t.Fatalf("%s: %v", line, err) } @@ -30,7 +30,7 @@ func eq(t *testing.T, got, want any) { func splitErr(t *testing.T, line string) *apperr.Error { t.Helper() - _, err := splitArgs(line) + _, err := SplitArgs(line) if err == nil { t.Fatalf("%s: no error", line) } @@ -50,7 +50,7 @@ func TestSplitsLikeRedisCli(t *testing.T) { eq(t, args(t, "ECHO ação"), []string{"ECHO", "ação"}) eq(t, args(t, " \n "), []string{}) - raw, err := splitArgs(`SET k "\xff\x41\xZZ"`) + raw, err := SplitArgs(`SET k "\xff\x41\xZZ"`) if err != nil { t.Fatal(err) } @@ -86,7 +86,7 @@ type table struct { func tab(t *testing.T, name, line string, v value, maxRows int) table { t.Helper() - a, err := splitArgs(line) + a, err := SplitArgs(line) if err != nil { t.Fatal(err) } @@ -307,7 +307,7 @@ func TestMapsErrorsAndKinds(t *testing.T) { func TestTracksMulti(t *testing.T) { var st state a := func(l string) [][]byte { - v, err := splitArgs(l) + v, err := SplitArgs(l) if err != nil { t.Fatal(err) } diff --git a/internal/app/engines.go b/internal/engines/engines.go similarity index 84% rename from internal/app/engines.go rename to internal/engines/engines.go index 2edfa8f..dac35ea 100644 --- a/internal/app/engines.go +++ b/internal/engines/engines.go @@ -1,4 +1,5 @@ -package app +// Package engines opens a session with the driver of a profile's engine. +package engines import ( "context" @@ -15,8 +16,8 @@ import ( "github.com/LowBloat/LowQuery/internal/model" ) -// openSession connects with the driver of the profile's engine. -func openSession(ctx context.Context, p model.ConnectionProfile, password *string) (drivers.Session, error) { +// Open connects with the driver of the profile's engine. +func Open(ctx context.Context, p model.ConnectionProfile, password *string) (drivers.Session, error) { // Each case returns through a typed variable so a nil *Session never // becomes a non-nil interface. switch p.Engine { diff --git a/internal/importers/datagrip.go b/internal/importers/datagrip.go new file mode 100644 index 0000000..2b20eec --- /dev/null +++ b/internal/importers/datagrip.go @@ -0,0 +1,948 @@ +package importers + +// DataGrip and other JetBrains IDEs: dataSources.xml (global, in the IDE +// config folder, or per project in .idea) with user names and SSH/SSL +// settings in dataSources.local.xml next to it. Passwords live in the OS +// keychain or KeePass and are not imported. +// +// Also holds the small XML reader and checks shared by the pgAdmin and SQL +// Developer importers. + +import ( + "encoding/xml" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "sort" + "strings" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" +) + +func datagripFiles() []source { + var f found + home := dirs.home() + for _, pd := range productDirs(home) { + options := filepath.Join(pd.path, "options") + f.add(pd.label+" · Global", filepath.Join(options, "dataSources.xml")) + for _, project := range subdirs(filepath.Join(pd.path, "projects")) { + f.addProject(pd.label, project) + } + for _, project := range recentProjects(filepath.Join(options, "recentProjects.xml"), home) { + f.addProject(pd.label, project) + } + } + if home != "" { + for _, project := range subdirs(filepath.Join(home, "DataGripProjects")) { + f.addProject("DataGrip", project) + } + } + return f.files +} + +type found struct { + files []source + seen map[string]bool +} + +func (f *found) add(label, path string) { + if !isFile(path) { + return + } + id := fileID(path, runtime.GOOS == "windows" || runtime.GOOS == "darwin") + if f.seen == nil { + f.seen = map[string]bool{} + } + if !f.seen[id] { + f.seen[id] = true + f.files = append(f.files, source{label, path}) + } +} + +func (f *found) addProject(product, project string) { + name := fileName(project) + if name == "" { + name = project + } + f.add(product+" · "+name, filepath.Join(project, ".idea", "dataSources.xml")) +} + +// productDirs lists the IDE config folders as (label, folder holding +// options). +func productDirs(home string) []source { + var bases []string + if dir := dirs.config(); dir != "" { + bases = append(bases, filepath.Join(dir, "JetBrains")) + } + if home != "" && runtime.GOOS == "linux" { + // Flatpak builds keep their own XDG config folder. + for _, app := range subdirs(filepath.Join(home, ".var", "app")) { + bases = append(bases, filepath.Join(app, "config", "JetBrains")) + } + } + var out []source + for _, base := range bases { + for _, dir := range subdirs(base) { + if isDir(filepath.Join(dir, "options")) { + out = append(out, source{productLabel(fileName(dir)), dir}) + } + } + } + // Before 2020.1: ~/.DataGrip2019.3/config (Windows, Linux) and + // ~/Library/Preferences/DataGrip2019.3 (macOS). + if home != "" { + for _, dir := range subdirs(home) { + name := fileName(dir) + if product, ok := strings.CutPrefix(name, "."); ok { + config := filepath.Join(dir, "config") + if isDir(filepath.Join(config, "options")) && strings.ContainsAny(product, "0123456789") { + out = append(out, source{productLabel(product), config}) + } + } + } + if runtime.GOOS == "darwin" { + for _, dir := range subdirs(filepath.Join(home, "Library", "Preferences")) { + if isFile(filepath.Join(dir, "options", "dataSources.xml")) { + out = append(out, source{productLabel(fileName(dir)), dir}) + } + } + } + } + return out +} + +// productLabel turns "DataGrip2024.1" into "DataGrip 2024.1". +func productLabel(name string) string { + if i := strings.IndexAny(name, "0123456789"); i > 0 { + return name[:i] + " " + name[i:] + } + return name +} + +// subdirs lists the subfolders sorted by name; empty when the folder cannot +// be read. Links to folders are not followed. +func subdirs(dir string) []string { + entries, err := os.ReadDir(dir) + if err != nil { + return nil + } + var out []string + for _, e := range entries { + if e.IsDir() { + out = append(out, filepath.Join(dir, e.Name())) + } + } + sort.Strings(out) + return out +} + +// recentProjects lists the project folders in the IDE's recentProjects.xml. +func recentProjects(file, home string) []string { + text, err := readText(file) + if err != nil { + return nil + } + root := parseXML(text) + if root == nil { + return nil + } + var paths []string + collectRecent(root, false, &paths) + var out []string + for _, p := range paths { + if home != "" { + p = strings.ReplaceAll(p, "$USER_HOME$", home) + } + if filepath.IsAbs(p) { + out = append(out, p) + } + } + return out +} + +func collectRecent(node *xmlNode, inRecentPaths bool, out *[]string) { + for _, child := range node.children { + switch child.name { + case "entry": + // additionalInfo map: . + if k, ok := child.attr("key"); ok && k != "" { + *out = append(*out, k) + } + case "option": + // recentPaths list: