From c7a40da1b70720db83ed18ce4d5051eac68ff44e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A1bio=20Henrique=20Ara=C3=BAjo?= Date: Fri, 4 Dec 2026 11:58:21 -0300 Subject: [PATCH 1/8] refactor(go): engine dispatch in its own package; app event emitter --- internal/app/app.go | 17 +++++++++++++++-- internal/{app => engines}/engines.go | 7 ++++--- main.go | 1 + 3 files changed, 20 insertions(+), 5 deletions(-) rename internal/{app => engines}/engines.go (84%) diff --git a/internal/app/app.go b/internal/app/app.go index 48ef9e2..07cfb86 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -13,6 +13,7 @@ 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" ) @@ -21,6 +22,7 @@ type App struct { version string profiles *profiles.Store window Window + emit func(event string, data any) mu sync.RWMutex sessions map[string]drivers.Session @@ -44,6 +46,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 +96,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 +106,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/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/main.go b/main.go index 9bd1a1e..add0889 100644 --- a/main.go +++ b/main.go @@ -94,6 +94,7 @@ func main() { }) frame := &mainWindow{win: win} backend.SetWindow(frame) + backend.SetEmitter(func(event string, data any) { wails.Event.Emit(event, data) }) time.AfterFunc(firstShowFallback, frame.showFirstTime) if err := wails.Run(); err != nil { From f4ed86461585574480792ec42adce7aa7fb77237 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A1bio=20Henrique=20Ara=C3=BAjo?= Date: Fri, 4 Dec 2026 11:59:02 -0300 Subject: [PATCH 2/8] refactor(go): profiles.ConfigDir for the app and the MCP server --- internal/profiles/profiles.go | 22 ++++++++++++++++++++++ main.go | 18 ++---------------- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/internal/profiles/profiles.go b/internal/profiles/profiles.go index abe7012..5999274 100644 --- a/internal/profiles/profiles.go +++ b/internal/profiles/profiles.go @@ -25,6 +25,28 @@ type Store struct { mu sync.Mutex } +// ConfigDir is the folder with connections.json and the AI activity log, the +// same one the first releases used: %APPDATA%\LowBloat\LowQuery\config on +// Windows, ~/Library/Application Support/dev.LowBloat.LowQuery on macOS, +// ~/.config/lowquery on Linux. +func ConfigDir() (string, error) { + base, err := os.UserConfigDir() + if err != nil { + return "", err + } + switch { + case filepath.Base(base) == "Application Support": // macOS + return filepath.Join(base, "dev.LowBloat.LowQuery"), nil + case os.PathSeparator == '\\': // Windows: %APPDATA% + return filepath.Join(base, "LowBloat", "LowQuery", "config"), nil + default: + return filepath.Join(base, "lowquery"), nil + } +} + +// Dir is the folder the store keeps connections.json in. +func (s *Store) Dir() string { return filepath.Dir(s.path) } + func NewStore(configDir string) (*Store, error) { if err := os.MkdirAll(configDir, 0o755); err != nil { return nil, err diff --git a/main.go b/main.go index add0889..1bde0ff 100644 --- a/main.go +++ b/main.go @@ -38,14 +38,11 @@ func main() { } _ = json.Unmarshal(packageJSON, &pkg) - configDir, err := os.UserConfigDir() + configDir, err := profiles.ConfigDir() if err != nil { log.Fatalf("user configuration directory unavailable: %v", err) } - // Same folder the first releases used: %APPDATA%\LowBloat\LowQuery\config - // on Windows, ~/Library/Application Support/dev.LowBloat.LowQuery on - // macOS, ~/.config/lowquery on Linux. - store, err := profiles.NewStore(appConfigDir(configDir)) + store, err := profiles.NewStore(configDir) if err != nil { log.Fatalf("could not create the configuration directory: %v", err) } @@ -102,17 +99,6 @@ func main() { } } -func appConfigDir(base string) string { - switch { - case filepath.Base(base) == "Application Support": // macOS - return filepath.Join(base, "dev.LowBloat.LowQuery") - case os.PathSeparator == '\\': // Windows: %APPDATA% - return filepath.Join(base, "LowBloat", "LowQuery", "config") - default: - return filepath.Join(base, "lowquery") - } -} - // webviewDataDir is the WebView2 profile (local storage with editor drafts, // cache) on Windows: %LOCALAPPDATA%\LowBloat\LowQuery\WebView. LQ_WEBVIEW_DATA // overrides it, so a test copy does not share the profile of the one in use. From 14f51564b3fee208c8fd6c64544df0670ea0c168 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A1bio=20Henrique=20Ara=C3=BAjo?= Date: Fri, 4 Dec 2026 12:16:41 -0300 Subject: [PATCH 3/8] feat(go): data export and import (SQL, CSV, JSON) with progress and cancel --- internal/app/app.go | 2 + internal/app/commands.go | 4 +- internal/app/transfer.go | 51 ++ internal/transfer/catalog.go | 247 +++++++++ internal/transfer/catalog_test.go | 48 ++ internal/transfer/export.go | 694 +++++++++++++++++++++++ internal/transfer/export_test.go | 238 ++++++++ internal/transfer/import.go | 824 ++++++++++++++++++++++++++++ internal/transfer/import_test.go | 322 +++++++++++ internal/transfer/roundtrip_test.go | 476 ++++++++++++++++ internal/transfer/sql.go | 526 ++++++++++++++++++ internal/transfer/sql_test.go | 332 +++++++++++ internal/transfer/transfer.go | 150 +++++ 13 files changed, 3913 insertions(+), 1 deletion(-) create mode 100644 internal/app/transfer.go create mode 100644 internal/transfer/catalog.go create mode 100644 internal/transfer/catalog_test.go create mode 100644 internal/transfer/export.go create mode 100644 internal/transfer/export_test.go create mode 100644 internal/transfer/import.go create mode 100644 internal/transfer/import_test.go create mode 100644 internal/transfer/roundtrip_test.go create mode 100644 internal/transfer/sql.go create mode 100644 internal/transfer/sql_test.go create mode 100644 internal/transfer/transfer.go diff --git a/internal/app/app.go b/internal/app/app.go index 07cfb86..4611b74 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -16,6 +16,7 @@ import ( "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 { @@ -23,6 +24,7 @@ type App struct { profiles *profiles.Store window Window emit func(event string, data any) + jobs transfer.Jobs mu sync.RWMutex sessions map[string]drivers.Session diff --git a/internal/app/commands.go b/internal/app/commands.go index 4c02ed9..575faa8 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,8 @@ func (a *App) commands() map[string]handler { return a.checkUpdate(ctx) }), } + a.transferCommands(m) + return m } // nonNil turns a nil list into an empty one, so the interface gets []. 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/transfer/catalog.go b/internal/transfer/catalog.go new file mode 100644 index 0000000..3ee53cc --- /dev/null +++ b/internal/transfer/catalog.go @@ -0,0 +1,247 @@ +package transfer + +// Catalog facts exports and imports need beyond what the tree shows: +// generated columns (never inserted), identity columns (inserted with their +// values, then the generator moved past them) and foreign keys (tables in +// dependency order). Cassandra has none of the three: the answers are empty. + +import ( + "context" + "fmt" + "slices" + + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/model" +) + +func catalogRows(ctx context.Context, s drivers.Session, sql string) ([]model.Row, error) { + r, err := s.Execute(ctx, model.ExecRequest{SQL: sql, MaxRows: 0}) + if err != nil { + return nil, err + } + return r.Rows, nil +} + +// generatedColumns returns the columns the database computes (generated, +// virtual, rowversion): an INSERT cannot set them. +func generatedColumns(ctx context.Context, s drivers.Session, schema, table string) (map[string]bool, error) { + e := s.Engine() + var sql string + switch e { + case model.Postgres: + sql = fmt.Sprintf(`SELECT a.attname::text FROM pg_attribute a + WHERE a.attrelid = to_regclass(%s) AND a.attnum > 0 AND NOT a.attisdropped + AND COALESCE(to_jsonb(a) ->> 'attgenerated', '') <> ''`, + text(e, qualified(e, schema, table))) + case model.MySQL, model.MariaDB: + sql = fmt.Sprintf(`SELECT COLUMN_NAME FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s + AND (EXTRA LIKE '%%VIRTUAL GENERATED%%' OR EXTRA LIKE '%%STORED GENERATED%%' + OR EXTRA LIKE '%%PERSISTENT%%')`, + text(e, schema), text(e, table)) + case model.SQLServer: + sql = fmt.Sprintf(`SELECT name FROM sys.columns + WHERE object_id = OBJECT_ID(%s) AND (is_computed = 1 OR system_type_id = 189)`, + text(e, qualified(e, schema, table))) + case model.Oracle: + sql = fmt.Sprintf(`SELECT column_name FROM all_tab_cols + WHERE owner = %s AND table_name = %s AND virtual_column = 'YES'`, + text(e, schema), text(e, table)) + case model.SQLite: + sql = fmt.Sprintf("SELECT name FROM pragma_table_xinfo(%s, %s) WHERE hidden IN (2, 3)", + text(e, table), text(e, schema)) + default: + // Redis; CQL has no generated columns (counters are written by UPDATE). + return map[string]bool{}, nil + } + rows, err := catalogRows(ctx, s, sql) + if err != nil { + return nil, err + } + out := map[string]bool{} + for _, r := range rows { + if len(r) > 0 && r[0] != nil { + out[*r[0]] = true + } + } + return out, nil +} + +// identity is an identity or serial column and what keeps its next value. +type identity struct { + column string + // PostgreSQL: the sequence; Oracle: ALWAYS or BY DEFAULT. + detail string +} + +func identityColumns(ctx context.Context, s drivers.Session, schema, table string) ([]identity, error) { + e := s.Engine() + q := qualified(e, schema, table) + var sql string + switch e { + case model.Postgres: + t := text(e, q) + sql = fmt.Sprintf(`SELECT a.attname::text, pg_get_serial_sequence(%[1]s, a.attname) + FROM pg_attribute a + WHERE a.attrelid = to_regclass(%[1]s) AND a.attnum > 0 AND NOT a.attisdropped + AND pg_get_serial_sequence(%[1]s, a.attname) IS NOT NULL`, t) + case model.SQLServer: + sql = fmt.Sprintf("SELECT name, '' FROM sys.identity_columns WHERE object_id = OBJECT_ID(%s)", text(e, q)) + case model.Oracle: + sql = fmt.Sprintf(`SELECT column_name, generation_type FROM all_tab_identity_cols + WHERE owner = %s AND table_name = %s`, text(e, schema), text(e, table)) + default: + return nil, nil + } + rows, err := catalogRows(ctx, s, sql) + if err != nil { + // all_tab_identity_cols only exists from 12c on. + if e == model.Oracle && ctx.Err() == nil { + return nil, nil + } + return nil, err + } + var out []identity + for _, r := range rows { + if len(r) < 2 || r[len(r)-2] == nil { + continue + } + detail := "" + if r[len(r)-1] != nil { + detail = *r[len(r)-1] + } + out = append(out, identity{column: *r[len(r)-2], detail: detail}) + } + return out, nil +} + +// identityStatements returns the statements around inserting rows that +// carry identity values: before (SQL Server's IDENTITY_INSERT, an Oracle +// ALWAYS identity made BY DEFAULT) and after (back off, and the generator +// moved past the largest value). +func identityStatements(e model.Engine, table string, ids []identity, columns []string) (before, after []string) { + var used []identity + for _, i := range ids { + if slices.Contains(columns, i.column) { + used = append(used, i) + } + } + if len(used) == 0 { + return nil, nil + } + switch e { + case model.SQLServer: + return []string{"SET IDENTITY_INSERT " + table + " ON"}, []string{"SET IDENTITY_INSERT " + table + " OFF"} + case model.Postgres: + for _, i := range used { + after = append(after, fmt.Sprintf("SELECT setval(%s, COALESCE(MAX(%s), 0) + 1, false) FROM %s", + text(e, i.detail), ident(e, i.column), table)) + } + return nil, after + case model.Oracle: + for _, i := range used { + if i.detail == "ALWAYS" { + before = append(before, fmt.Sprintf("ALTER TABLE %s MODIFY (%s GENERATED BY DEFAULT AS IDENTITY)", + table, ident(e, i.column))) + } + } + for _, i := range used { + how := "BY DEFAULT" + if i.detail == "ALWAYS" { + how = "ALWAYS" + } + after = append(after, fmt.Sprintf("ALTER TABLE %s MODIFY (%s GENERATED %s AS IDENTITY (START WITH LIMIT VALUE))", + table, ident(e, i.column), how)) + } + return before, after + } + return nil, nil +} + +// dependencyOrder orders tables so that a table comes after the tables its +// foreign keys point to (as far as cycles allow). +func dependencyOrder(ctx context.Context, s drivers.Session, schema string, tables []string) []string { + e := s.Engine() + var sql string + switch e { + case model.Postgres: + sql = fmt.Sprintf(`SELECT cl.relname::text, rf.relname::text FROM pg_constraint c + JOIN pg_class cl ON cl.oid = c.conrelid JOIN pg_namespace n ON n.oid = cl.relnamespace + JOIN pg_class rf ON rf.oid = c.confrelid JOIN pg_namespace rn ON rn.oid = rf.relnamespace + WHERE c.contype = 'f' AND n.nspname = %[1]s AND rn.nspname = %[1]s`, text(e, schema)) + case model.MySQL, model.MariaDB: + sql = fmt.Sprintf(`SELECT TABLE_NAME, REFERENCED_TABLE_NAME FROM information_schema.REFERENTIAL_CONSTRAINTS + WHERE CONSTRAINT_SCHEMA = %[1]s AND UNIQUE_CONSTRAINT_SCHEMA = %[1]s`, text(e, schema)) + case model.SQLServer: + sql = fmt.Sprintf(`SELECT OBJECT_NAME(parent_object_id), OBJECT_NAME(referenced_object_id) + FROM sys.foreign_keys + WHERE OBJECT_SCHEMA_NAME(parent_object_id) = %[1]s + AND OBJECT_SCHEMA_NAME(referenced_object_id) = %[1]s`, text(e, schema)) + case model.Oracle: + sql = fmt.Sprintf(`SELECT c.table_name, r.table_name FROM all_constraints c + JOIN all_constraints r ON r.owner = c.r_owner AND r.constraint_name = c.r_constraint_name + WHERE c.constraint_type = 'R' AND c.owner = %[1]s AND r.owner = %[1]s`, text(e, schema)) + case model.SQLite: + sql = fmt.Sprintf(`SELECT m.name, f."table" FROM %s.sqlite_schema m, + pragma_foreign_key_list(m.name, %s) f + WHERE m.type = 'table'`, ident(e, schema), text(e, schema)) + default: + // No foreign keys in Redis or CQL. + return tables + } + rows, err := catalogRows(ctx, s, sql) + if err != nil { + return tables + } + parents := map[string]map[string]bool{} + for _, r := range rows { + if len(r) < 2 || r[len(r)-1] == nil || r[len(r)-2] == nil { + continue + } + child, parent := *r[len(r)-2], *r[len(r)-1] + if parent != child { + if parents[child] == nil { + parents[child] = map[string]bool{} + } + parents[child][parent] = true + } + } + return order(tables, parents) +} + +// order is Kahn's order, keeping the given order among independent tables. +func order(tables []string, parents map[string]map[string]bool) []string { + set := map[string]bool{} + for _, t := range tables { + set[t] = true + } + done := map[string]bool{} + out := make([]string, 0, len(tables)) + left := slices.Clone(tables) + for len(left) > 0 { + before := len(left) + kept := left[:0] + for _, t := range left { + ready := true + for p := range parents[t] { + if !done[p] && set[p] { + ready = false + break + } + } + if ready { + done[t] = true + out = append(out, t) + } else { + kept = append(kept, t) + } + } + left = kept + if len(left) == before { + // A cycle: keep the rest in their order. + out = append(out, left...) + left = nil + } + } + return out +} diff --git a/internal/transfer/catalog_test.go b/internal/transfer/catalog_test.go new file mode 100644 index 0000000..7f21d7f --- /dev/null +++ b/internal/transfer/catalog_test.go @@ -0,0 +1,48 @@ +package transfer + +import ( + "reflect" + "testing" + + "github.com/LowBloat/LowQuery/internal/model" +) + +func TestParentsComeFirst(t *testing.T) { + parents := map[string]map[string]bool{ + "items": {"orders": true}, + "orders": {"customers": true}, + } + got := order([]string{"items", "orders", "customers", "logs"}, parents) + if want := []string{"customers", "logs", "orders", "items"}; !reflect.DeepEqual(got, want) { + t.Errorf("%v", got) + } + // A cycle keeps the original order. + cyc := map[string]map[string]bool{"a": {"b": true}, "b": {"a": true}} + if got := order([]string{"a", "b"}, cyc); !reflect.DeepEqual(got, []string{"a", "b"}) { + t.Errorf("%v", got) + } +} + +func TestIdentityStatements(t *testing.T) { + cols := []string{"id", "name"} + before, after := identityStatements(model.SQLServer, "[dbo].[t]", []identity{{column: "id"}}, cols) + if !reflect.DeepEqual(before, []string{"SET IDENTITY_INSERT [dbo].[t] ON"}) || + !reflect.DeepEqual(after, []string{"SET IDENTITY_INSERT [dbo].[t] OFF"}) { + t.Errorf("%q %q", before, after) + } + // Identity columns not written need nothing. + if before, after := identityStatements(model.SQLServer, "t", []identity{{column: "other"}}, cols); before != nil || after != nil { + t.Errorf("%q %q", before, after) + } + before, after = identityStatements(model.Postgres, `"public"."t"`, []identity{{column: "id", detail: "public.t_id_seq"}}, cols) + if before != nil || !reflect.DeepEqual(after, []string{ + `SELECT setval('public.t_id_seq', COALESCE(MAX("id"), 0) + 1, false) FROM "public"."t"`, + }) { + t.Errorf("%q %q", before, after) + } + before, after = identityStatements(model.Oracle, `"S"."T"`, []identity{{column: "id", detail: "ALWAYS"}}, cols) + if !reflect.DeepEqual(before, []string{`ALTER TABLE "S"."T" MODIFY ("id" GENERATED BY DEFAULT AS IDENTITY)`}) || + !reflect.DeepEqual(after, []string{`ALTER TABLE "S"."T" MODIFY ("id" GENERATED ALWAYS AS IDENTITY (START WITH LIMIT VALUE))`}) { + t.Errorf("%q %q", before, after) + } +} diff --git a/internal/transfer/export.go b/internal/transfer/export.go new file mode 100644 index 0000000..636b858 --- /dev/null +++ b/internal/transfer/export.go @@ -0,0 +1,694 @@ +package transfer + +// Exports a table, a view or a whole schema: a SQL script (structure, data +// or both) that runs back on the same database, or the rows as CSV or JSON. +// Rows are streamed from the server to the file, never held in memory. + +import ( + "bufio" + "context" + "encoding/json" + "fmt" + "os" + "regexp" + "slices" + "strings" + "unicode" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/model" +) + +type ExportFormat string + +const ( + FormatSQL ExportFormat = "sql" + FormatCSV ExportFormat = "csv" + // CSV that Excel opens with accents and columns right: `;`, BOM, CRLF. + FormatCSVExcel ExportFormat = "csv-excel" + FormatJSON ExportFormat = "json" +) + +func (f *ExportFormat) UnmarshalJSON(b []byte) error { + return unmarshalVariant(b, (*string)(f), "sql", "csv", "csv-excel", "json") +} + +type ExportContent string + +const ( + ContentAll ExportContent = "all" + ContentStructure ExportContent = "structure" + ContentData ExportContent = "data" +) + +func (c *ExportContent) UnmarshalJSON(b []byte) error { + return unmarshalVariant(b, (*string)(c), "all", "structure", "data") +} + +// unmarshalVariant reads a string that must be one of variants. +func unmarshalVariant(b []byte, out *string, variants ...string) error { + var s string + if err := json.Unmarshal(b, &s); err != nil { + return err + } + if !slices.Contains(variants, s) { + return fmt.Errorf("unknown variant `%s`, expected one of `%s`", s, strings.Join(variants, "`, `")) + } + *out = s + return nil +} + +type ExportRequest struct { + JobID string `json:"jobId"` + SessionID string `json:"sessionId"` + Schema string `json:"schema"` + // The objects to export; nil (JSON null) exports the whole schema. + Objects *[]model.DbObject `json:"objects"` + Format ExportFormat `json:"format"` + Content ExportContent `json:"content"` + // A file, or a folder for CSV/JSON of several tables. + Path string `json:"path"` + // Header comment: the app version and the source. + Source string `json:"source"` +} + +type ExportSummary struct { + Objects int `json:"objects"` + Rows uint64 `json:"rows"` + Files []string `json:"files"` + // Objects that could not be scripted, with the reason. + Warnings []string `json:"warnings"` +} + +// structureOrder holds the kinds a schema export scripts, in the order they +// are created. Cassandra indexes are not listed: the DDL of their table +// already ends with them. +var structureOrder = []string{ + "sequence", "type", "table", "foreign", "view", "matview", "function", "aggregate", + "procedure", "package", "synonym", +} + +var dataKinds = []string{"table", "view", "matview", "foreign"} + +// Export writes the rows or the script of req to req.Path. ctx cancels it +// (see Jobs); report receives progress (may be nil). A cancelled or failed +// export leaves no file behind. +func Export(ctx context.Context, s drivers.Session, req ExportRequest, report func(Progress)) (*ExportSummary, error) { + switch req.Format { + case FormatSQL, FormatCSV, FormatCSVExcel, FormatJSON: + default: + return nil, apperr.Invalidf("Unknown export format %q.", req.Format) + } + whole := req.Objects == nil + e := s.Engine() + var objects []model.DbObject + if whole { + list, err := s.ListObjects(ctx, req.Schema) + if err != nil { + return nil, err + } + objects = list + } else { + objects = slices.Clone(*req.Objects) + } + objects = slices.DeleteFunc(objects, func(o model.DbObject) bool { + return !slices.Contains(structureOrder, o.Kind) + }) + // A schema export dumps the rows of tables; picking a view exports its rows. + var data []string + for _, o := range objects { + var keep bool + switch { + case whole: + keep = o.Kind == "table" + case e == model.Cassandra && req.Format == FormatSQL: + // Materialized views cannot be INSERTed into. + keep = o.Kind == "table" + default: + keep = slices.Contains(dataKinds, o.Kind) + } + if keep { + data = append(data, o.Name) + } + } + data = dependencyOrder(ctx, s, req.Schema, data) + progress := reporter(req.JobID, report) + if req.Format == FormatSQL { + return exportSQL(ctx, s, req, objects, data, progress) + } + return exportRows(ctx, s, req, data, progress) +} + +type progressFunc = func(object string, step, steps int, rows uint64) + +// output writes to `.part` and renames it at the end, so a cancelled +// or failed export leaves no half file behind. Write errors are kept and +// reported by check and finish. +type output struct { + path string + part string + file *os.File + w *bufio.Writer + err error +} + +func createOutput(path string) (*output, error) { + part := path + ".part" + f, err := os.Create(part) + if err != nil { + return nil, ioError(err) + } + return &output{path: path, part: part, file: f, w: bufio.NewWriterSize(f, 1<<20)}, nil +} + +func (o *output) Write(p []byte) (int, error) { + if o.err != nil { + return 0, o.err + } + n, err := o.w.Write(p) + if err != nil { + o.err = err + } + return n, err +} + +func (o *output) print(s string) { _, _ = o.Write([]byte(s)) } + +// check returns the first write error. +func (o *output) check() error { return ioError(o.err) } + +func (o *output) finish() (string, error) { + if o.err == nil { + o.err = o.w.Flush() + } + closeErr := o.file.Close() + if o.err == nil { + o.err = closeErr + } + if o.err != nil { + _ = os.Remove(o.part) + return "", ioError(o.err) + } + if err := os.Rename(o.part, o.path); err != nil { + _ = os.Remove(o.part) + return "", ioError(err) + } + return o.path, nil +} + +func (o *output) abandon() { + _ = o.file.Close() + _ = os.Remove(o.part) +} + +func comment(text string) string { + var b strings.Builder + for _, l := range rustLines(text) { + b.WriteString("-- ") + b.WriteString(l) + b.WriteByte('\n') + } + return b.String() +} + +// needsTerminator reports whether a statement needs its ending in a script, +// after DDL that may end in `/` or `GO`. +func needsTerminator(ddl string) bool { + lines := rustLines(strings.TrimRightFunc(ddl, unicode.IsSpace)) + last := "" + if len(lines) > 0 { + last = strings.TrimSpace(lines[len(lines)-1]) + } + return !(strings.HasSuffix(last, ";") || last == "/" || strings.EqualFold(last, "GO") || + strings.EqualFold(last, "DELIMITER ;")) +} + +func exportSQL(ctx context.Context, s drivers.Session, req ExportRequest, objects []model.DbObject, data []string, progress progressFunc) (*ExportSummary, error) { + out, err := createOutput(req.Path) + if err != nil { + return nil, err + } + summary, err := writeScript(ctx, s, req, objects, data, progress, out) + if err == nil { + err = out.check() + } + if err != nil { + out.abandon() + return nil, err + } + file, err := out.finish() + if err != nil { + return nil, err + } + summary.Files = append(summary.Files, file) + return summary, nil +} + +func writeScript(ctx context.Context, s drivers.Session, req ExportRequest, objects []model.DbObject, data []string, progress progressFunc, w *output) (*ExportSummary, error) { + e := s.Engine() + summary := newExportSummary() + w.print(comment(req.Source)) + w.print("\n") + mysql := isMySQL(e) + if mysql { + w.print("SET FOREIGN_KEY_CHECKS = 0;\n\n") + } + structure := req.Content != ContentData + withRows := req.Content != ContentStructure + // Foreign keys PostgreSQL and SQL Server script as ALTER TABLE go to the + // end, after every table and its rows exist. + var foreignKeys []string + total := 0 + if structure { + total += len(objects) + } + if withRows { + total += len(data) + } + step := 0 + + if structure { + var ordered []model.DbObject + for _, kind := range structureOrder { + if kind == "table" { + var tables []string + for _, o := range objects { + if o.Kind == "table" { + tables = append(tables, o.Name) + } + } + for _, name := range dependencyOrder(ctx, s, req.Schema, tables) { + for _, o := range objects { + if o.Kind == "table" && o.Name == name { + ordered = append(ordered, o) + } + } + } + } else { + for _, o := range objects { + if o.Kind == kind { + ordered = append(ordered, o) + } + } + } + } + for _, o := range ordered { + if ctx.Err() != nil { + return nil, apperr.CancelledErr() + } + step++ + progress(o.Name, step, total, 0) + ddl, err := s.ObjectDDL(ctx, req.Schema, o.Name, o.Kind) + if err != nil { + if ctx.Err() != nil { + return nil, apperr.CancelledErr() + } + msg := apperr.From(err).Message + summary.Warnings = append(summary.Warnings, fmt.Sprintf("%s %s: %s", o.Kind, o.Name, msg)) + w.print(comment(fmt.Sprintf("%s %s was not scripted: %s", o.Kind, o.Name, msg))) + w.print("\n") + } else { + var body strings.Builder + for _, line := range rustLines(ddl) { + t := strings.TrimLeftFunc(line, unicode.IsSpace) + if strings.HasPrefix(t, "ALTER TABLE") && strings.Contains(t, " FOREIGN KEY ") { + foreignKeys = append(foreignKeys, line) + } else { + body.WriteString(line) + body.WriteByte('\n') + } + } + w.print(comment(o.Kind + " " + o.Name)) + b := strings.TrimRightFunc(body.String(), unicode.IsSpace) + w.print(b) + if needsTerminator(b) { + w.print(";") + } + w.print("\n\n") + } + summary.Objects++ + if err := w.check(); err != nil { + return nil, err + } + } + } + + if withRows { + for _, table := range data { + if ctx.Err() != nil { + return nil, apperr.CancelledErr() + } + step++ + current := step + rows, err := writeTableRows(ctx, s, req.Schema, table, w, func(n uint64) { + progress(table, current, total, n) + }) + if err != nil { + return nil, err + } + summary.Rows += rows + if !structure { + summary.Objects++ + } + } + } + + if len(foreignKeys) > 0 { + w.print(comment("Foreign keys")) + for _, fk := range foreignKeys { + w.print(strings.TrimSpace(fk) + "\n") + } + w.print("\n") + } + if mysql { + w.print("SET FOREIGN_KEY_CHECKS = 1;\n") + } + return summary, nil +} + +func newExportSummary() *ExportSummary { + return &ExportSummary{Files: []string{}, Warnings: []string{}} +} + +// writeTableRows writes INSERT statements for every row of a table, with +// what identity columns need around them. +func writeTableRows(ctx context.Context, s drivers.Session, schema, table string, w *output, progress func(uint64)) (uint64, error) { + e := s.Engine() + generated, err := generatedColumns(ctx, s, schema, table) + if err != nil { + return 0, err + } + all, err := s.ListColumns(ctx, schema, table) + if err != nil { + return 0, err + } + // CQL literals depend on the column's type; counters need the key. + var types, columns, quoted []string + var keys []bool + for _, c := range all { + if generated[c.Name] { + continue + } + types = append(types, c.TypeName) + keys = append(keys, c.PrimaryKey) + columns = append(columns, c.Name) + quoted = append(quoted, ident(e, c.Name)) + } + if len(columns) == 0 { + return 0, nil + } + target := qualified(e, schema, table) + ids, err := identityColumns(ctx, s, schema, table) + if err != nil { + return 0, err + } + before, after := identityStatements(e, target, ids, columns) + sel := "SELECT " + strings.Join(quoted, ", ") + " FROM " + target + + w.print(comment("Data for " + table)) + for _, stmt := range before { + w.print(stmt + ";\n") + } + var kinds []model.ValueKind + rows, err := streamRows(ctx, s, sel, func(cols []model.ColumnInfo, batch []model.Row) error { + if len(kinds) == 0 { + kinds = make([]model.ValueKind, len(cols)) + for i, c := range cols { + kinds[i] = c.Kind + } + } + t := &insertTarget{engine: e, table: target, columns: quoted, kinds: kinds, types: types, keys: keys} + _ = writeInserts(w, t, batch) + return w.check() + }, progress) + if err != nil { + return 0, err + } + for _, stmt := range after { + w.print(stmt + ";\n") + } + w.print("\n") + return rows, w.check() +} + +// streamRows streams the rows of sel to write, batch by batch, until the +// end or a cancel. +func streamRows(ctx context.Context, s drivers.Session, sel string, write func([]model.ColumnInfo, []model.Row) error, progress func(uint64)) (uint64, error) { + streamCtx, stop := context.WithCancel(drivers.WithFullValues(ctx)) + defer stop() + sink := make(chan drivers.StreamEvent, 4) + var readErr error + go func() { + _, readErr = s.Stream(streamCtx, sel, sink) + close(sink) + }() + var columns []model.ColumnInfo + var rows uint64 + var writeErr error + for ev := range sink { + if writeErr != nil { + // Drain until the reader sees the stop. + continue + } + if ctx.Err() != nil { + writeErr = apperr.CancelledErr() + stop() + continue + } + if ev.Columns != nil { + columns = ev.Columns + continue + } + if err := write(columns, ev.Rows); err != nil { + writeErr = err + stop() + continue + } + rows += uint64(len(ev.Rows)) + progress(rows) + } + // The sink is closed after Stream returned: readErr is set. + if writeErr != nil { + return 0, writeErr + } + if readErr != nil { + return 0, cancelledIf(ctx, readErr) + } + return rows, nil +} + +func csvField(v string, delimiter rune) string { + if strings.ContainsRune(v, delimiter) || strings.ContainsAny(v, "\"\n\r") { + return `"` + strings.ReplaceAll(v, `"`, `""`) + `"` + } + return v +} + +var jsonNumber = regexp.MustCompile(`^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?$`) + +// jsonValue writes a cell as a JSON value: numbers, booleans and JSON +// columns as themselves, everything else as a string. +func jsonValue(kind model.ValueKind, v *string) string { + if v == nil { + return "null" + } + switch kind { + case model.KindNumber: + if jsonNumber.MatchString(strings.Trim(*v, " \t\n\r")) { + return *v + } + case model.KindBool: + if b, ok := truth(*v); ok { + if b { + return "true" + } + return "false" + } + case model.KindJSON: + if compact, err := compactJSON(*v); err == nil { + return compact + } + } + return jsonString(*v) +} + +// jsonString writes s as a JSON string, escaping what JSON requires (as +// serde_json does: no HTML escapes). +func jsonString(s string) string { + const hex = "0123456789abcdef" + var b strings.Builder + b.Grow(len(s) + 2) + b.WriteByte('"') + for _, r := range s { + switch r { + case '"': + b.WriteString(`\"`) + case '\\': + b.WriteString(`\\`) + case '\n': + b.WriteString(`\n`) + case '\r': + b.WriteString(`\r`) + case '\t': + b.WriteString(`\t`) + case '\b': + b.WriteString(`\b`) + case '\f': + b.WriteString(`\f`) + default: + if r < 0x20 { + b.WriteString(`\u00`) + b.WriteByte(hex[r>>4]) + b.WriteByte(hex[r&0xF]) + } else { + b.WriteRune(r) + } + } + } + b.WriteByte('"') + return b.String() +} + +// fileName is the file for a table's rows: the table name without +// characters that file systems reject. +func fileName(table, ext string) string { + safe := strings.Map(func(r rune) rune { + if strings.ContainsRune(`<>:"/\|?*`, r) || unicode.IsControl(r) { + return '_' + } + return r + }, table) + return safe + "." + ext +} + +// joinPath joins a folder and a file name as Rust's Path::join does on the +// platform: one separator, the folder kept as given. +func joinPath(dir, name string) string { + if dir == "" { + return name + } + if last := dir[len(dir)-1]; os.IsPathSeparator(last) { + return dir + name + } + return dir + string(os.PathSeparator) + name +} + +func exportRows(ctx context.Context, s drivers.Session, req ExportRequest, tables []string, progress progressFunc) (*ExportSummary, error) { + e := s.Engine() + ext := "csv" + if req.Format == FormatJSON { + ext = "json" + } + single := len(tables) == 1 && req.Objects != nil + if !single { + if err := os.MkdirAll(req.Path, 0o755); err != nil { + return nil, ioError(err) + } + } + summary := newExportSummary() + for i, table := range tables { + path := req.Path + if !single { + path = joinPath(req.Path, fileName(table, ext)) + } + out, err := createOutput(path) + if err != nil { + return nil, err + } + sel := "SELECT * FROM " + qualified(e, req.Schema, table) + rows, err := writeRows(ctx, s, req.Format, sel, out, func(n uint64) { + progress(table, i+1, len(tables), n) + }) + if err == nil { + err = out.check() + } + if err != nil { + out.abandon() + return nil, err + } + file, err := out.finish() + if err != nil { + return nil, err + } + summary.Rows += rows + summary.Objects++ + summary.Files = append(summary.Files, file) + } + if summary.Objects == 0 { + return nil, apperr.New(apperr.Invalid, "There are no tables to export.") + } + return summary, nil +} + +// writeRows writes the rows of sel as CSV or JSON. +func writeRows(ctx context.Context, s drivers.Session, format ExportFormat, sel string, w *output, progress func(uint64)) (uint64, error) { + delimiter, newline := ',', "\n" + if format == FormatCSVExcel { + delimiter, newline = ';', "\r\n" + w.print("\uFEFF") + } + if format == FormatJSON { + w.print("[") + } + first := true + rows, err := streamRows(ctx, s, sel, func(cols []model.ColumnInfo, batch []model.Row) error { + var line strings.Builder + if format == FormatJSON { + keys := make([]string, len(cols)) + for i, c := range cols { + keys[i] = jsonString(c.Name) + } + for _, row := range batch { + line.Reset() + if !first { + line.WriteByte(',') + } + line.WriteString("\n {") + n := min(len(keys), len(row)) + for j := range n { + if j > 0 { + line.WriteString(", ") + } + line.WriteString(keys[j]) + line.WriteString(": ") + line.WriteString(jsonValue(cols[j].Kind, row[j])) + } + line.WriteByte('}') + w.print(line.String()) + first = false + } + } else { + sep := string(delimiter) + if first { + header := make([]string, len(cols)) + for i, c := range cols { + header[i] = csvField(c.Name, delimiter) + } + w.print(strings.Join(header, sep) + newline) + first = false + } + for _, row := range batch { + fields := make([]string, len(row)) + for j, v := range row { + if v != nil { + fields[j] = csvField(*v, delimiter) + } + } + w.print(strings.Join(fields, sep) + newline) + } + } + return w.check() + }, progress) + if err != nil { + return 0, err + } + if format == FormatJSON { + if first { + w.print("]\n") + } else { + w.print("\n]\n") + } + } + return rows, nil +} diff --git a/internal/transfer/export_test.go b/internal/transfer/export_test.go new file mode 100644 index 0000000..eca148f --- /dev/null +++ b/internal/transfer/export_test.go @@ -0,0 +1,238 @@ +package transfer + +import ( + "encoding/json" + "os" + "path/filepath" + "reflect" + "strconv" + "strings" + "testing" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" +) + +func itoa(i int) string { return strconv.Itoa(i) } + +// bom is U+FEFF in UTF-8, spelled as bytes so no editor turns it into an +// invisible character. +const bom = "\xEF\xBB\xBF" + +func TestCSVQuotesOnlyWhenNeeded(t *testing.T) { + cases := []struct { + v string + d rune + want string + }{ + {"plain", ',', "plain"}, + {"a,b", ',', `"a,b"`}, + {"a,b", ';', "a,b"}, + {"say \"hi\"\nbye", ';', "\"say \"\"hi\"\"\nbye\""}, + } + for _, c := range cases { + if got := csvField(c.v, c.d); got != c.want { + t.Errorf("%q: %q", c.v, got) + } + } +} + +func TestJSONKeepsTypes(t *testing.T) { + cases := []struct { + kind model.ValueKind + v *string + want string + }{ + {model.KindNumber, sp("12.50"), "12.50"}, + {model.KindNumber, sp("NaN"), `"NaN"`}, + {model.KindNumber, sp("01"), `"01"`}, + {model.KindBool, sp("true"), "true"}, + {model.KindBool, sp("maybe"), `"maybe"`}, + {model.KindJSON, sp(`{"a": [1, 2]}`), `{"a":[1,2]}`}, + {model.KindJSON, sp(`{bad`), `"{bad"`}, + {model.KindText, nil, "null"}, + {model.KindText, sp("\n\x01"), `"\n\u0001"`}, + } + for _, c := range cases { + if got := jsonValue(c.kind, c.v); got != c.want { + t.Errorf("%s: %s, want %s", c.kind, got, c.want) + } + } +} + +func TestTerminatorsFollowTheDDL(t *testing.T) { + if needsTerminator("CREATE TABLE t (a int);\n") { + t.Error("semicolon") + } + if needsTerminator("CREATE PROCEDURE p AS SELECT 1\nGO\n") { + t.Error("GO") + } + if needsTerminator("END;\n/\n") { + t.Error("slash") + } + if !needsTerminator("CREATE VIEW v AS SELECT 1") { + t.Error("view") + } + if got := fileName("a/b:c", "csv"); got != "a_b_c.csv" { + t.Error(got) + } + if got := comment("a\r\nb\n"); got != "-- a\n-- b\n" { + t.Errorf("%q", got) + } +} + +func TestRequestShapesFromTheInterface(t *testing.T) { + var req ExportRequest + err := json.Unmarshal([]byte(`{"jobId":"j","sessionId":"s","schema":"main","objects":null,`+ + `"format":"csv-excel","content":"data","path":"p","source":"x"}`), &req) + if err != nil || req.Objects != nil || req.Format != FormatCSVExcel || req.Content != ContentData || req.JobID != "j" { + t.Errorf("%+v %v", req, err) + } + err = json.Unmarshal([]byte(`{"objects":[{"name":"t","kind":"table"}],"format":"sql","content":"all"}`), &req) + if err != nil || req.Objects == nil || (*req.Objects)[0].Name != "t" { + t.Errorf("%+v %v", req, err) + } + if err := json.Unmarshal([]byte(`{"format":"xml"}`), &req); err == nil { + t.Error("unknown format accepted") + } + var imp ImportRequest + err = json.Unmarshal([]byte(`{"jobId":"j","sessionId":"s","path":"p","options":{"delimiter":";","header":true},`+ + `"schema":"main","table":"t","replace":true}`), &imp) + if err != nil || *imp.Options.Delimiter != ";" || !*imp.Options.Header || !imp.Replace || imp.Table != "t" { + t.Errorf("%+v %v", imp, err) + } + b, _ := json.Marshal(newExportSummary()) + if string(b) != `{"objects":0,"rows":0,"files":[],"warnings":[]}` { + t.Error(string(b)) + } + b, _ = json.Marshal(ImportSummary{Rows: 1, SkippedColumns: []string{}}) + if string(b) != `{"rows":1,"skippedColumns":[]}` { + t.Error(string(b)) + } + b, _ = json.Marshal(Progress{JobID: "j", Object: "t", Step: 1, Steps: 2, Rows: 3}) + if string(b) != `{"jobId":"j","object":"t","step":1,"steps":2,"rows":3}` { + t.Error(string(b)) + } +} + +func TestSchemaExportsAndProgress(t *testing.T) { + s := sqliteSession(t) + mustRun(t, s, "CREATE TABLE parent (id INTEGER PRIMARY KEY, name TEXT)") + mustRun(t, s, "CREATE TABLE child (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES parent(id), \"a:b\" TEXT)") + mustRun(t, s, "CREATE VIEW v AS SELECT name FROM parent") + mustRun(t, s, "INSERT INTO parent VALUES (1, 'Ana'), (2, 'it''s, \"x\"')") + mustRun(t, s, "INSERT INTO child VALUES (10, 1, 'é')") + dir := t.TempDir() + + // The whole schema as CSV: one file per table, parents first. + var reports []Progress + summary, err := Export(bg, s, ExportRequest{JobID: "j", Schema: "main", Format: FormatCSVExcel, + Content: ContentAll, Path: filepath.Join(dir, "csv")}, func(p Progress) { reports = append(reports, p) }) + if err != nil { + t.Fatal(err) + } + if summary.Objects != 2 || summary.Rows != 3 || len(summary.Files) != 2 || + filepath.Base(summary.Files[0]) != "parent.csv" || filepath.Base(summary.Files[1]) != "child.csv" { + t.Errorf("%+v", summary) + } + want := []Progress{{"j", "parent", 1, 2, 2}, {"j", "child", 2, 2, 1}} + if !reflect.DeepEqual(reports, want) { + t.Errorf("%+v", reports) + } + b, _ := os.ReadFile(summary.Files[0]) + if string(b) != bom+"id;name\r\n1;Ana\r\n2;\"it's, \"\"x\"\"\"\r\n" { + t.Errorf("%q", b) + } + + // A view picked alone exports its rows to the file given. + path := filepath.Join(dir, "v.json") + objects := []model.DbObject{{Name: "v", Kind: "view"}} + summary, err = Export(bg, s, ExportRequest{Schema: "main", Objects: &objects, Format: FormatJSON, + Content: ContentAll, Path: path}, nil) + if err != nil || summary.Files[0] != path { + t.Fatalf("%+v %v", summary, err) + } + b, _ = os.ReadFile(path) + if string(b) != "[\n {\"name\": \"Ana\"},\n {\"name\": \"it's, \\\"x\\\"\"}\n]\n" { + t.Errorf("%q", b) + } + + // Structure only scripts every object, in creation order. + path = filepath.Join(dir, "schema.sql") + summary, err = Export(bg, s, ExportRequest{Schema: "main", Format: FormatSQL, Content: ContentStructure, + Path: path, Source: "LowQuery test\nSource: x"}, nil) + if err != nil || summary.Objects != 3 || summary.Rows != 0 { + t.Fatalf("%+v %v", summary, err) + } + b, _ = os.ReadFile(path) + script := string(b) + if !strings.HasPrefix(script, "-- LowQuery test\n-- Source: x\n\n-- table parent\n") || + strings.Index(script, "-- table child") > strings.Index(script, "-- view v") || + strings.Contains(script, "INSERT") { + t.Errorf("%s", script) + } + if _, err := os.Stat(path + ".part"); !os.IsNotExist(err) { + t.Error("the .part file was left") + } + + // Nothing to export. + objects = []model.DbObject{{Name: "x", Kind: "index"}} + _, err = Export(bg, s, ExportRequest{Schema: "main", Objects: &objects, Format: FormatCSV, Path: filepath.Join(dir, "none")}, nil) + if e := apperr.From(err); e == nil || e.Kind != apperr.Invalid || e.Message != "There are no tables to export." { + t.Errorf("%v", err) + } +} + +func TestCancelledExportLeavesNoFile(t *testing.T) { + s := sqliteSession(t) + mustRun(t, s, "CREATE TABLE big (id INTEGER PRIMARY KEY, v TEXT)") + mustRun(t, s, "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 5000) "+ + "INSERT INTO big SELECT x, 'value ' || x FROM c") + dir := t.TempDir() + for _, format := range []ExportFormat{FormatSQL, FormatCSV} { + var jobs Jobs + ctx := jobs.Start(bg, "job", s) + path := filepath.Join(dir, "big."+string(format)) + objects := []model.DbObject{{Name: "big", Kind: "table"}} + _, err := Export(ctx, s, ExportRequest{JobID: "job", Schema: "main", Objects: &objects, Format: format, + Content: ContentData, Path: path}, func(p Progress) { + if p.Rows > 0 { + jobs.Cancel("job") + } + }) + jobs.Finish("job") + if e := apperr.From(err); e == nil || e.Kind != apperr.Cancelled { + t.Fatalf("%s: %v", format, err) + } + entries, _ := os.ReadDir(dir) + if len(entries) != 0 { + t.Errorf("%s: files left: %v", format, entries) + } + // The session is still usable. + mustRun(t, s, "SELECT count(*) FROM big") + } +} + +func TestJobs(t *testing.T) { + var jobs Jobs + if _, ok := jobs.Cancel("none"); ok { + t.Error("unknown job cancelled") + } + s := sqliteSession(t) + ctx := jobs.Start(bg, "a", s) + if got, ok := jobs.Cancel("a"); !ok || got != s { + t.Error("session not returned") + } + if ctx.Err() == nil { + t.Error("context not cancelled") + } + jobs.Finish("a") + if _, ok := jobs.Cancel("a"); ok { + t.Error("finished job still listed") + } + ctx = jobs.Start(bg, "b", s) + jobs.Finish("b") + if ctx.Err() == nil { + t.Error("finish did not release the context") + } +} diff --git a/internal/transfer/import.go b/internal/transfer/import.go new file mode 100644 index 0000000..bb2488a --- /dev/null +++ b/internal/transfer/import.go @@ -0,0 +1,824 @@ +package transfer + +// Imports rows from a CSV or JSON file into a table. The file's encoding, +// delimiter and header are detected; columns are matched by name; values +// written the way spreadsheets in many locales write them (`1.234,56`, +// `31/12/2024`, `sim`) are converted for the column's type. Everything runs +// in one transaction: an error leaves the table as it was. Cassandra has no +// transactions: its rows are inserted one statement at a time, and an error +// leaves the rows written so far. + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "strconv" + "strings" + "unicode" + "unicode/utf8" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/model" + "github.com/LowBloat/LowQuery/internal/textcodec" +) + +type FileFormat string + +const ( + FileCSV FileFormat = "csv" + FileJSON FileFormat = "json" +) + +// ReadOptions is what the user can change after the preview. +type ReadOptions struct { + // One character; nil detects it. + Delimiter *string `json:"delimiter"` + // nil detects it. + Header *bool `json:"header"` +} + +// Inferred is the inferred type of a file column, for a new table. +type Inferred string + +const ( + InferredInteger Inferred = "integer" + InferredDecimal Inferred = "decimal" + InferredBoolean Inferred = "boolean" + InferredDate Inferred = "date" + InferredTimestamp Inferred = "timestamp" + InferredText Inferred = "text" +) + +type ImportPreview struct { + Format FileFormat `json:"format"` + Encoding string `json:"encoding"` + Delimiter string `json:"delimiter"` + Header bool `json:"header"` + Columns []string `json:"columns"` + // The first rows, as they will be read. + Rows []model.Row `json:"rows"` + TotalRows int `json:"totalRows"` + Inferred []Inferred `json:"inferred"` + // Longest value per column (in characters), for text lengths. + MaxLengths []int `json:"maxLengths"` +} + +type ImportRequest struct { + JobID string `json:"jobId"` + SessionID string `json:"sessionId"` + Path string `json:"path"` + Options ReadOptions `json:"options"` + Schema string `json:"schema"` + Table string `json:"table"` + // Delete the table's rows first (in the same transaction). + Replace bool `json:"replace"` +} + +type ImportSummary struct { + Rows uint64 `json:"rows"` + // File columns with no table column of the same name. + SkippedColumns []string `json:"skippedColumns"` +} + +// detectDelimiter returns the delimiter used most outside quotes in the +// first lines. +func detectDelimiter(text string) rune { + lines := rustLines(text) + if len(lines) > 5 { + lines = lines[:5] + } + sample := strings.Join(lines, "\n") + best, bestN := ',', 0 + for _, d := range []rune{',', ';', '\t', '|'} { + quoted := false + n := 0 + for _, c := range sample { + if c == '"' { + quoted = !quoted + } + if !quoted && c == d { + n++ + } + } + if n > bestN { + best, bestN = d, n + } + } + return best +} + +// parseCSV reads RFC 4180 records: quoted fields may hold delimiters, quotes +// (doubled) and line breaks. +func parseCSV(text string, delimiter rune) [][]string { + var records [][]string + var record []string + var field strings.Builder + quoted, any := false, false + peek := func(i int) rune { + if i >= len(text) { + return -1 + } + r, _ := utf8.DecodeRuneInString(text[i:]) + return r + } + blank := func(r []string) bool { return len(r) == 1 && r[0] == "" } + for i := 0; i < len(text); { + c, size := utf8.DecodeRuneInString(text[i:]) + i += size + any = true + switch { + case quoted: + if c == '"' { + if peek(i) == '"' { + field.WriteByte('"') + i++ + } else { + quoted = false + } + } else { + field.WriteRune(c) + } + case c == '"' && field.Len() == 0: + quoted = true + case c == delimiter: + record = append(record, field.String()) + field.Reset() + case c == '\n' || c == '\r': + if c == '\r' && peek(i) == '\n' { + i++ + } + record = append(record, field.String()) + field.Reset() + if !blank(record) { + records = append(records, record) + } + record = nil + any = false + default: + field.WriteRune(c) + } + } + if any || field.Len() > 0 || len(record) > 0 { + record = append(record, field.String()) + if !blank(record) { + records = append(records, record) + } + } + return records +} + +const notAnObject = "Each JSON item must be an object with one key per column." + +// field is one key of a JSON record with its value kept as the text it was +// written in: parsing numbers into float64 would cut NUMERIC, BIGINT and +// varint values to 17 digits. +type field struct { + key string + value *string +} + +// isNonObjectStart reports whether a JSON value starting with b is a valid +// start of something other than an object (a type error, not a syntax one). +func isNonObjectStart(b byte) bool { + return b == '[' || b == '"' || b == '-' || (b >= '0' && b <= '9') || b == 't' || b == 'f' || b == 'n' +} + +func firstByte(raw []byte) byte { + raw = bytes.TrimLeft(raw, " \t\r\n") + if len(raw) == 0 { + return 0 + } + return raw[0] +} + +// parseRecord reads one JSON object (already validated) as its fields in +// order. As in a JSON object, the last of repeated keys wins. +func parseRecord(raw []byte) ([]field, error) { + dec := json.NewDecoder(bytes.NewReader(raw)) + if _, err := dec.Token(); err != nil { // { + return nil, err + } + var fields []field + for dec.More() { + tok, err := dec.Token() + if err != nil { + return nil, err + } + key, _ := tok.(string) + var value json.RawMessage + if err := dec.Decode(&value); err != nil { + return nil, err + } + v, err := rawText(value) + if err != nil { + return nil, err + } + found := false + for i := range fields { + if fields[i].key == key { + fields[i].value = v + found = true + break + } + } + if !found { + fields = append(fields, field{key: key, value: v}) + } + } + return fields, nil +} + +// rawText is a raw JSON value as the text of the cell: strings unescaped, +// numbers as written, null as no value, arrays, objects and booleans +// compact. +func rawText(raw []byte) (*string, error) { + raw = bytes.TrimSpace(raw) + if len(raw) == 0 { + return nil, errors.New("empty value") + } + switch b := raw[0]; { + case b == '"': + var s string + if err := json.Unmarshal(raw, &s); err != nil { + return nil, err + } + return &s, nil + case b == '-' || (b >= '0' && b <= '9'): + s := string(raw) + return &s, nil + case string(raw) == "null": + return nil, nil + } + s, err := compactJSON(string(raw)) + if err != nil { + return nil, err + } + return &s, nil +} + +// compactJSON validates a JSON text and removes its insignificant spaces. +func compactJSON(v string) (string, error) { + var buf bytes.Buffer + if err := json.Compact(&buf, []byte(v)); err != nil { + return "", err + } + return buf.String(), nil +} + +// parseJSON reads the columns and rows of a JSON array of objects, or of one +// object per line, every value as text. +func parseJSON(text string) ([]string, []model.Row, error) { + var records [][]field + if strings.HasPrefix(strings.TrimLeftFunc(text, unicode.IsSpace), "[") { + invalid := func(err error) error { + return apperr.Invalidf("The JSON file is not valid: %v", err) + } + dec := json.NewDecoder(strings.NewReader(text)) + if _, err := dec.Token(); err != nil { // [ + return nil, nil, invalid(err) + } + for dec.More() { + var raw json.RawMessage + if err := dec.Decode(&raw); err != nil { + return nil, nil, invalid(err) + } + if firstByte(raw) != '{' { + return nil, nil, apperr.New(apperr.Invalid, notAnObject) + } + rec, err := parseRecord(raw) + if err != nil { + return nil, nil, invalid(err) + } + records = append(records, rec) + } + if _, err := dec.Token(); err != nil { // ] + return nil, nil, invalid(err) + } + if _, err := dec.Token(); err != io.EOF { + if err == nil { + err = errors.New("trailing characters") + } + return nil, nil, invalid(err) + } + } else { + n := 0 + for _, l := range rustLines(text) { + if strings.TrimSpace(l) == "" { + continue + } + n++ + lineErr := func(err error) error { + return apperr.Invalidf("Line %d is not valid JSON: %v", n, err) + } + first := firstByte([]byte(l)) + if first != '{' && isNonObjectStart(first) { + return nil, nil, apperr.New(apperr.Invalid, notAnObject) + } + var raw json.RawMessage + if err := json.Unmarshal([]byte(l), &raw); err != nil { + return nil, nil, lineErr(err) + } + rec, err := parseRecord(raw) + if err != nil { + return nil, nil, lineErr(err) + } + records = append(records, rec) + } + } + columns := []string{} + index := map[string]int{} + for _, rec := range records { + for _, f := range rec { + if _, ok := index[f.key]; !ok { + index[f.key] = len(columns) + columns = append(columns, f.key) + } + } + } + rows := make([]model.Row, len(records)) + for i, rec := range records { + row := make(model.Row, len(columns)) + for _, f := range rec { + row[index[f.key]] = f.value + } + rows[i] = row + } + return columns, rows, nil +} + +// looksLikeHeader reports whether the first record names the columns: no +// value in it is empty, a number or a date, and no name repeats. +func looksLikeHeader(first []string) bool { + seen := map[string]bool{} + for _, v := range first { + if strings.TrimSpace(v) == "" { + return false + } + if k, ok := inferOne(v); ok && (k == InferredInteger || k == InferredDecimal || k == InferredDate || k == InferredTimestamp) { + return false + } + } + for _, v := range first { + k := strings.ToLower(strings.TrimSpace(v)) + if seen[k] { + return false + } + seen[k] = true + } + return true +} + +type fileData struct { + format FileFormat + encoding string + delimiter rune + header bool + columns []string + rows []model.Row +} + +func readFile(path string, options ReadOptions) (*fileData, error) { + var delimiter rune = -1 + if options.Delimiter != nil { + d := *options.Delimiter + if utf8.RuneCountInString(d) != 1 { + return nil, apperr.Invalidf("The delimiter must be one character, not %q.", d) + } + delimiter, _ = utf8.DecodeRuneInString(d) + } + raw, err := os.ReadFile(path) + if err != nil { + return nil, ioError(err) + } + content, encoding := textcodec.Decode(raw) + raw = nil + lower := strings.ToLower(path) + trimmed := strings.TrimLeftFunc(content, unicode.IsSpace) + if strings.HasSuffix(lower, ".json") || strings.HasSuffix(lower, ".ndjson") || + strings.HasPrefix(trimmed, "[") || strings.HasPrefix(trimmed, "{") { + columns, rows, err := parseJSON(content) + if err != nil { + return nil, err + } + return &fileData{format: FileJSON, encoding: encoding, delimiter: ',', header: true, columns: columns, rows: rows}, nil + } + if delimiter < 0 { + delimiter = detectDelimiter(content) + } + records := parseCSV(content, delimiter) + content = "" + var header bool + if options.Header != nil { + header = *options.Header + } else { + header = len(records) > 0 && looksLikeHeader(records[0]) + } + width := 0 + for _, r := range records { + width = max(width, len(r)) + } + columns := make([]string, width) + if header && len(records) > 0 { + for i := range columns { + name := "" + if i < len(records[0]) { + name = strings.TrimSpace(records[0][i]) + } + if name == "" { + name = "column_" + strconv.Itoa(i+1) + } + columns[i] = name + } + records = records[1:] + } else { + for i := range columns { + columns[i] = "column_" + strconv.Itoa(i+1) + } + } + rows := make([]model.Row, len(records)) + for i, r := range records { + row := make(model.Row, width) + for j, v := range r { + row[j] = &v + } + rows[i] = row + } + return &fileData{format: FileCSV, encoding: encoding, delimiter: delimiter, header: header, columns: columns, rows: rows}, nil +} + +func inferOne(v string) (Inferred, bool) { + v = strings.TrimSpace(v) + if v == "" { + return "", false + } + // Leading zeros (codes, postal codes) stay text. + digits := strings.TrimPrefix(v, "-") + if len(digits) > 1 && digits[0] == '0' && !strings.HasPrefix(digits, "0.") && !strings.HasPrefix(digits, "0,") { + return InferredText, true + } + if digits != "" && allDigits(digits) { + if len(digits) <= 18 { + return InferredInteger, true + } + return InferredDecimal, true + } + if _, ok := number(v); ok { + return InferredDecimal, true + } + if t, ok := temporal(v); ok { + if len(t) == 10 { + return InferredDate, true + } + return InferredTimestamp, true + } + if l := strings.ToLower(v); l == "true" || l == "false" { + return InferredBoolean, true + } + return InferredText, true +} + +// infer returns the narrowest type that holds every value of a column. +func infer(rows []model.Row, col int) Inferred { + var kind Inferred + for _, r := range rows { + if col >= len(r) || r[col] == nil { + continue + } + k, ok := inferOne(*r[col]) + if !ok { + continue + } + switch { + case kind == "": + kind = k + case kind == k: + case (kind == InferredInteger && k == InferredDecimal) || (kind == InferredDecimal && k == InferredInteger): + kind = InferredDecimal + case (kind == InferredDate && k == InferredTimestamp) || (kind == InferredTimestamp && k == InferredDate): + kind = InferredTimestamp + default: + kind = InferredText + } + if kind == InferredText { + break + } + } + if kind == "" { + return InferredText + } + return kind +} + +// PreviewFile reads a CSV or JSON file and shows how it will be imported. +func PreviewFile(path string, options ReadOptions) (*ImportPreview, error) { + data, err := readFile(path, options) + if err != nil { + return nil, err + } + n := len(data.columns) + p := &ImportPreview{ + Format: data.format, + Encoding: data.encoding, + Delimiter: string(data.delimiter), + Header: data.header, + Columns: data.columns, + TotalRows: len(data.rows), + Inferred: make([]Inferred, n), + MaxLengths: make([]int, n), + } + for c := range n { + p.Inferred[c] = infer(data.rows, c) + for _, r := range data.rows { + if c < len(r) && r[c] != nil { + p.MaxLengths[c] = max(p.MaxLengths[c], utf8.RuneCountInString(*r[c])) + } + } + } + p.Rows = data.rows[:min(20, len(data.rows))] + if p.Rows == nil { + p.Rows = []model.Row{} + } + return p, nil +} + +// number reads `1.234,56`, `1,234.56`, `12,5` and ` 7 ` as `1234.56`, +// `1234.56`, `12.5`, `7`. +func number(v string) (string, bool) { + v = strings.Map(func(r rune) rune { + if unicode.IsSpace(r) { + return -1 + } + return r + }, v) + comma, dot := strings.LastIndex(v, ","), strings.LastIndex(v, ".") + var normal string + switch { + case comma >= 0 && dot >= 0 && comma > dot: + normal = strings.ReplaceAll(strings.ReplaceAll(v, ".", ""), ",", ".") + case comma >= 0 && dot >= 0: + normal = strings.ReplaceAll(v, ",", "") + case comma >= 0 && strings.Count(v, ",") == 1: + normal = strings.ReplaceAll(v, ",", ".") + case comma >= 0: + return "", false + default: + normal = v + } + body := stripSign(normal) + if body == "" || strings.Count(body, ".") > 1 { + return "", false + } + anyDigit := false + for i := 0; i < len(body); i++ { + switch c := body[i]; { + case c >= '0' && c <= '9': + anyDigit = true + case c == '.': + default: + return "", false + } + } + if !anyDigit { + return "", false + } + return normal, true +} + +// temporal reads `31/12/2024 [23:59[:59]]` and ISO dates with a `T` as +// `2024-12-31 23:59:59`. +func temporal(v string) (string, bool) { + v = strings.TrimSpace(v) + date, timePart, hasTime := v, "", false + if i := strings.IndexAny(v, " T"); i >= 0 { + date, timePart, hasTime = v[:i], strings.TrimRight(v[i+1:], "Z"), true + } + var iso string + if len(date) == 10 && date[4] == '-' && date[7] == '-' { + iso = date + } else { + parts := strings.Split(date, "/") + if len(parts) != 3 || len(parts[2]) != 4 || len(parts[0]) > 2 || len(parts[1]) > 2 { + return "", false + } + d, err1 := strconv.ParseUint(parts[0], 10, 32) + m, err2 := strconv.ParseUint(parts[1], 10, 32) + if err1 != nil || err2 != nil || d < 1 || d > 31 || m < 1 || m > 12 { + return "", false + } + iso = fmt.Sprintf("%s-%02d-%02d", parts[2], m, d) + } + for i := 0; i < len(iso); i++ { + if i == 4 || i == 7 { + if iso[i] != '-' { + return "", false + } + } else if iso[i] < '0' || iso[i] > '9' { + return "", false + } + } + if !hasTime { + return iso, true + } + t := timePart + if len(t) == 5 { + t += ":00" + } + if len(t) >= 8 && t[2] == ':' && t[5] == ':' { + return iso + " " + t, true + } + return "", false +} + +// convert turns a file value into what the column expects. Empty values +// are NULL. +func convert(kind model.ValueKind, v *string) *string { + if v == nil || strings.TrimSpace(*v) == "" { + return nil + } + switch kind { + case model.KindNumber: + if n, ok := number(*v); ok { + return &n + } + case model.KindTemporal: + if t, ok := temporal(*v); ok { + return &t + } + } + return v +} + +// Import loads the file of req into its table, in one transaction (row by +// row on Cassandra). ctx cancels it (see Jobs); report receives progress (may +// be nil). +func Import(ctx context.Context, s drivers.Session, req ImportRequest, report func(Progress)) (*ImportSummary, error) { + e := s.Engine() + data, err := readFile(req.Path, req.Options) + if err != nil { + return nil, err + } + tableColumns, err := s.ListColumns(ctx, req.Schema, req.Table) + if err != nil { + return nil, err + } + if len(tableColumns) == 0 { + return nil, apperr.NotFoundf("%s.%s was not found.", req.Schema, req.Table) + } + generated, err := generatedColumns(ctx, s, req.Schema, req.Table) + if err != nil { + return nil, err + } + // File column → table column, matched by name ignoring case, spaces, + // underscores and hyphens. + key := func(n string) string { + return strings.NewReplacer(" ", "", "_", "", "-", "").Replace(strings.ToLower(strings.TrimSpace(n))) + } + byName := map[string]model.DbColumn{} + for _, c := range tableColumns { + if !generated[c.Name] { + byName[key(c.Name)] = c + } + } + type match struct { + file int + column model.DbColumn + } + var used []match + skipped := []string{} + for i, name := range data.columns { + c, ok := byName[key(name)] + taken := false + for _, u := range used { + taken = taken || u.column.Name == c.Name + } + if ok && !taken { + used = append(used, match{i, c}) + } else { + skipped = append(skipped, name) + } + } + if len(used) == 0 { + return nil, apperr.Invalidf("No column of the file matches a column of %s. The file has: %s.", + req.Table, strings.Join(data.columns, ", ")) + } + + target := qualified(e, req.Schema, req.Table) + names := make([]string, len(used)) + quoted := make([]string, len(used)) + kinds := make([]model.ValueKind, len(used)) + types := make([]string, len(used)) + keys := make([]bool, len(used)) + for i, u := range used { + names[i] = u.column.Name + quoted[i] = ident(e, u.column.Name) + kinds[i] = columnKind(e, u.column.TypeName) + types[i] = u.column.TypeName + keys[i] = u.column.PrimaryKey + } + ids, err := identityColumns(ctx, s, req.Schema, req.Table) + if err != nil { + return nil, err + } + before, after := identityStatements(e, target, ids, names) + + run := func(sql string) error { + _, err := s.Execute(ctx, model.ExecRequest{SQL: sql, MaxRows: 0}) + return cancelledIf(ctx, err) + } + // Ending the transaction and restoring autocommit must happen even + // after a cancel. + cleanup := context.WithoutCancel(ctx) + // CQL has no transactions (SetAutocommit(false) is an error there), and + // the INSERTs are not wrapped in BEGIN BATCH either: a batch spanning + // partitions is an anti-pattern. Each row is its own statement; the + // chunks only group the progress reports. + transactional := e != model.Cassandra + wasAutocommit := transactional && s.TxState().Autocommit + if wasAutocommit { + if _, err := s.SetAutocommit(ctx, false); err != nil { + return nil, err + } + } + progress := reporter(req.JobID, report) + done, outcome := func() (int, error) { + // Oracle commits the identity changes (DDL) on its own; everything + // else is undone together on error. + for _, stmt := range before { + if err := run(stmt); err != nil { + return 0, err + } + } + if req.Replace { + // CQL cannot DELETE without a key. + clear := "DELETE FROM" + if e == model.Cassandra { + clear = "TRUNCATE" + } + if err := run(clear + " " + target); err != nil { + return 0, err + } + } + t := &insertTarget{engine: e, table: target, columns: quoted, kinds: kinds, types: types, keys: keys} + header := 0 + if data.header { + header = 1 + } + done := 0 + for start := 0; start < len(data.rows); start += rowsPerInsert { + if ctx.Err() != nil { + return done, apperr.CancelledErr() + } + chunk := data.rows[start:min(start+rowsPerInsert, len(data.rows))] + rows := make([]model.Row, len(chunk)) + for i, r := range chunk { + row := make(model.Row, len(used)) + for j, u := range used { + var v *string + if u.file < len(r) { + v = r[u.file] + } + row[j] = convert(kinds[j], v) + } + rows[i] = row + } + for _, stmt := range insertStatements(t, rows) { + if err := run(stmt); err != nil { + if apperr.From(err).Kind == apperr.Cancelled { + return done, err + } + first := done + 1 + header + ae := *apperr.From(err) + ae.Message = fmt.Sprintf("Rows %d–%d of the file: %s", first, first+len(rows)-1, ae.Message) + return done, &ae + } + } + done += len(rows) + progress(req.Table, 1, 1, uint64(done)) + } + for _, stmt := range after { + if err := run(stmt); err != nil { + return done, err + } + } + return done, nil + }() + var finish error + if transactional { + _, finish = s.EndTransaction(cleanup, outcome == nil) + } + if wasAutocommit { + _, _ = s.SetAutocommit(cleanup, true) + } + if outcome != nil { + return nil, outcome + } + if finish != nil { + return nil, finish + } + return &ImportSummary{Rows: uint64(done), SkippedColumns: skipped}, nil +} diff --git a/internal/transfer/import_test.go b/internal/transfer/import_test.go new file mode 100644 index 0000000..b5ce699 --- /dev/null +++ b/internal/transfer/import_test.go @@ -0,0 +1,322 @@ +package transfer + +import ( + "encoding/json" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" + "github.com/LowBloat/LowQuery/internal/textcodec" +) + +func TestCSVWithQuotesAndLineBreaks(t *testing.T) { + text := "id;name;note\r\n1;\"Silva; Ana\";\"line 1\nline \"\"2\"\"\"\r\n2;Bruno;\n" + if d := detectDelimiter(text); d != ';' { + t.Errorf("delimiter %q", d) + } + rows := parseCSV(text, ';') + if len(rows) != 3 { + t.Fatalf("%q", rows) + } + if want := []string{"1", "Silva; Ana", "line 1\nline \"2\""}; !reflect.DeepEqual(rows[1], want) { + t.Errorf("%q", rows[1]) + } + if want := []string{"2", "Bruno", ""}; !reflect.DeepEqual(rows[2], want) { + t.Errorf("%q", rows[2]) + } + // Blank lines are skipped; the last record needs no line break. + if rows := parseCSV("a,b\n\n1,2", ','); !reflect.DeepEqual(rows, [][]string{{"a", "b"}, {"1", "2"}}) { + t.Errorf("%q", rows) + } + if d := detectDelimiter("a\tb|c\n1\t2\n"); d != '\t' { + t.Errorf("delimiter %q", d) + } +} + +// Decoding is textcodec.Decode (shared with read_sql_file). +func TestDecodesWindows1252AndBOM(t *testing.T) { + if text, _ := textcodec.Decode([]byte{0xEF, 0xBB, 0xBF, 'a'}); text != "a" { + t.Error(text) + } + text, enc := textcodec.Decode([]byte{'S', 0xE3, 'o', ' ', 0x80}) + if text != "São €" || enc != "Windows-1252" { + t.Error(text, enc) + } +} + +func TestNumbersAndDatesFromSpreadsheets(t *testing.T) { + for in, want := range map[string]string{"1.234,56": "1234.56", "1,234.56": "1234.56", "12,5": "12.5", " 7 ": "7"} { + if got, ok := number(in); !ok || got != want { + t.Errorf("number(%q) = %q, %v", in, got, ok) + } + } + if _, ok := number("abc"); ok { + t.Error("abc") + } + for in, want := range map[string]string{ + "31/12/2024": "2024-12-31", + "1/2/2024 08:30": "2024-02-01 08:30:00", + "2024-02-29T13:45:10Z": "2024-02-29 13:45:10", + } { + if got, ok := temporal(in); !ok || got != want { + t.Errorf("temporal(%q) = %q, %v", in, got, ok) + } + } + if _, ok := temporal("12/2024"); ok { + t.Error("12/2024") + } + if got := convert(model.KindNumber, sp(" ")); got != nil { + t.Error(*got) + } + if got := convert(model.KindNumber, sp("1.234,5")); got == nil || *got != "1234.5" { + t.Error(got) + } +} + +func TestInfersColumnTypes(t *testing.T) { + rows := func(vals ...string) []model.Row { + out := make([]model.Row, len(vals)) + for i, v := range vals { + out[i] = model.Row{sp(v)} + } + return out + } + cases := []struct { + rows []model.Row + want Inferred + }{ + {rows("1", "22", ""), InferredInteger}, + {rows("1", "2,5"), InferredDecimal}, + {rows("01310", "22"), InferredText}, + {rows("31/12/2024", "2024-01-01 10:00"), InferredTimestamp}, + {rows("true", "false"), InferredBoolean}, + {rows("x", "1"), InferredText}, + {rows(), InferredText}, + } + for _, c := range cases { + if got := infer(c.rows, 0); got != c.want { + t.Errorf("%q: %s, want %s", texts(c.rows), got, c.want) + } + } +} + +func TestJSONArraysAndLines(t *testing.T) { + cols, rows, err := parseJSON(`[{"a": 1, "b": "x"}, {"b": null, "c": [1]}]`) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(cols, []string{"a", "b", "c"}) { + t.Errorf("%q", cols) + } + if got := texts(rows[1:]); !reflect.DeepEqual(got, [][]string{{"", "", "[1]"}}) { + t.Errorf("%q", got) + } + cols, rows, err = parseJSON("{\"a\": true}\n\n{\"a\": false}\n") + if err != nil || !reflect.DeepEqual(cols, []string{"a"}) || len(rows) != 2 { + t.Errorf("%q %d %v", cols, len(rows), err) + } +} + +func TestJSONNumbersKeepEveryDigit(t *testing.T) { + _, rows, err := parseJSON(`[{"a": 123456789012345678901234567890, "b": 1.50, "c": -1e5, ` + + `"d": "x\ny", "e": {"k": [1, true]}, "f": false}]`) + if err != nil { + t.Fatal(err) + } + want := [][]string{{"123456789012345678901234567890", "1.50", "-1e5", "x\ny", `{"k":[1,true]}`, "false"}} + if got := texts(rows); !reflect.DeepEqual(got, want) { + t.Errorf("%q", got) + } + for _, bad := range []string{"[1]", "{\"a\": 1}\n[2]"} { + _, _, err := parseJSON(bad) + if e := apperr.From(err); e == nil || e.Kind != apperr.Invalid || e.Message != notAnObject { + t.Errorf("%q: %v", bad, err) + } + } + for bad, prefix := range map[string]string{ + `[{"a": 1}`: "The JSON file is not valid: ", + `[{"a": 1}] x`: "The JSON file is not valid: ", + "{\"a\": 1}\n{\"a\"": "Line 2 is not valid JSON: ", + } { + _, _, err := parseJSON(bad) + if e := apperr.From(err); e == nil || e.Kind != apperr.Invalid || !strings.HasPrefix(e.Message, prefix) { + t.Errorf("%q: %v", bad, err) + } + } + // The last of repeated keys wins. + cols, rows, err := parseJSON(`[{"a": 1, "a": 2}]`) + if err != nil || len(cols) != 1 || *rows[0][0] != "2" { + t.Errorf("%q %q %v", cols, texts(rows), err) + } +} + +func TestHeaderDetection(t *testing.T) { + if !looksLikeHeader([]string{"id", "name"}) { + t.Error("id, name") + } + if looksLikeHeader([]string{"1", "Ana"}) { + t.Error("1, Ana") + } + if looksLikeHeader([]string{"a", "a"}) { + t.Error("a, a") + } + if looksLikeHeader([]string{"a", " "}) { + t.Error("blank") + } +} + +func writeFile(t *testing.T, name string, content []byte) string { + t.Helper() + path := filepath.Join(t.TempDir(), name) + if err := os.WriteFile(path, content, 0o644); err != nil { + t.Fatal(err) + } + return path +} + +func TestPreviewShapesForTheInterface(t *testing.T) { + // Windows-1252, `;`, a header and a short row. + path := writeFile(t, "people.txt", []byte("id;nome;obs\r\n1;Jo\xe3o;x\r\n02;Ana\r\n")) + p, err := PreviewFile(path, ReadOptions{}) + if err != nil { + t.Fatal(err) + } + b, _ := json.Marshal(p) + want := `{"format":"csv","encoding":"Windows-1252","delimiter":";","header":true,` + + `"columns":["id","nome","obs"],"rows":[["1","João","x"],["02","Ana",null]],` + + `"totalRows":2,"inferred":["text","text","text"],"maxLengths":[2,4,1]}` + if string(b) != want { + t.Errorf("\n got %s\nwant %s", b, want) + } + + // A blank name is no header; told there is one, the blank is named. + path = writeFile(t, "blank.csv", []byte("id,nome,\n1,Ana,x\n")) + if p, err = PreviewFile(path, ReadOptions{}); err != nil || p.Header || p.Columns[0] != "column_1" { + t.Errorf("%+v %v", p, err) + } + yes := true + p, err = PreviewFile(path, ReadOptions{Header: &yes}) + if err != nil || !reflect.DeepEqual(p.Columns, []string{"id", "nome", "column_3"}) || p.TotalRows != 1 || + !reflect.DeepEqual(p.Inferred, []Inferred{InferredInteger, InferredText, InferredText}) { + t.Errorf("%+v %v", p, err) + } + + // The options override detection. + no, comma := false, "," + path = writeFile(t, "people.csv", []byte("id;nome;obs\r\n1;Jo\xe3o;x\r\n02;Ana\r\n")) + p, err = PreviewFile(path, ReadOptions{Delimiter: &comma, Header: &no}) + if err != nil || p.Header || p.Delimiter != "," || len(p.Columns) != 1 || p.TotalRows != 3 { + t.Errorf("%+v %v", p, err) + } + var opts ReadOptions + if err := json.Unmarshal([]byte(`{"delimiter": null, "header": null}`), &opts); err != nil || opts.Delimiter != nil || opts.Header != nil { + t.Errorf("%+v %v", opts, err) + } + bad := "ab" + if _, err := PreviewFile(path, ReadOptions{Delimiter: &bad}); apperr.From(err).Kind != apperr.Invalid { + t.Errorf("%v", err) + } + + // An empty JSON array still has lists, not nulls. + p, err = PreviewFile(writeFile(t, "empty.json", []byte("[]")), ReadOptions{}) + if err != nil { + t.Fatal(err) + } + b, _ = json.Marshal(p) + want = `{"format":"json","encoding":"UTF-8","delimiter":",","header":true,"columns":[],"rows":[],` + + `"totalRows":0,"inferred":[],"maxLengths":[]}` + if string(b) != want { + t.Errorf("\n got %s\nwant %s", b, want) + } + + if _, err := PreviewFile(filepath.Join(t.TempDir(), "missing.csv"), ReadOptions{}); apperr.From(err).Kind != apperr.Internal { + t.Errorf("%v", err) + } +} + +func TestImportMatchesColumnsAndRollsBack(t *testing.T) { + s := sqliteSession(t) + mustRun(t, s, "CREATE TABLE people (id INTEGER PRIMARY KEY, full_name TEXT, born DATE, score NUMERIC)") + mustRun(t, s, "INSERT INTO people VALUES (99, 'kept', NULL, NULL)") + + // Names match ignoring case, spaces, underscores and hyphens; values + // are converted for the column's type; unknown columns are skipped. + path := writeFile(t, "people.csv", []byte("ID;Full Name;born;Score;extra\n1;Ana;31/12/2024;1.234,5;x\n2;Bruno;;;\n")) + var reports []Progress + summary, err := Import(bg, s, ImportRequest{JobID: "job-1", Path: path, Schema: "main", Table: "people"}, + func(p Progress) { reports = append(reports, p) }) + if err != nil { + t.Fatal(err) + } + if summary.Rows != 2 || !reflect.DeepEqual(summary.SkippedColumns, []string{"extra"}) { + t.Errorf("%+v", summary) + } + if want := []Progress{{JobID: "job-1", Object: "people", Step: 1, Steps: 1, Rows: 2}}; !reflect.DeepEqual(reports, want) { + t.Errorf("%+v", reports) + } + got := texts(mustRun(t, s, "SELECT id, full_name, born, score FROM people ORDER BY id")) + want := [][]string{{"1", "Ana", "2024-12-31", "1234.5"}, {"2", "Bruno", "", ""}, {"99", "kept", "", ""}} + if !reflect.DeepEqual(got, want) { + t.Errorf("%q", got) + } + if !s.TxState().Autocommit { + t.Error("autocommit was not restored") + } + + // A failing row undoes the whole import, the DELETE of replace included, + // and the error names the rows of the file. + path = writeFile(t, "dup.csv", []byte("id,full_name\n5,Eva\n1,Dup\n1,Dup\n")) + _, err = Import(bg, s, ImportRequest{Path: path, Schema: "main", Table: "people", Replace: true}, nil) + e := apperr.From(err) + if e == nil || !strings.HasPrefix(e.Message, "Rows 2–4 of the file: ") { + t.Fatalf("%v", err) + } + if got := texts(mustRun(t, s, "SELECT count(*) FROM people")); got[0][0] != "3" { + t.Errorf("%q rows after a failed import", got) + } + + path = writeFile(t, "none.json", []byte(`[{"x": 1}]`)) + _, err = Import(bg, s, ImportRequest{Path: path, Schema: "main", Table: "people"}, nil) + if e := apperr.From(err); e == nil || e.Message != "No column of the file matches a column of people. The file has: x." { + t.Errorf("%v", err) + } + _, err = Import(bg, s, ImportRequest{Path: path, Schema: "main", Table: "nobody"}, nil) + if e := apperr.From(err); e == nil || e.Kind != apperr.NotFound || e.Message != "main.nobody was not found." { + t.Errorf("%v", err) + } +} + +func TestImportStopsWhenCancelled(t *testing.T) { + s := sqliteSession(t) + mustRun(t, s, "CREATE TABLE t (id INTEGER PRIMARY KEY)") + var content strings.Builder + content.WriteString("id\n") + for i := range 1000 { + content.WriteString(itoa(i + 1)) + content.WriteByte('\n') + } + path := writeFile(t, "ids.csv", []byte(content.String())) + var jobs Jobs + ctx := jobs.Start(bg, "job", s) + defer jobs.Finish("job") + _, err := Import(ctx, s, ImportRequest{JobID: "job", Path: path, Schema: "main", Table: "t"}, func(p Progress) { + if p.Rows == 200 { + if got, ok := jobs.Cancel("job"); !ok || got != s { + t.Error("cancel did not find the job") + } + } + }) + if e := apperr.From(err); e == nil || e.Kind != apperr.Cancelled { + t.Fatalf("%v", err) + } + if got := texts(mustRun(t, s, "SELECT count(*) FROM t")); got[0][0] != "0" { + t.Errorf("%q rows after a cancelled import", got) + } + if !s.TxState().Autocommit { + t.Error("autocommit was not restored") + } +} diff --git a/internal/transfer/roundtrip_test.go b/internal/transfer/roundtrip_test.go new file mode 100644 index 0000000..8145edd --- /dev/null +++ b/internal/transfer/roundtrip_test.go @@ -0,0 +1,476 @@ +package transfer + +// Exports a table with awkward values (quotes, line breaks, backslashes, +// accents, binary, JSON, dates, identity and generated columns) and loads it +// back: from the SQL script after dropping the table, and from CSV and JSON +// after deleting its rows. The rows must come back the same. +// +// SQLite always runs. The server engines run when their variables are set +// (the same ones the driver tests read): LQ_PG_*, LQ_ORA_*, LQ_MYSQL_*, +// LQ_MSSQL_* and LQ_CASSANDRA_*. Each test works on a table (Cassandra: a +// keyspace) named uniquely, dropped at the end. +// +// Cassandra has no ORDER BY on this table, no identity or generated columns, +// and keeps its collections as CQL literals. + +import ( + "context" + "crypto/rand" + "encoding/hex" + "fmt" + "os" + "path/filepath" + "reflect" + "sort" + "strconv" + "strings" + "testing" + "time" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/drivers/fixtures" + "github.com/LowBloat/LowQuery/internal/engines" + "github.com/LowBloat/LowQuery/internal/model" +) + +var bg = context.Background() + +type roundTripCase struct { + create string + fill []string + // Columns compared (rowversion and the like change on their own). + compare string +} + +func caseFor(e model.Engine) roundTripCase { + switch e { + case model.Postgres: + return roundTripCase{ + create: `CREATE TABLE lq_schema.lq_xfer ( + id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text, + amount numeric(12,2), born date, seen timestamp(3), flag boolean, data bytea, + doc jsonb, total numeric GENERATED ALWAYS AS (amount * 2) STORED)`, + fill: []string{`INSERT INTO lq_schema.lq_xfer (name, amount, born, seen, flag, data, doc) VALUES + ('it''s "quoted"' || chr(10) || 'line \ back', 1234.56, '2024-02-29', + '2024-02-29 13:45:10.25', true, '\xdeadbeef', '{"a": [1, 2]}'), + ('Ação ☃', -0.5, NULL, NULL, false, NULL, NULL), + (NULL, NULL, '1999-12-31', NULL, NULL, '\x', '[]')`}, + compare: "id, name, amount, born, seen, flag, data, doc, total", + } + case model.MySQL, model.MariaDB: + return roundTripCase{ + create: `CREATE TABLE lq_schema.lq_xfer ( + id INT AUTO_INCREMENT PRIMARY KEY, name TEXT, amount DECIMAL(12,2), born DATE, + seen DATETIME(3), flag TINYINT(1), data VARBINARY(64), doc TEXT, + total DECIMAL(14,2) AS (amount * 2) STORED)`, + fill: []string{`INSERT INTO lq_schema.lq_xfer (name, amount, born, seen, flag, data, doc) VALUES + ('it''s "quoted"\nline \\ back', 1234.56, '2024-02-29', + '2024-02-29 13:45:10.250', 1, X'DEADBEEF', '{"a": [1, 2]}'), + ('Ação ☃', -0.5, NULL, NULL, 0, NULL, NULL), + (NULL, NULL, '1999-12-31', NULL, NULL, X'', '[]')`}, + compare: "id, name, amount, born, seen, flag, data, doc, total", + } + case model.SQLServer: + return roundTripCase{ + create: `CREATE TABLE lq_schema.lq_xfer ( + id int IDENTITY(1,1) PRIMARY KEY, name nvarchar(200), amount decimal(12,2), + born date, seen datetime2(3), flag bit, data varbinary(64), doc nvarchar(max), + total AS (amount * 2), rv rowversion)`, + fill: []string{`INSERT INTO lq_schema.lq_xfer (name, amount, born, seen, flag, data, doc) VALUES + (N'it''s "quoted"' + CHAR(10) + N'line \ back', 1234.56, '2024-02-29', + '2024-02-29 13:45:10.250', 1, 0xDEADBEEF, N'{"a": [1, 2]}'), + (N'Ação ☃', -0.5, NULL, NULL, 0, NULL, NULL), + (NULL, NULL, '1999-12-31', NULL, NULL, 0x, N'[]')`}, + compare: "id, name, amount, born, seen, flag, data, doc, total", + } + case model.Oracle: + return roundTripCase{ + create: `CREATE TABLE lq_schema.lq_xfer ( + id NUMBER(10) GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name VARCHAR2(200), + amount NUMBER(12,2), born DATE, seen TIMESTAMP(3), flag NUMBER(1), data RAW(64), + doc CLOB, total NUMBER GENERATED ALWAYS AS (amount * 2) VIRTUAL)`, + fill: []string{ + `INSERT INTO lq_schema.lq_xfer (name, amount, born, seen, flag, data, doc) VALUES + ('it''s "quoted"' || chr(10) || 'line \ back', 1234.56, DATE '2024-02-29', + TIMESTAMP '2024-02-29 13:45:10.250', 1, HEXTORAW('DEADBEEF'), RPAD('x', 3000, 'y'))`, + "INSERT INTO lq_schema.lq_xfer (name, amount, flag) VALUES ('Ação ☃', -0.5, 0)", + "INSERT INTO lq_schema.lq_xfer (born, doc) VALUES (DATE '1999-12-31', '[]')", + }, + compare: "id, name, amount, born, seen, flag, data, doc, total", + } + case model.Cassandra: + return roundTripCase{ + create: `CREATE TABLE lq_schema.lq_xfer ( + id int PRIMARY KEY, name text, big varint, amount decimal, born date, + seen timestamp, flag boolean, data blob, uid uuid, nums list, + tags set, scores map)`, + fill: []string{ + `INSERT INTO lq_schema.lq_xfer (id, name, big, amount, born, seen, flag, data, + uid, nums, tags, scores) VALUES (1, 'it''s "quoted" +line \ back; -- x', 123456789012345678901234567890, 1234567890.0987654321, '2024-02-29', + '2024-02-29 13:45:10.250+0000', true, 0xdeadbeef, + 123e4567-e89b-12d3-a456-426614174000, [3, 1, 2], {'a', 'it''s, {x}'}, + {'k': 1, 'it''s': -2})`, + `INSERT INTO lq_schema.lq_xfer (id, name, big, amount, flag, data) + VALUES (2, 'Ação ☃', -98765432109876543210, -0.5, false, 0x)`, + `INSERT INTO lq_schema.lq_xfer (id, born, uid) VALUES + (3, '1999-12-31', 00000000-0000-1000-8000-000000000000)`, + }, + compare: "id, name, big, amount, born, seen, flag, data, uid, nums, tags, scores", + } + } + return roundTripCase{ + create: `CREATE TABLE lq_schema.lq_xfer ( + id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, amount NUMERIC, born TEXT, + seen TEXT, flag INTEGER, data BLOB, doc TEXT, + total NUMERIC GENERATED ALWAYS AS (amount * 2) STORED)`, + fill: []string{`INSERT INTO lq_schema.lq_xfer (name, amount, born, seen, flag, data, doc) VALUES + ('it''s "quoted"' || char(10) || 'line \ back', 1234.56, '2024-02-29', + '2024-02-29 13:45:10.250', 1, X'DEADBEEF', '{"a": [1, 2]}'), + ('Ação ☃', -0.5, NULL, NULL, 0, NULL, NULL), + (NULL, NULL, '1999-12-31', NULL, NULL, X'', '[]')`}, + compare: "id, name, amount, born, seen, flag, data, doc, total", + } +} + +func dialect(e model.Engine) string { + switch e { + case model.Postgres: + return "postgres" + case model.Oracle: + return "oracle" + case model.MySQL, model.MariaDB: + return "mysql" + case model.SQLServer: + return "sqlserver" + case model.Cassandra: + return "cassandra" + } + return "sqlite" +} + +func mustRun(t *testing.T, s drivers.Session, sql string) []model.Row { + t.Helper() + r, err := s.Execute(bg, model.ExecRequest{SQL: sql, MaxRows: 0}) + if err != nil { + t.Fatalf("%v\n%s", err, sql) + } + return r.Rows +} + +// texts shows rows with NULL as "", for comparisons. +func texts(rows []model.Row) [][]string { + out := make([][]string, len(rows)) + for i, row := range rows { + out[i] = make([]string, len(row)) + for j, v := range row { + if v == nil { + out[i][j] = "" + } else { + out[i][j] = *v + } + } + } + return out +} + +func uniqueName(prefix string) string { + b := make([]byte, 4) + _, _ = rand.Read(b) + return prefix + hex.EncodeToString(b) +} + +// checkRoundTrip runs the round trip on s; schema replaces lq_schema, and +// Oracle names fold to uppercase. +func checkRoundTrip(t *testing.T, s drivers.Session, schema string) { + t.Helper() + e := s.Engine() + c := caseFor(e) + up := func(v string) string { + if e == model.Oracle { + return strings.ToUpper(v) + } + return v + } + name := uniqueName("lq_xfer_") + sql := func(v string) string { + return strings.ReplaceAll(strings.ReplaceAll(v, "lq_xfer", name), "lq_schema", schema) + } + table := up(name) + target := qualified(e, schema, table) + _, _ = s.Execute(bg, model.ExecRequest{SQL: "DROP TABLE " + target}) + mustRun(t, s, sql(c.create)) + t.Cleanup(func() { _, _ = s.Execute(bg, model.ExecRequest{SQL: "DROP TABLE " + target}) }) + for _, f := range c.fill { + mustRun(t, s, sql(f)) + } + // CQL cannot ORDER BY a regular column: rows are sorted here instead (the + // first column is the integer key). + order := " ORDER BY 1" + if e == model.Cassandra { + order = "" + } + sel := "SELECT " + up(c.compare) + " FROM " + target + order + fetch := func() [][]string { + rows := texts(mustRun(t, s, sel)) + if e == model.Cassandra { + sort.SliceStable(rows, func(i, j int) bool { + a, _ := strconv.ParseInt(rows[i][0], 10, 64) + b, _ := strconv.ParseInt(rows[j][0], 10, 64) + return a < b + }) + } + return rows + } + original := fetch() + if len(original) != 3 { + t.Fatalf("%d rows", len(original)) + } + + dir := t.TempDir() + request := func(format ExportFormat, path string) ExportRequest { + objects := []model.DbObject{{Name: table, Kind: "table"}} + return ExportRequest{ + JobID: "test", Schema: schema, Objects: &objects, Format: format, + Content: ContentAll, Path: path, Source: "LowQuery test export", + } + } + + // SQL script: drop the table, run the script. + path := filepath.Join(dir, "script.sql") + if _, err := Export(bg, s, request(FormatSQL, path), nil); err != nil { + t.Fatalf("SQL export: %v", err) + } + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + script := string(raw) + mustRun(t, s, "DROP TABLE "+target) + for _, stmt := range fixtures.Statements(script, dialect(e)) { + if _, err := s.Execute(bg, model.ExecRequest{SQL: stmt}); err != nil { + t.Fatalf("%v\n%s\n\nscript:\n%s", err, stmt, script) + } + } + if got := fetch(); !reflect.DeepEqual(got, original) { + t.Fatalf("SQL round trip:\n got %q\nwant %q\n%s", got, original, script) + } + + // CSV and JSON: delete the rows, import the file. + for _, f := range []struct { + format ExportFormat + name string + }{{FormatCSV, "rows.csv"}, {FormatCSVExcel, "excel.csv"}, {FormatJSON, "rows.json"}} { + path := filepath.Join(dir, f.name) + if _, err := Export(bg, s, request(f.format, path), nil); err != nil { + t.Fatalf("%s: %v", f.name, err) + } + summary, err := Import(bg, s, ImportRequest{ + JobID: "test", Path: path, Schema: schema, Table: table, Replace: true, + }, nil) + if err != nil { + content, _ := os.ReadFile(path) + t.Fatalf("%s: %v\n%s", f.name, err, content) + } + if summary.Rows != 3 { + t.Errorf("%s: %d rows", f.name, summary.Rows) + } + if got := fetch(); !reflect.DeepEqual(got, original) { + content, _ := os.ReadFile(path) + t.Fatalf("%s round trip:\n got %q\nwant %q\n%s", f.name, got, original, content) + } + } + + // Identity generators moved past the imported values (CQL has none: its + // keys are always given). + if e != model.Cassandra { + mustRun(t, s, fmt.Sprintf("INSERT INTO %s (%s) VALUES ('after')", target, ident(e, up("name")))) + } + mustRun(t, s, "DROP TABLE "+target) +} + +func openSession(t *testing.T, p model.ConnectionProfile, password *string) drivers.Session { + t.Helper() + ctx, cancel := context.WithTimeout(bg, 60*time.Second) + defer cancel() + s, err := engines.Open(ctx, p, password) + if err != nil { + t.Fatalf("connection: %v", err) + } + t.Cleanup(func() { _ = s.Close() }) + return s +} + +func env(name, fallback string) string { + if v := os.Getenv(name); v != "" { + return v + } + return fallback +} + +func port(name string, fallback uint16) uint16 { + if p, err := strconv.ParseUint(os.Getenv(name), 10, 16); err == nil { + return uint16(p) + } + return fallback +} + +func password(name string) *string { + if pw := os.Getenv(name); pw != "" { + return &pw + } + return nil +} + +func serverProfile(t *testing.T, engine model.Engine, hostVar string) model.ConnectionProfile { + t.Helper() + host := os.Getenv(hostVar) + if host == "" { + t.Skip(hostVar + " is not set") + } + p := model.DefaultProfile() + p.Name = "test" + p.Engine = engine + p.Host = host + return p +} + +// sqliteSession opens a new database file in a test folder. +func sqliteSession(t *testing.T) drivers.Session { + t.Helper() + dir, err := os.MkdirTemp("", "lq-transfer-") + if err != nil { + t.Fatal(err) + } + // Registered before the session's Close, so it runs after it. On Windows + // an antivirus may still hold the file for a moment. + t.Cleanup(func() { + for range 20 { + if os.RemoveAll(dir) == nil { + return + } + time.Sleep(100 * time.Millisecond) + } + }) + p := model.DefaultProfile() + p.Engine = model.SQLite + p.Database = filepath.Join(dir, "xfer.db") + p.CreateFile = true + return openSession(t, p, nil) +} + +func TestSQLiteExportImportRoundTrip(t *testing.T) { + checkRoundTrip(t, sqliteSession(t), "main") +} + +func TestPostgresExportImportRoundTrip(t *testing.T) { + checkRoundTrip(t, postgresSession(t), "public") +} + +func TestOracleExportImportRoundTrip(t *testing.T) { + p := serverProfile(t, model.Oracle, "LQ_ORA_HOST") + p.Port = port("LQ_ORA_PORT", 1521) + p.User = env("LQ_ORA_USER", "system") + p.Database = env("LQ_ORA_SERVICE", "FREEPDB1") + p.OracleConnectType = model.OracleService + s := openSession(t, p, password("LQ_ORA_PASSWORD")) + checkRoundTrip(t, s, strings.ToUpper(p.User)) +} + +func TestMySQLExportImportRoundTrip(t *testing.T) { + p := serverProfile(t, model.MySQL, "LQ_MYSQL_HOST") + if os.Getenv("LQ_MYSQL_ENGINE") == "mariadb" { + p.Engine = model.MariaDB + } + p.Port = port("LQ_MYSQL_PORT", 3306) + p.User = env("LQ_MYSQL_USER", "root") + p.Database = env("LQ_MYSQL_DB", "lowquery") + p.SslMode = model.SslPrefer + s := openSession(t, p, password("LQ_MYSQL_PASSWORD")) + checkRoundTrip(t, s, p.Database) +} + +func TestSQLServerExportImportRoundTrip(t *testing.T) { + p := serverProfile(t, model.SQLServer, "LQ_MSSQL_HOST") + p.Port = port("LQ_MSSQL_PORT", 1433) + p.User = env("LQ_MSSQL_USER", "sa") + p.Database = env("LQ_MSSQL_DB", "master") + p.SslMode = model.SslPrefer + pw := os.Getenv("LQ_MSSQL_PASSWORD") + s := openSession(t, p, &pw) + checkRoundTrip(t, s, "dbo") +} + +func cassandraSession(t *testing.T) drivers.Session { + t.Helper() + p := serverProfile(t, model.Cassandra, "LQ_CASSANDRA_HOST") + p.Port = port("LQ_CASSANDRA_PORT", 9042) + p.User = os.Getenv("LQ_CASSANDRA_USER") + p.Datacenter = os.Getenv("LQ_CASSANDRA_DC") + p.SslMode = model.SslDisable + return openSession(t, p, password("LQ_CASSANDRA_PASSWORD")) +} + +// cassandraKeyspace creates a keyspace of its own, dropped when the test +// ends (also when a check fails). +func cassandraKeyspace(t *testing.T, s drivers.Session) string { + t.Helper() + keyspace := uniqueName("lq_xfer_ks_") + mustRun(t, s, "CREATE KEYSPACE "+keyspace+ + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}") + t.Cleanup(func() { + _, _ = s.Execute(bg, model.ExecRequest{SQL: "DROP KEYSPACE IF EXISTS " + keyspace}) + }) + return keyspace +} + +func TestCassandraExportImportRoundTrip(t *testing.T) { + s := cassandraSession(t) + checkRoundTrip(t, s, cassandraKeyspace(t, s)) +} + +func postgresSession(t *testing.T) drivers.Session { + t.Helper() + p := serverProfile(t, model.Postgres, "LQ_PG_HOST") + p.Port = port("LQ_PG_PORT", 5432) + p.User = env("LQ_PG_USER", "postgres") + p.Database = env("LQ_PG_DB", "postgres") + p.SslMode = model.SslPrefer + return openSession(t, p, password("LQ_PG_PASSWORD")) +} + +// A cancelled import rolls back on a real server, and the session goes on. +func TestPostgresImportStopsWhenCancelled(t *testing.T) { + s := postgresSession(t) + table := uniqueName("lq_xfer_cancel_") + target := qualified(s.Engine(), "public", table) + mustRun(t, s, "CREATE TABLE "+target+" (id integer PRIMARY KEY)") + t.Cleanup(func() { _, _ = s.Execute(bg, model.ExecRequest{SQL: "DROP TABLE " + target}) }) + var content strings.Builder + content.WriteString("id\n") + for i := range 1000 { + content.WriteString(strconv.Itoa(i+1) + "\n") + } + path := filepath.Join(t.TempDir(), "ids.csv") + if err := os.WriteFile(path, []byte(content.String()), 0o644); err != nil { + t.Fatal(err) + } + var jobs Jobs + ctx := jobs.Start(bg, "job", s) + defer jobs.Finish("job") + _, err := Import(ctx, s, ImportRequest{JobID: "job", Path: path, Schema: "public", Table: table}, func(p Progress) { + if p.Rows == 200 { + jobs.Cancel("job") + } + }) + if e := apperr.From(err); e == nil || e.Kind != apperr.Cancelled { + t.Fatalf("%v", err) + } + if got := texts(mustRun(t, s, "SELECT count(*) FROM "+target)); got[0][0] != "0" { + t.Errorf("%q rows after a cancelled import", got) + } + if st := s.TxState(); !st.Autocommit || st.InTransaction { + t.Errorf("%+v", st) + } +} diff --git a/internal/transfer/sql.go b/internal/transfer/sql.go new file mode 100644 index 0000000..f7ee61b --- /dev/null +++ b/internal/transfer/sql.go @@ -0,0 +1,526 @@ +package transfer + +// SQL text for exports and imports: identifiers, value literals and INSERT +// statements in each database's syntax. Values arrive as the drivers format +// them, and every literal reads back as the same value in the same database. +// +// CQL (Cassandra) literals depend on the column's type, not only its kind (a +// uuid is bare, text is quoted, both are KindText), so they come from +// literalTyped, which reads the type (see cqlLiteral). + +import ( + "io" + "strings" + "unicode" + "unicode/utf8" + + "github.com/LowBloat/LowQuery/internal/model" +) + +func isMySQL(e model.Engine) bool { return e == model.MySQL || e == model.MariaDB } + +// ident quotes an identifier always: exports keep names exactly as the +// catalog has them (CQL too: `"` doubled, so case-sensitive names survive). +func ident(e model.Engine, name string) string { + switch { + case isMySQL(e): + return "`" + strings.ReplaceAll(name, "`", "``") + "`" + case e == model.SQLServer: + return "[" + strings.ReplaceAll(name, "]", "]]") + "]" + } + return `"` + strings.ReplaceAll(name, `"`, `""`) + `"` +} + +func qualified(e model.Engine, schema, name string) string { + return ident(e, schema) + "." + ident(e, name) +} + +// text is a plain string literal for catalog queries (names, never user +// data). +func text(e model.Engine, s string) string { + body := strings.ReplaceAll(s, "'", "''") + if e == model.SQLServer { + return "N'" + body + "'" + } + return "'" + body + "'" +} + +// kindOfType is the kind of value a column holds, from its declared type +// (catalog type names: numeric(12,2), VARCHAR2(50), datetime2(3)...). +func kindOfType(typeName string) model.ValueKind { + t := asciiLower(typeName) + has := func(words ...string) bool { + for _, w := range words { + if strings.Contains(t, w) { + return true + } + } + return false + } + switch { + case strings.HasPrefix(t, "interval"): + return model.KindOther + case has("bool") || t == "bit": + return model.KindBool + case has("int", "numeric", "decimal", "number", "float", "double", "real", "money", "serial"): + return model.KindNumber + case has("date", "time", "year"): + return model.KindTemporal + case has("bytea", "blob", "binary", "raw", "image"): + return model.KindBinary + case has("json"): + return model.KindJSON + } + return model.KindText +} + +// kindOfCQLType is the kind of value a column holds, from its CQL type as +// system_schema writes it (int, frozen>, vector...): +// collections, tuples, UDTs and vectors are KindOther. +func kindOfCQLType(typeName string) model.ValueKind { + switch cqlNativeType(typeName) { + case "tinyint", "smallint", "int", "bigint", "varint", "decimal", "float", "double", "counter": + return model.KindNumber + case "boolean": + return model.KindBool + case "timestamp", "date", "time", "duration": + return model.KindTemporal + case "blob": + return model.KindBinary + case "text", "varchar", "ascii", "uuid", "timeuuid", "inet": + return model.KindText + } + return model.KindOther +} + +// columnKind is the kind of a column of engine e from its declared type. +func columnKind(e model.Engine, typeName string) model.ValueKind { + if e == model.Cassandra { + return kindOfCQLType(typeName) + } + return kindOfType(typeName) +} + +// cqlNativeType lowercases a CQL type name and strips frozen<...> wrappers; +// what is left is a native type name (int) or a collection, tuple, vector or +// UDT. +func cqlNativeType(typeName string) string { + t := asciiLower(strings.TrimSpace(typeName)) + for strings.HasPrefix(t, "frozen<") && strings.HasSuffix(t, ">") { + t = strings.TrimSpace(t[len("frozen<") : len(t)-1]) + } + return t +} + +func asciiLower(s string) string { + b := []byte(s) + for i, c := range b { + if c >= 'A' && c <= 'Z' { + b[i] = c + 32 + } + } + return string(b) +} + +func allDigits(s string) bool { + for i := 0; i < len(s); i++ { + if s[i] < '0' || s[i] > '9' { + return false + } + } + return true +} + +func stripSign(v string) string { + if v != "" && (v[0] == '-' || v[0] == '+') { + return v[1:] + } + return v +} + +// isNumber reports whether v is a plain decimal number (optional sign, +// digits with at most one point, optional exponent). +func isNumber(v string) bool { + v = stripSign(v) + mantissa, exponent, hasExp := v, "", false + if i := strings.IndexAny(v, "eE"); i >= 0 { + mantissa, exponent, hasExp = v[:i], v[i+1:], true + } + digits := strings.Replace(mantissa, ".", "", 1) + if digits == "" || !allDigits(digits) || strings.Count(mantissa, ".") > 1 { + return false + } + if hasExp { + e := stripSign(exponent) + return e != "" && allDigits(e) + } + return true +} + +// truth is true, false or neither (ok false), from the words drivers and +// spreadsheets use. +func truth(v string) (value bool, ok bool) { + switch strings.ToLower(strings.TrimSpace(v)) { + case "true", "t", "1", "yes", "y", "sim", "s", "verdadeiro", "v": + return true, true + case "false", "f", "0", "no", "n", "não", "nao", "falso": + return false, true + } + return false, false +} + +func isHex(c byte) bool { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') +} + +// hexDigits returns the hex digits of a binary value in any of the drivers' +// formats: \x... (PostgreSQL), 0x... (MySQL, SQL Server), X'...' (SQLite) or +// bare hex (Oracle). +func hexDigits(v string) (string, bool) { + v = strings.TrimSpace(v) + digits := v + switch { + case strings.HasPrefix(v, `\x`): + digits = v[2:] + case strings.HasPrefix(v, "0x") || strings.HasPrefix(v, "0X"): + digits = v[2:] + case (strings.HasPrefix(v, "X'") || strings.HasPrefix(v, "x'")) && strings.HasSuffix(v, "'") && len(v) >= 3: + digits = v[2 : len(v)-1] + } + if len(digits)%2 != 0 { + return "", false + } + for i := 0; i < len(digits); i++ { + if !isHex(digits[i]) { + return "", false + } + } + return digits, true +} + +func stringLiteral(e model.Engine, v string) string { + switch { + case isMySQL(e): + // Backslash is an escape character in MySQL's default mode, as in + // mysqldump output. + return "'" + strings.ReplaceAll(strings.ReplaceAll(v, `\`, `\\`), "'", "''") + "'" + case e == model.SQLServer: + return "N'" + strings.ReplaceAll(v, "'", "''") + "'" + case e == model.Oracle && utf8.RuneCountInString(v) > 1000: + // A literal holds at most 4000 bytes: longer text is built from CLOB + // pieces. + runes := []rune(v) + var parts []string + for i := 0; i < len(runes); i += 1000 { + end := min(i+1000, len(runes)) + parts = append(parts, "TO_CLOB('"+strings.ReplaceAll(string(runes[i:end]), "'", "''")+"')") + } + return strings.Join(parts, " || ") + } + return "'" + strings.ReplaceAll(v, "'", "''") + "'" +} + +// literal writes a value as a literal of engine e, for a column of kind. +// CQL columns should go through literalTyped; here a CQL value is written as +// the plain CQL type of its kind (Other cannot be told apart: it is quoted). +func literal(e model.Engine, kind model.ValueKind, value *string) string { + if e == model.Cassandra { + ty := "text" + switch kind { + case model.KindNumber: + ty = "decimal" + case model.KindBool: + ty = "boolean" + case model.KindBinary: + ty = "blob" + case model.KindTemporal: + ty = "timestamp" + } + return literalTyped(e, kind, ty, value) + } + if value == nil { + return "NULL" + } + v := *value + switch kind { + case model.KindNumber: + if t := strings.TrimSpace(v); isNumber(t) { + return t + } + case model.KindBool: + if b, ok := truth(v); ok { + if e == model.Postgres || e == model.Oracle { + if b { + return "TRUE" + } + return "FALSE" + } + if b { + return "1" + } + return "0" + } + case model.KindBinary: + if h, ok := hexDigits(v); ok { + switch e { + case model.Postgres: + return "decode('" + h + "', 'hex')" + case model.SQLServer: + return "0x" + h + case model.Oracle: + return "HEXTORAW('" + h + "')" + } + return "X'" + h + "'" + } + case model.KindTemporal: + if e == model.Oracle { + t := strings.TrimSpace(v) + dashed := len(t) > 4 && t[4] == '-' + switch { + case len(t) == 10 && dashed: + return "DATE '" + t + "'" + case len(t) >= 19 && dashed: + return "TIMESTAMP '" + t + "'" + } + return stringLiteral(e, t) + } + } + return stringLiteral(e, v) +} + +// literalTyped writes a value as a literal of engine e, for a column of kind +// and declared type typeName (DbColumn.TypeName, the same text as +// ColumnInfo.TypeName). Only CQL reads the type: numbers, booleans, uuids, +// blobs and durations are bare, text and temporal values quoted, and +// collections, tuples, UDTs and vectors (whose cell text is already a CQL +// literal) are kept as they are. +func literalTyped(e model.Engine, kind model.ValueKind, typeName string, value *string) string { + if e == model.Cassandra { + return cqlLiteral(typeName, value) + } + return literal(e, kind, value) +} + +// insertTarget is where rows go: the table and the columns written, with +// their kinds. +type insertTarget struct { + engine model.Engine + // Qualified, quoted table name. + table string + // Quoted column names. + columns []string + kinds []model.ValueKind + // Declared types of the columns, as DbColumn.TypeName. Only CQL reads + // them; other engines may pass nil. + types []string + // Whether each column is part of the primary key. Only CQL reads it (to + // address counter updates); may be nil. + keys []bool +} + +func (t *insertTarget) typeAt(i int) string { + if i < len(t.types) { + return t.types[i] + } + return "" +} + +func (t *insertTarget) keyAt(i int) bool { return i < len(t.keys) && t.keys[i] } + +// rowsPerInsert is the number of rows per INSERT where the engine takes +// several (SQL Server allows 1000). +const rowsPerInsert = 100 + +// writeInserts writes the INSERT statements for rows, each ending in `;` and +// a new line. +func writeInserts(w io.Writer, t *insertTarget, rows []model.Row) error { + for _, stmt := range insertStatements(t, rows) { + if _, err := io.WriteString(w, stmt+";\n"); err != nil { + return err + } + } + return nil +} + +// insertStatements returns the INSERT statements for rows, without +// terminators. Several rows share a statement except in Oracle and CQL; +// PostgreSQL inserts override identity columns that only accept generated +// values. +func insertStatements(t *insertTarget, rows []model.Row) []string { + head := "INSERT INTO " + t.table + " (" + strings.Join(t.columns, ", ") + ")" + if t.engine == model.Postgres { + head += " OVERRIDING SYSTEM VALUE" + } + if t.engine == model.Cassandra { + for i := range t.columns { + if isCounter(t.typeAt(i)) { + return counterUpdates(t, rows) + } + } + } + tuple := func(row model.Row) string { + n := min(len(row), len(t.kinds)) + values := make([]string, n) + for i := range n { + values[i] = literalTyped(t.engine, t.kinds[i], t.typeAt(i), row[i]) + } + return "(" + strings.Join(values, ", ") + ")" + } + // CQL has no multi-row INSERT. + per := rowsPerInsert + if t.engine == model.Oracle || t.engine == model.Cassandra { + per = 1 + } + var out []string + for start := 0; start < len(rows); start += per { + chunk := rows[start:min(start+per, len(rows))] + values := make([]string, len(chunk)) + for i, row := range chunk { + values[i] = tuple(row) + } + if len(values) == 1 { + out = append(out, head+" VALUES "+values[0]) + } else { + out = append(out, head+" VALUES\n"+strings.Join(values, ",\n")) + } + } + return out +} + +func isCounter(typeName string) bool { return cqlNativeType(typeName) == "counter" } + +// counterUpdates writes the rows of a CQL table with counter columns. +// Counters cannot be INSERTed, so each row becomes +// `UPDATE t SET c = c + n WHERE key = ...`: loaded into an empty table (a +// fresh export script, or an import that deleted the rows) the counters hold +// the exported values, and on a table that has rows the values are added to +// them. A row without a counter value has nothing to add and is left out. +// With no key columns known no UPDATE can address the row, so INSERTs are +// written and the server refuses them with its message. +func counterUpdates(t *insertTarget, rows []model.Row) []string { + n := len(t.columns) + lit := func(row model.Row, i int) string { + kind := model.KindOther + if i < len(t.kinds) { + kind = t.kinds[i] + } + var v *string + if i < len(row) { + v = row[i] + } + return literalTyped(t.engine, kind, t.typeAt(i), v) + } + anyKey := false + for i := range n { + anyKey = anyKey || t.keyAt(i) + } + var out []string + if !anyKey { + head := "INSERT INTO " + t.table + " (" + strings.Join(t.columns, ", ") + ")" + for _, row := range rows { + values := make([]string, n) + for i := range n { + values[i] = lit(row, i) + } + out = append(out, head+" VALUES ("+strings.Join(values, ", ")+")") + } + return out + } + for _, row := range rows { + var sets []string + for i := range n { + if !isCounter(t.typeAt(i)) || i >= len(row) || row[i] == nil { + continue + } + c, v := t.columns[i], lit(row, i) + if abs, ok := strings.CutPrefix(v, "-"); ok { + sets = append(sets, c+" = "+c+" - "+abs) + } else { + sets = append(sets, c+" = "+c+" + "+v) + } + } + if len(sets) == 0 { + continue + } + var wheres []string + for i := range n { + if t.keyAt(i) { + wheres = append(wheres, t.columns[i]+" = "+lit(row, i)) + } + } + out = append(out, "UPDATE "+t.table+" SET "+strings.Join(sets, ", ")+" WHERE "+strings.Join(wheres, " AND ")) + } + return out +} + +// 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. +// +// This is the Cassandra driver's cqlLiteral (internal/drivers/cassandra, +// values.go), which that package does not export; keep the two in step. +func cqlLiteral(typeName string, value *string) string { + if value == nil { + return "null" + } + v := *value + trimmed := strings.TrimSpace(v) + ok := false + switch cqlNativeType(typeName) { + case "tinyint", "smallint", "int", "bigint", "varint", "decimal", "float", "double", "counter": + ok = trimmed == "NaN" || trimmed == "Infinity" || trimmed == "-Infinity" || isNumber(trimmed) + case "boolean": + if b := asciiLower(trimmed); b == "true" || b == "false" { + return b + } + case "uuid", "timeuuid": + ok = isUUID(trimmed) + case "blob": + ok = isCQLBlob(trimmed) + case "duration": + ok = trimmed != "" && strings.IndexFunc(trimmed, unicode.IsSpace) < 0 + case "text", "varchar", "ascii", "inet", "timestamp", "date", "time": + return quoteCQL(v) + default: + // Collections, tuples, vectors and UDTs. + return v + } + if ok { + return trimmed + } + return quoteCQL(v) +} + +func quoteCQL(s string) string { return "'" + strings.ReplaceAll(s, "'", "''") + "'" } + +func isUUID(v string) bool { + if len(v) != 36 { + return false + } + for i := 0; i < len(v); i++ { + c := v[i] + if i == 8 || i == 13 || i == 18 || i == 23 { + if c != '-' { + return false + } + } else if !isHex(c) { + return false + } + } + return true +} + +func isCQLBlob(v string) bool { + h, ok := strings.CutPrefix(v, "0x") + if !ok || len(h)%2 != 0 { + return false + } + for i := 0; i < len(h); i++ { + if !isHex(h[i]) { + return false + } + } + return true +} diff --git a/internal/transfer/sql_test.go b/internal/transfer/sql_test.go new file mode 100644 index 0000000..67ae899 --- /dev/null +++ b/internal/transfer/sql_test.go @@ -0,0 +1,332 @@ +package transfer + +import ( + "reflect" + "strings" + "testing" + + "github.com/LowBloat/LowQuery/internal/model" +) + +func sp(v string) *string { return &v } + +func TestNumbersStayBareOnlyWhenNumeric(t *testing.T) { + for _, v := range []string{"12", "-0.5", ".5", "1.5e-10"} { + if !isNumber(v) { + t.Errorf("%q should be a number", v) + } + } + for _, v := range []string{"NaN", "1.2.3", "$12.00"} { + if isNumber(v) { + t.Errorf("%q should not be a number", v) + } + } + if got := literal(model.Postgres, model.KindNumber, sp("12.50")); got != "12.50" { + t.Error(got) + } + if got := literal(model.Postgres, model.KindNumber, sp("NaN")); got != "'NaN'" { + t.Error(got) + } +} + +func TestStringsEscapePerEngine(t *testing.T) { + v := sp(`it's a \ path`) + cases := []struct { + e model.Engine + want string + }{ + {model.Postgres, `'it''s a \ path'`}, + {model.MySQL, `'it''s a \\ path'`}, + {model.SQLServer, `N'it''s a \ path'`}, + } + for _, c := range cases { + if got := literal(c.e, model.KindText, v); got != c.want { + t.Errorf("%s: %s", c.e, got) + } + } + if got := literal(model.Oracle, model.KindText, nil); got != "NULL" { + t.Error(got) + } + lit := literal(model.Oracle, model.KindText, sp(strings.Repeat("a", 2500))) + if n := strings.Count(lit, "TO_CLOB("); n != 3 { + t.Errorf("%d pieces", n) + } + // Pieces are cut by characters, not bytes. + lit = literal(model.Oracle, model.KindText, sp(strings.Repeat("ã", 1001))) + if lit != "TO_CLOB('"+strings.Repeat("ã", 1000)+"') || TO_CLOB('ã')" { + t.Error("multibyte pieces") + } +} + +func TestBinaryAndBooleans(t *testing.T) { + cases := []struct { + e model.Engine + kind model.ValueKind + v string + want string + }{ + {model.Postgres, model.KindBinary, `\xdeadbeef`, "decode('deadbeef', 'hex')"}, + {model.SQLServer, model.KindBinary, "0x00FF", "0x00FF"}, + {model.MySQL, model.KindBinary, "0x", "X''"}, + {model.SQLite, model.KindBinary, "X'0A'", "X'0A'"}, + {model.Oracle, model.KindBinary, "DEADBEEF", "HEXTORAW('DEADBEEF')"}, + {model.Postgres, model.KindBool, "true", "TRUE"}, + {model.SQLServer, model.KindBool, "false", "0"}, + {model.MySQL, model.KindBool, "Sim", "1"}, + } + for _, c := range cases { + if got := literal(c.e, c.kind, sp(c.v)); got != c.want { + t.Errorf("%s %s %q: %s, want %s", c.e, c.kind, c.v, got, c.want) + } + } +} + +func TestOracleDatesUseTypedLiterals(t *testing.T) { + if got := literal(model.Oracle, model.KindTemporal, sp("2024-02-29")); got != "DATE '2024-02-29'" { + t.Error(got) + } + if got := literal(model.Oracle, model.KindTemporal, sp("2024-02-29 13:45:10.250 -03:00")); got != "TIMESTAMP '2024-02-29 13:45:10.250 -03:00'" { + t.Error(got) + } + if got := literal(model.Postgres, model.KindTemporal, sp("infinity")); got != "'infinity'" { + t.Error(got) + } +} + +func TestTypesMapToKinds(t *testing.T) { + cases := map[string]model.ValueKind{ + "numeric(12,2)": model.KindNumber, + "BINARY_DOUBLE": model.KindNumber, + "interval": model.KindOther, + "timestamp with time zone": model.KindTemporal, + "varbinary(max)": model.KindBinary, + "LONG RAW": model.KindBinary, + "bit": model.KindBool, + "character varying(50)": model.KindText, + "jsonb": model.KindJSON, + } + for ty, want := range cases { + if got := kindOfType(ty); got != want { + t.Errorf("%s: %s, want %s", ty, got, want) + } + } +} + +func TestInsertsGroupRowsExceptInOracle(t *testing.T) { + rows := []model.Row{{sp("1"), sp("x")}, {sp("2"), nil}} + tg := &insertTarget{ + engine: model.Postgres, + table: `"s"."t"`, + columns: []string{`"a"`, `"b"`}, + kinds: []model.ValueKind{model.KindNumber, model.KindText}, + } + want := []string{"INSERT INTO \"s\".\"t\" (\"a\", \"b\") OVERRIDING SYSTEM VALUE VALUES\n(1, 'x'),\n(2, NULL)"} + if got := insertStatements(tg, rows); !reflect.DeepEqual(got, want) { + t.Errorf("%q", got) + } + tg.engine = model.Oracle + if got := insertStatements(tg, rows); len(got) != 2 { + t.Errorf("%q", got) + } + // More rows than fit in one statement. + many := make([]model.Row, rowsPerInsert+1) + for i := range many { + many[i] = model.Row{sp("1"), nil} + } + tg.engine = model.SQLServer + if got := insertStatements(tg, many); len(got) != 2 || strings.Count(got[0], "\n") != rowsPerInsert { + t.Errorf("%d statements", len(got)) + } +} + +func cql(kind model.ValueKind, ty, v string) string { + return literalTyped(model.Cassandra, kind, ty, &v) +} + +func TestCQLIdentifiersAndText(t *testing.T) { + if got := ident(model.Cassandra, `My"Tbl`); got != `"My""Tbl"` { + t.Error(got) + } + if got := qualified(model.Cassandra, "ks", "t"); got != `"ks"."t"` { + t.Error(got) + } + if got := text(model.Cassandra, "it's"); got != "'it''s'" { + t.Error(got) + } +} + +func TestCQLNumbersAndBooleansAreBare(t *testing.T) { + n, b := model.KindNumber, model.KindBool + cases := []struct { + kind model.ValueKind + ty, v, w string + }{ + {n, "int", "42", "42"}, + {n, "varint", "-123456789012345678901234567890", "-123456789012345678901234567890"}, + {n, "decimal", "1234567890.0987654321", "1234567890.0987654321"}, + {n, "double", "1.5e-10", "1.5e-10"}, + {n, "double", "NaN", "NaN"}, + {n, "float", "-Infinity", "-Infinity"}, + {n, "counter", "7", "7"}, + {b, "boolean", "true", "true"}, + {b, "boolean", "false", "false"}, + } + for _, c := range cases { + if got := cql(c.kind, c.ty, c.v); got != c.w { + t.Errorf("%s %q: %s", c.ty, c.v, got) + } + } + if got := literalTyped(model.Cassandra, model.KindText, "text", nil); got != "null" { + t.Error(got) + } +} + +func TestCQLUUIDsBlobsAndDurationsAreBare(t *testing.T) { + id := "123e4567-e89b-12d3-a456-426614174000" + cases := []struct { + kind model.ValueKind + ty, v, w string + }{ + {model.KindText, "uuid", id, id}, + {model.KindText, "timeuuid", id, id}, + // Same kind, but a text column: quoted. + {model.KindText, "text", id, "'" + id + "'"}, + {model.KindBinary, "blob", "0xDEADBEEF", "0xDEADBEEF"}, + {model.KindBinary, "blob", "0x", "0x"}, + {model.KindTemporal, "duration", "1y2mo3d4h5m6s7ms8us9ns", "1y2mo3d4h5m6s7ms8us9ns"}, + } + for _, c := range cases { + if got := cql(c.kind, c.ty, c.v); got != c.w { + t.Errorf("%s %q: %s", c.ty, c.v, got) + } + } +} + +func TestCQLTextAndTemporalAreQuoted(t *testing.T) { + cases := []struct { + kind model.ValueKind + ty, v, w string + }{ + {model.KindText, "text", "it's \\ a \"x\"\nline", "'it''s \\ a \"x\"\nline'"}, + {model.KindText, "ascii", "abc", "'abc'"}, + {model.KindText, "varchar", "Ação ☃", "'Ação ☃'"}, + {model.KindText, "inet", "10.0.0.1", "'10.0.0.1'"}, + {model.KindTemporal, "timestamp", "2024-05-06 07:08:09.123+0000", "'2024-05-06 07:08:09.123+0000'"}, + {model.KindTemporal, "date", "2024-05-06", "'2024-05-06'"}, + {model.KindTemporal, "time", "07:08:09.123456789", "'07:08:09.123456789'"}, + } + for _, c := range cases { + if got := cql(c.kind, c.ty, c.v); got != c.w { + t.Errorf("%s %q: %s", c.ty, c.v, got) + } + } + // Without a type the kind decides. + if got := literal(model.Cassandra, model.KindText, sp("a'b")); got != "'a''b'" { + t.Error(got) + } + if got := literal(model.Cassandra, model.KindNumber, sp("5")); got != "5" { + t.Error(got) + } + if got := literal(model.Cassandra, model.KindBool, sp("true")); got != "true" { + t.Error(got) + } + if got := literal(model.Cassandra, model.KindTemporal, nil); got != "null" { + t.Error(got) + } +} + +func TestCQLCollectionsTuplesUDTsAndVectorsAreVerbatim(t *testing.T) { + for _, c := range [][2]string{ + {"list", "[1, 2]"}, + {"set", "{'a', 'it''s ; here'}"}, + {"map", "{'a': 1, 'b': 2}"}, + {"frozen>>>", "{'a': [1], 'b': []}"}, + {"tuple", "(1, 'x')"}, + {"frozen
", "{street: 'Main', zip: 12345}"}, + {"vector", "[0.1, 0.2, 0.3]"}, + } { + if got := cql(model.KindOther, c[0], c[1]); got != c[1] { + t.Errorf("%s: %s", c[0], got) + } + } +} + +func TestCQLTypesMapToKinds(t *testing.T) { + cases := map[string]model.ValueKind{ + "int": model.KindNumber, + "varint": model.KindNumber, + "counter": model.KindNumber, + "boolean": model.KindBool, + "timestamp": model.KindTemporal, + "duration": model.KindTemporal, + "blob": model.KindBinary, + "uuid": model.KindText, + "inet": model.KindText, + "list": model.KindOther, + "frozen>": model.KindOther, + "tuple": model.KindOther, + "vector": model.KindOther, + "frozen
": model.KindOther, + } + for ty, want := range cases { + if got := kindOfCQLType(ty); got != want { + t.Errorf("%s: %s, want %s", ty, got, want) + } + } + if got := columnKind(model.Cassandra, "list"); got != model.KindOther { + t.Error(got) + } + if got := columnKind(model.Postgres, "integer"); got != model.KindNumber { + t.Error(got) + } +} + +func TestCQLInsertsAreOneRowEach(t *testing.T) { + tg := &insertTarget{ + engine: model.Cassandra, + table: `"ks"."t"`, + columns: []string{`"id"`, `"name"`, `"tags"`}, + kinds: []model.ValueKind{model.KindText, model.KindText, model.KindOther}, + types: []string{"uuid", "text", "set"}, + keys: []bool{true, false, false}, + } + rows := []model.Row{ + {sp("123e4567-e89b-12d3-a456-426614174000"), sp("it's"), sp("{'a', 'b'}")}, + {sp("123e4567-e89b-12d3-a456-426614174001"), nil, nil}, + } + want := []string{ + `INSERT INTO "ks"."t" ("id", "name", "tags") VALUES (123e4567-e89b-12d3-a456-426614174000, 'it''s', {'a', 'b'})`, + `INSERT INTO "ks"."t" ("id", "name", "tags") VALUES (123e4567-e89b-12d3-a456-426614174001, null, null)`, + } + if got := insertStatements(tg, rows); !reflect.DeepEqual(got, want) { + t.Errorf("%q", got) + } +} + +func TestCQLCounterTablesAreWrittenAsUpdates(t *testing.T) { + tg := &insertTarget{ + engine: model.Cassandra, + table: `"ks"."c"`, + columns: []string{`"id"`, `"seq"`, `"hits"`, `"misses"`}, + kinds: []model.ValueKind{model.KindText, model.KindNumber, model.KindNumber, model.KindNumber}, + types: []string{"text", "int", "counter", "counter"}, + keys: []bool{true, true, false, false}, + } + rows := []model.Row{ + {sp("a'b"), sp("1"), sp("5"), sp("-2")}, + {sp("c"), sp("2"), sp("9"), nil}, + {sp("d"), sp("3"), nil, nil}, + } + want := []string{ + `UPDATE "ks"."c" SET "hits" = "hits" + 5, "misses" = "misses" - 2 WHERE "id" = 'a''b' AND "seq" = 1`, + `UPDATE "ks"."c" SET "hits" = "hits" + 9 WHERE "id" = 'c' AND "seq" = 2`, + } + if got := insertStatements(tg, rows); !reflect.DeepEqual(got, want) { + t.Errorf("%q", got) + } + // With no key known, INSERTs (the server refuses them with its message). + tg.keys = nil + if got := insertStatements(tg, rows[:1]); len(got) != 1 || !strings.HasPrefix(got[0], "INSERT INTO") { + t.Errorf("%q", got) + } +} diff --git a/internal/transfer/transfer.go b/internal/transfer/transfer.go new file mode 100644 index 0000000..a4b1a71 --- /dev/null +++ b/internal/transfer/transfer.go @@ -0,0 +1,150 @@ +// Package transfer moves data in and out: exports to SQL, CSV and JSON, +// imports from CSV and JSON. Jobs run on a session of their own (the +// interface opens one per job), report progress as `transfer-progress` +// events and stop when cancelled. +package transfer + +import ( + "context" + "errors" + "io/fs" + "os" + "sync" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" +) + +// ProgressEvent is the name of the event Progress is sent as. +const ProgressEvent = "transfer-progress" + +// Progress is the payload of the `transfer-progress` event. +type Progress struct { + // The job the report belongs to (ExportRequest.JobID, ImportRequest.JobID). + JobID string `json:"jobId"` + // The table or object being written or read. + Object string `json:"object"` + // 1-based position of the object, and how many there are. + Step int `json:"step"` + Steps int `json:"steps"` + // Rows of the current object so far. + Rows uint64 `json:"rows"` +} + +// reporter turns a job's report function into one that fills in the job id +// and tolerates a nil report. +func reporter(jobID string, report func(Progress)) func(object string, step, steps int, rows uint64) { + return func(object string, step, steps int, rows uint64) { + if report != nil { + report(Progress{JobID: jobID, Object: object, Step: step, Steps: steps, Rows: rows}) + } + } +} + +// Jobs are the running exports and imports: what cancels each one and the +// session it runs on. +type Jobs struct { + mu sync.Mutex + jobs map[string]*job +} + +type job struct { + cancel context.CancelFunc + session drivers.Session +} + +// Start registers a job running on s. The returned context is cancelled by +// Cancel (or when parent is); pass it to Export or Import. Call Finish when +// the job ends. +func (j *Jobs) Start(parent context.Context, id string, s drivers.Session) context.Context { + ctx, cancel := context.WithCancel(parent) + j.mu.Lock() + defer j.mu.Unlock() + if j.jobs == nil { + j.jobs = map[string]*job{} + } + if old, ok := j.jobs[id]; ok { + old.cancel() + } + j.jobs[id] = &job{cancel: cancel, session: s} + return ctx +} + +// Finish forgets a job and releases its context. +func (j *Jobs) Finish(id string) { + j.mu.Lock() + defer j.mu.Unlock() + if jb, ok := j.jobs[id]; ok { + jb.cancel() + delete(j.jobs, id) + } +} + +// Cancel stops a job: its context is cancelled, so the job stops at the next +// batch. It returns the job's session, so the statement running on the +// server can be cancelled too (Session.Cancel); false when no such job runs. +func (j *Jobs) Cancel(id string) (drivers.Session, bool) { + j.mu.Lock() + defer j.mu.Unlock() + jb, ok := j.jobs[id] + if !ok { + return nil, false + } + jb.cancel() + return jb.session, true +} + +// ioError reports a file error as the Rust version did: an internal error +// with the system's message (without Go's "open :" prefix). +func ioError(err error) error { + if err == nil { + return nil + } + var pe *fs.PathError + if errors.As(err, &pe) { + return apperr.New(apperr.Internal, pe.Err.Error()) + } + var le *os.LinkError + if errors.As(err, &le) { + return apperr.New(apperr.Internal, le.Err.Error()) + } + return apperr.New(apperr.Internal, err.Error()) +} + +// cancelledIf returns the cancelled error when ctx is done, else err: a +// statement interrupted by a cancel reports the cancel, not the driver's +// message about it. +func cancelledIf(ctx context.Context, err error) error { + if err != nil && ctx.Err() != nil { + return apperr.CancelledErr() + } + return err +} + +// rustLines splits text as Rust's str::lines does: at \n, dropping a \r +// before it, with no empty last line for a trailing newline. A \r at the +// very end (no \n after it) stays. +func rustLines(text string) []string { + if text == "" { + return nil + } + var out []string + start := 0 + for i := 0; i < len(text); i++ { + if text[i] == '\n' { + out = append(out, trimCR(text[start:i])) + start = i + 1 + } + } + if start < len(text) { + out = append(out, text[start:]) + } + return out +} + +func trimCR(s string) string { + if n := len(s); n > 0 && s[n-1] == '\r' { + return s[:n-1] + } + return s +} From b7fc47fc781a16df7ad3f083cd82870e1ba2f0be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A1bio=20Henrique=20Ara=C3=BAjo?= Date: Fri, 4 Dec 2026 12:17:25 -0300 Subject: [PATCH 4/8] refactor(go): transfer uses the Cassandra driver's CQL literals instead of a copy --- internal/drivers/cassandra/cassandra_test.go | 4 +- internal/drivers/cassandra/edit.go | 6 +- internal/drivers/cassandra/values.go | 4 +- internal/transfer/sql.go | 78 +------------------- 4 files changed, 10 insertions(+), 82 deletions(-) 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/transfer/sql.go b/internal/transfer/sql.go index f7ee61b..5c33701 100644 --- a/internal/transfer/sql.go +++ b/internal/transfer/sql.go @@ -6,14 +6,14 @@ package transfer // // CQL (Cassandra) literals depend on the column's type, not only its kind (a // uuid is bare, text is quoted, both are KindText), so they come from -// literalTyped, which reads the type (see cqlLiteral). +// literalTyped, which reads the type (see cassandra.CQLLiteral). import ( "io" "strings" - "unicode" "unicode/utf8" + "github.com/LowBloat/LowQuery/internal/drivers/cassandra" "github.com/LowBloat/LowQuery/internal/model" ) @@ -296,7 +296,7 @@ func literal(e model.Engine, kind model.ValueKind, value *string) string { // literal) are kept as they are. func literalTyped(e model.Engine, kind model.ValueKind, typeName string, value *string) string { if e == model.Cassandra { - return cqlLiteral(typeName, value) + return cassandra.CQLLiteral(typeName, value) } return literal(e, kind, value) } @@ -452,75 +452,3 @@ func counterUpdates(t *insertTarget, rows []model.Row) []string { } return out } - -// 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. -// -// This is the Cassandra driver's cqlLiteral (internal/drivers/cassandra, -// values.go), which that package does not export; keep the two in step. -func cqlLiteral(typeName string, value *string) string { - if value == nil { - return "null" - } - v := *value - trimmed := strings.TrimSpace(v) - ok := false - switch cqlNativeType(typeName) { - case "tinyint", "smallint", "int", "bigint", "varint", "decimal", "float", "double", "counter": - ok = trimmed == "NaN" || trimmed == "Infinity" || trimmed == "-Infinity" || isNumber(trimmed) - case "boolean": - if b := asciiLower(trimmed); b == "true" || b == "false" { - return b - } - case "uuid", "timeuuid": - ok = isUUID(trimmed) - case "blob": - ok = isCQLBlob(trimmed) - case "duration": - ok = trimmed != "" && strings.IndexFunc(trimmed, unicode.IsSpace) < 0 - case "text", "varchar", "ascii", "inet", "timestamp", "date", "time": - return quoteCQL(v) - default: - // Collections, tuples, vectors and UDTs. - return v - } - if ok { - return trimmed - } - return quoteCQL(v) -} - -func quoteCQL(s string) string { return "'" + strings.ReplaceAll(s, "'", "''") + "'" } - -func isUUID(v string) bool { - if len(v) != 36 { - return false - } - for i := 0; i < len(v); i++ { - c := v[i] - if i == 8 || i == 13 || i == 18 || i == 23 { - if c != '-' { - return false - } - } else if !isHex(c) { - return false - } - } - return true -} - -func isCQLBlob(v string) bool { - h, ok := strings.CutPrefix(v, "0x") - if !ok || len(h)%2 != 0 { - return false - } - for i := 0; i < len(h); i++ { - if !isHex(h[i]) { - return false - } - } - return true -} From 93b1b597c8bdd825af5ab38b18734ca9cc89cc3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A1bio=20Henrique=20Ara=C3=BAjo?= Date: Fri, 4 Dec 2026 12:19:01 -0300 Subject: [PATCH 5/8] feat(go): connection importers (DBeaver, DataGrip, pgAdmin, SQL Developer) and AI client setup --- internal/aisetup/aisetup.go | 386 ++++++ internal/aisetup/aisetup_test.go | 212 ++++ internal/app/commands.go | 1 + internal/app/integrations.go | 39 + internal/importers/datagrip.go | 948 +++++++++++++++ internal/importers/datagrip_fixtures_test.go | 141 +++ internal/importers/datagrip_test.go | 354 ++++++ internal/importers/dbeaver.go | 1082 +++++++++++++++++ internal/importers/dbeaver_fixtures_test.go | 259 ++++ internal/importers/dbeaver_test.go | 396 ++++++ internal/importers/helpers_test.go | 90 ++ internal/importers/importers.go | 322 +++++ internal/importers/importers_test.go | 125 ++ internal/importers/jdbc.go | 442 +++++++ internal/importers/jdbc_test.go | 143 +++ internal/importers/pgadmin.go | 670 ++++++++++ internal/importers/pgadmin_fixtures_test.go | 94 ++ internal/importers/pgadmin_test.go | 224 ++++ internal/importers/sqldeveloper.go | 378 ++++++ .../importers/sqldeveloper_fixtures_test.go | 50 + internal/importers/sqldeveloper_test.go | 176 +++ internal/importers/text.go | 177 +++ internal/ojson/ojson.go | 214 ++++ internal/ojson/ojson_test.go | 48 + 24 files changed, 6971 insertions(+) create mode 100644 internal/aisetup/aisetup.go create mode 100644 internal/aisetup/aisetup_test.go create mode 100644 internal/app/integrations.go create mode 100644 internal/importers/datagrip.go create mode 100644 internal/importers/datagrip_fixtures_test.go create mode 100644 internal/importers/datagrip_test.go create mode 100644 internal/importers/dbeaver.go create mode 100644 internal/importers/dbeaver_fixtures_test.go create mode 100644 internal/importers/dbeaver_test.go create mode 100644 internal/importers/helpers_test.go create mode 100644 internal/importers/importers.go create mode 100644 internal/importers/importers_test.go create mode 100644 internal/importers/jdbc.go create mode 100644 internal/importers/jdbc_test.go create mode 100644 internal/importers/pgadmin.go create mode 100644 internal/importers/pgadmin_fixtures_test.go create mode 100644 internal/importers/pgadmin_test.go create mode 100644 internal/importers/sqldeveloper.go create mode 100644 internal/importers/sqldeveloper_fixtures_test.go create mode 100644 internal/importers/sqldeveloper_test.go create mode 100644 internal/importers/text.go create mode 100644 internal/ojson/ojson.go create mode 100644 internal/ojson/ojson_test.go 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/commands.go b/internal/app/commands.go index 575faa8..f55a80e 100644 --- a/internal/app/commands.go +++ b/internal/app/commands.go @@ -202,6 +202,7 @@ func (a *App) commands() map[string]handler { }), } a.transferCommands(m) + a.integrationCommands(m) return m } diff --git a/internal/app/integrations.go b/internal/app/integrations.go new file mode 100644 index 0000000..00aad17 --- /dev/null +++ b/internal/app/integrations.go @@ -0,0 +1,39 @@ +package app + +import ( + "context" + + "github.com/LowBloat/LowQuery/internal/aisetup" + "github.com/LowBloat/LowQuery/internal/importers" +) + +// 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) + }) +} 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: "}, + } { + _, err := parseDataGrip(writeFile(t, dir, c[0], c[1])) + if !strings.Contains(errMessage(err), "dataSources.xml") { + t.Fatalf("%s: %v", c[0], err) + } + } + local := writeFile(t, dir, "x/dataSources.local.xml", datagripLocal) + if _, err := parseDataGrip(local); !strings.Contains(errMessage(err), "local settings") { + t.Fatal(err) + } + if _, err := parseDataGrip(filepath.Join(dir, "missing.xml")); err == nil { + t.Fatal("parsed a missing file") + } + // Odd values do not panic. + odd := writeFile(t, dir, "odd.xml", `jdbc:redis:jdbc:mysql:xjdbc:sqlserver://;`) + p, err := parseDataGrip(odd) + if err != nil { + t.Fatal(err) + } + if len(p.skipped) != 2 { + t.Fatalf("%v", p.skipped) + } + deep := writeFile(t, dir, "deep.xml", ``+ + strings.Repeat("", 5000)+strings.Repeat("", 5000)+``) + p, err = parseDataGrip(deep) + if err != nil { + t.Fatal(err) + } + if len(p.candidates) != 0 { + t.Fatal("candidates in a deep file") + } +} + +func TestDataGripRecentProjectsAndLabels(t *testing.T) { + fakeHome(t) + dir := t.TempDir() + file := writeFile(t, dir, "recentProjects.xml", ` + + + + +`) + projects := recentProjects(file, dir) + if len(projects) != 2 || filepath.Clean(projects[0]) != filepath.Join(dir, "work", "erp") || + filepath.Clean(projects[1]) != filepath.Join(dir, "work", "shop") { + t.Fatalf("%q", projects) + } + if got := productLabel("DataGrip2024.1"); got != "DataGrip 2024.1" { + t.Fatal(got) + } + if got := productLabel("IntelliJIdea2026.2"); got != "IntelliJIdea 2026.2" { + t.Fatal(got) + } + var f found + ds := writeFile(t, dir, "work/erp/.idea/dataSources.xml", datagripProject) + f.addProject("DataGrip 2024.1", filepath.Join(dir, "work", "erp")) + f.add("again", ds) + f.addProject("DataGrip 2024.1", filepath.Join(dir, "work", "none")) + if len(f.files) != 1 || f.files[0].label != "DataGrip 2024.1 · erp" { + t.Fatalf("%+v", f.files) + } + + // Default files: the IDE folder under the fake config, its global + // file, and a recent project. + writeFile(t, dirs.config(), "JetBrains/DataGrip2024.1/options/dataSources.xml", "") + writeFile(t, dirs.config(), "JetBrains/DataGrip2024.1/options/recentProjects.xml", + ``) + files := datagripFiles() + var labels []string + for _, s := range files { + labels = append(labels, s.label) + } + if strings.Join(labels, "|") != "DataGrip 2024.1 · Global|DataGrip 2024.1 · erp" { + t.Fatalf("%q", labels) + } +} + +func TestDataGripHelpers(t *testing.T) { + if got, _ := hexColor("#E1F5FE"); got != "#e1f5fe" { + t.Fatal(got) + } + if got, _ := hexColor("f00"); got != "#ff0000" { + t.Fatal(got) + } + if _, ok := hexColor("red"); ok { + t.Fatal("red") + } + if u, r, ok := splitOracleRole("SYS AS SYSDBA"); !ok || u != "SYS" || r != "sysdba" { + t.Fatal(u, r) + } + if u, _, ok := splitOracleRole("as x"); ok || u != "as x" { + t.Fatal(u) + } + if url, dir := splitTnsAdmin("oracle:thin:@db_high?TNS_ADMIN=/w&x=1"); url != "oracle:thin:@db_high?x=1" || dir != "/w" { + t.Fatal(url, dir) + } + x := parseXML(`x < y A]]>`) + if x == nil { + t.Fatal("not parsed") + } + if k, _ := x.attr("k"); k != "1 & 2" { + t.Fatal(k) + } + if x.text != "x < y A" { + t.Fatal(x.text) + } +} diff --git a/internal/importers/dbeaver.go b/internal/importers/dbeaver.go new file mode 100644 index 0000000..beccd22 --- /dev/null +++ b/internal/importers/dbeaver.go @@ -0,0 +1,1082 @@ +package importers + +// DBeaver (Community and PRO). Each project keeps its connections in +// //.dbeaver/data-sources*.json; user names and saved +// passwords live next to it in credentials-config*.json, encrypted with +// DBeaver's built-in key (AES-128-CBC, the first 16 bytes are the IV). +// +// Key names follow DBeaver's DataSourceSerializerModern, RegistryConstants +// and the Oracle, SQL Server, PostgreSQL and MySQL plugin constants. + +import ( + "crypto/aes" + "crypto/cipher" + "encoding/json" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "unicode/utf8" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" + "github.com/LowBloat/LowQuery/internal/ojson" +) + +// credentialsKey is BaseProjectImpl.LOCAL_KEY_CACHE in DBeaver. +var credentialsKey = []byte{ + 0xba, 0xbb, 0x4a, 0x9f, 0x77, 0x4a, 0xb8, 0x53, 0xc9, 0x6c, 0x2d, 0x65, 0x3d, 0xfe, 0x54, 0x4a, +} + +const ( + maxFileBytes = 32 * 1024 * 1024 + red = "#dc2626" + green = "#16a34a" +) + +// Provider properties (DBConstants.INTERNAL_PROP_PREFIX is "@dbeaver-"). +const ( + oraConnectionType = "@dbeaver-connection-type@" + oraSidService = "@dbeaver-sid-service@" + oraTnsPath = "@dbeaver-tns-path@" + oraInternalLogon = "@dbeaver-internal-logon@" + oraLogonAs = "oracle.logon-as" + oraOsAuth = "@dbeaver-os-authentication@" + mssqlWindowsAuth = "@dbeaver-connection-windows-auth@" +) + +// harmlessProperties are driver properties that do not change how LowQuery +// connects. +var harmlessProperties = []string{ + "allowPublicKeyRetrieval", + "ApplicationName", + "applicationName", + "connectTimeout", + "loginTimeout", + "socketTimeout", + "tcpKeepAlive", + "characterEncoding", + "useUnicode", +} + +func dbeaverFiles() []source { + seen := map[string]bool{} + var out []source + for _, r := range dbeaverRoots() { + workspace := filepath.Join(r.path, "workspace6") + if !seen[workspace] { + seen[workspace] = true + out = append(out, workspaceFiles(workspace, r.label)...) + } + } + return out +} + +// dbeaverRoots are the DBeaverData folders: %APPDATA% on Windows, ~/Library +// on macOS, $XDG_DATA_HOME or ~/.local/share on Linux, plus Snap and +// Flatpak. label is the variant shown after "DBeaver". +func dbeaverRoots() []source { + var roots []source + if data := dirs.data(); data != "" { + roots = append(roots, source{"", filepath.Join(data, "DBeaverData")}) + } + if home := dirs.home(); home != "" { + under := func(parts ...string) string { return filepath.Join(append([]string{home}, parts...)...) } + roots = append(roots, + source{"", under("Library", "DBeaverData")}, + source{"", under(".local", "share", "DBeaverData")}, + source{" (Snap)", under("snap", "dbeaver-ce", "current", ".local", "share", "DBeaverData")}, + source{" (Flatpak)", under(".var", "app", "io.dbeaver.DBeaverCommunity", "data", "DBeaverData")}, + ) + } + return roots +} + +// workspaceFiles lists the data-sources*.json files of every project in a +// workspace. +func workspaceFiles(workspace, variant string) []source { + entries, err := os.ReadDir(workspace) + if err != nil { + return nil + } + var projects []string + for _, e := range entries { + name := e.Name() + if strings.HasPrefix(name, ".") || !isDir(filepath.Join(workspace, name)) { + continue + } + projects = append(projects, name) + } + sort.Strings(projects) + var out []source + for _, project := range projects { + dot := filepath.Join(workspace, project, ".dbeaver") + entries, err := os.ReadDir(dot) + if err != nil { + continue + } + var files []string + for _, e := range entries { + name := e.Name() + if isDataSourcesName(name) && isFile(filepath.Join(dot, name)) { + files = append(files, name) + } + } + sort.Strings(files) + several := len(files) > 1 + for _, name := range files { + label := "DBeaver" + variant + " · " + project + if several { + label += " · " + name + } + out = append(out, source{label, filepath.Join(dot, name)}) + } + } + return out +} + +func isDataSourcesName(name string) bool { + return strings.HasPrefix(name, "data-sources") && strings.HasSuffix(name, ".json") +} + +// credentialsPath: data-sources-2.json keeps its credentials in +// credentials-config-2.json (DataSourceFileStorage.configSuffix). +func credentialsPath(path string) (string, bool) { + name := fileName(path) + rest, ok := strings.CutPrefix(name, "data-sources") + if !ok { + return "", false + } + suffix, ok := strings.CutSuffix(rest, ".json") + if !ok { + return "", false + } + return path[:len(path)-len(name)] + "credentials-config" + suffix + ".json", true +} + +func notDBeaver() error { + return apperr.New(apperr.Invalid, "This is not a DBeaver data-sources.json file.") +} + +type credState int + +const ( + credsRead credState = iota + credsMissing + credsUnreadable +) + +func parseDBeaver(path string) (*parsed, error) { + st, err := os.Stat(path) + if err != nil { + return nil, ioError(err) + } + if st.Size() > maxFileBytes { + return nil, notDBeaver() + } + data, err := os.ReadFile(path) + if err != nil { + return nil, ioError(err) + } + text := strings.TrimLeft(lossy(data), bom) + v, err := ojson.Parse([]byte(text)) + if err != nil { + return nil, notDBeaver() + } + root := ojson.Obj(v) + if root == nil || (!root.Has("connections") && !root.Has("folders")) { + return nil, notDBeaver() + } + connections := root.Field("connections") + types := root.Field("connection-types") + + out := newParsed() + var creds *ojson.Object + state := credsMissing + if cp, ok := credentialsPath(path); ok && isFile(cp) { + if creds = readCredentials(cp); creds != nil { + state = credsRead + } else { + state = credsUnreadable + } + } + anySaved := false + for _, id := range connections.Keys() { + if truthy(ojson.Obj(connections.Get(id)).Get("save-password")) { + anySaved = true + } + } + switch { + case state == credsUnreadable && connections.Len() > 0: + out.notes = append(out.notes, "credentials-config.json could not be decrypted (the project may be protected by a "+ + "password), so user names and passwords must be typed on first connect.") + case state == credsMissing && anySaved: + out.notes = append(out.notes, "DBeaver keeps the saved credentials of this project in its secure storage, so "+ + "user names and passwords must be typed on first connect.") + } + + for _, id := range connections.Keys() { + conn := ojson.Obj(connections.Get(id)) + if conn == nil { + out.skip(id, "The connection entry is not readable.") + continue + } + secret := creds.Field(id).Field("#connection") + dbeaverConnection(id, conn, secret, types, out) + } + return out, nil +} + +// readCredentials decrypts credentials-config.json: { id: { "#connection": +// { user, password, auth properties... } } }. Nil when it cannot be read. +func readCredentials(path string) *ojson.Object { + st, err := os.Stat(path) + if err != nil || st.Size() > maxFileBytes { + return nil + } + data, err := os.ReadFile(path) + if err != nil { + return nil + } + plain := decrypt(data) + if plain == nil || !utf8.Valid(plain) { + return nil + } + v, err := ojson.Parse(plain) + if err != nil { + return nil + } + return ojson.Obj(v) +} + +func decrypt(data []byte) []byte { + if len(data) < 32 || len(data)%16 != 0 { + return nil + } + block, err := aes.NewCipher(credentialsKey) + if err != nil { + return nil + } + iv, body := data[:16], data[16:] + buf := make([]byte, len(body)) + cipher.NewCBCDecrypter(block, iv).CryptBlocks(buf, body) + // PKCS#7 padding. + pad := int(buf[len(buf)-1]) + if pad == 0 || pad > 16 || pad > len(buf) { + return nil + } + for _, b := range buf[len(buf)-pad:] { + if int(b) != pad { + return nil + } + } + return buf[:len(buf)-pad] +} + +// text is a JSON scalar as text (DBeaver writes ports and flags as strings, +// older files sometimes as numbers or booleans). +func text(v any) string { + switch t := v.(type) { + case string: + return strings.TrimSpace(t) + case json.Number: + return t.String() + case bool: + if t { + return "true" + } + return "false" + } + return "" +} + +// raw is a string exactly as stored (passwords keep their spaces). +func raw(v any) string { + s, _ := v.(string) + return s +} + +func truthy(v any) bool { + switch t := v.(type) { + case bool: + return t + case string: + return eqFold(strings.TrimSpace(t), "true") + } + return false +} + +func dbeaverConnection(id string, conn, secret, types *ojson.Object, out *parsed) { + name := text(conn.Get("name")) + display := name + if display == "" { + display = id + } + provider := lowerASCII(text(conn.Get("provider"))) + driver := text(conn.Get("driver")) + cfg := conn.Field("configuration") + url := text(cfg.Get("url")) + urlMode := eqFold(text(cfg.Get("configurationType")), "URL") + + engine, reason := dbeaverEngine(provider, driver) + if reason != "" { + out.skip(display, reason) + return + } + if engine == "" { + // Generic or custom driver: the URL tells the database. + probe := model.DefaultProfile() + if urlTarget(url, &probe) != nil { + out.skip(display, product(driver)+" is not supported by LowQuery.") + return + } + engine = probe.Engine + } + + p := model.DefaultProfile() + p.Name = name + p.Engine = engine + p.Port = defaultPort(engine) + p.SavePassword = truthy(conn.Get("save-password")) + warnings := []string{} + + // User: the credentials file first, then a plain "user" (DBeaver #6564). + user := text(secret.Get("user")) + if user == "" { + user = text(cfg.Get("user")) + } + password := raw(secret.Get("password")) + if password == "" { + password = raw(cfg.Get("password")) + } + p.User = user + + providerProps := cfg.Field("provider-properties") + authProps := cfg.Field("auth-properties") + driverProps := cfg.Field("properties") + handlers := cfg.Field("handlers") + var sslHandler *ojson.Object + if h := sslHandlerID(engine); h != "" { + sslHandler = enabledHandler(handlers, h) + } + + oracleType := upperASCII(text(providerProps.Get(oraConnectionType))) + var addrErr error + if urlMode || (engine == model.Oracle && oracleType == "CUSTOM") { + addrErr = urlTarget(url, &p) + } else { + manualTarget(engine, cfg, providerProps, &p) + } + if addrErr != nil { + out.skip(display, fmt.Sprintf("Uses a JDBC URL LowQuery cannot read: %s.", addrErr)) + return + } + + switch p.Engine { + case model.Postgres: + postgresSsl(&p, sslHandler, driverProps, urlMode) + case model.MySQL, model.MariaDB: + mysqlSsl(&p, sslHandler, driverProps, urlMode) + case model.SQLServer: + sqlserverOptions(&p, driver, sslHandler, driverProps, providerProps, urlMode) + case model.Oracle: + dbeaverOraclePrivilege(&p, secret, authProps, providerProps) + if truthy(providerProps.Get(oraOsAuth)) { + warnings = append(warnings, "Uses Oracle OS authentication, which LowQuery does not support.") + } + } + + warnings = authModelWarnings(&p, text(cfg.Get("auth-model")), warnings) + warnings = handlerWarnings(handlers, sslHandlerID(p.Engine), warnings) + if sslHandler != nil { + warnings = certificateWarnings(sslHandler, warnings) + } + warnings = propertyWarnings(p.Engine, driverProps, warnings) + warnings = otherWarnings(conn, cfg, warnings) + + p.Color = dbeaverColor(cfg, types) + if strings.TrimSpace(p.Name) == "" && p.Engine == model.SQLite { + p.Name = fileName(p.Database) + } + if reason := incomplete(&p); reason != "" { + out.skip(display, reason) + return + } + + if password != "" { + // DBeaver turns "save password" on when it finds one. + p.SavePassword = true + out.passwords[id] = password + } + var folder *string + if f := text(conn.Get("folder")); f != "" { + folder = &f + } + out.candidates = append(out.candidates, ImportCandidate{ + Key: id, + Profile: p, + Folder: folder, + Warnings: warnings, + }) +} + +// dbeaverEngine is the engine of a DBeaver provider and driver. An empty +// engine and reason means a generic or custom driver whose URL decides; a +// reason means the database is not supported. +func dbeaverEngine(provider, driver string) (model.Engine, string) { + d := lowerASCII(driver) + unsupported := func(what string) (model.Engine, string) { + return "", what + " is not supported by LowQuery." + } + if provider == "redis" || strings.Contains(d, "redis") { + return model.Redis, "" + } + // DBeaver ships Cassandra through commercial and third-party drivers; + // what they have in common is the id and the jdbc:cassandra: URL. + if strings.Contains(provider, "cassandra") || strings.Contains(d, "cassandra") { + return model.Cassandra, "" + } + switch provider { + case "postgresql", "greenplum": + for _, v := range [][2]string{ + {"redshift", "Amazon Redshift"}, + {"cockroach", "CockroachDB"}, + {"materialize", "Materialize"}, + {"risingwave", "RisingWave"}, + {"cratedb", "CrateDB"}, + {"yellowbrick", "Yellowbrick"}, + {"gcloud", "The Google Cloud SQL connector"}, + } { + if strings.Contains(d, v[0]) { + return unsupported(v[1]) + } + } + return model.Postgres, "" + case "oracle": + return model.Oracle, "" + case "mysql": + switch d { + case "mariadb": + return model.MariaDB, "" + case "starrocks": + return unsupported("StarRocks") + } + return model.MySQL, "" + case "mariadb": + return model.MariaDB, "" + case "sqlserver", "mssql": + if strings.Contains(d, "sybase") || strings.Contains(d, "sypase") { + return unsupported("Sybase") + } + return model.SQLServer, "" + case "sqlite": + if strings.Contains(d, "libsql") { + return unsupported("libSQL") + } + return model.SQLite, "" + case "generic": + switch d { + case "sqlite_jdbc": + return model.SQLite, "" + case "postgresql", "postgresql_generic": + return model.Postgres, "" + case "mysql3": + return model.MySQL, "" + case "mssql", "mssql_ms": + return model.SQLServer, "" + case "oracle": + return model.Oracle, "" + } + return "", "" + case "": + return "", "The connection has no DBeaver driver." + } + return unsupported(product(provider)) +} + +var productNames = [][2]string{ + {"db2", "DB2"}, + {"clickhouse", "ClickHouse"}, + {"snowflake", "Snowflake"}, + {"mongo", "MongoDB"}, + {"hana", "SAP HANA"}, + {"vertica", "Vertica"}, + {"exasol", "Exasol"}, + {"firebird", "Firebird"}, + {"duckdb", "DuckDB"}, + {"bigquery", "Google BigQuery"}, + {"redshift", "Amazon Redshift"}, + {"athena", "Amazon Athena"}, + {"databricks", "Databricks"}, + {"teradata", "Teradata"}, + {"informix", "Informix"}, + {"sybase", "Sybase"}, + {"hive", "Apache Hive"}, + {"elastic", "Elasticsearch"}, + {"dynamo", "DynamoDB"}, + {"couchbase", "Couchbase"}, + {"neo4j", "Neo4j"}, + {"trino", "Trino"}, + {"presto", "Presto"}, + {"derby", "Apache Derby"}, + {"hsqldb", "HSQLDB"}, + {"access", "Microsoft Access"}, + {"csv", "CSV files"}, +} + +// product is the product name for a DBeaver provider or driver id. +func product(id string) string { + l := lowerASCII(id) + if l == "h2" || strings.HasPrefix(l, "h2_") { + return "H2" + } + for _, n := range productNames { + if strings.Contains(l, n[0]) { + return n[1] + } + } + if id == "" { + return "This driver" + } + return `The DBeaver driver "` + id + `"` +} + +func defaultPort(engine model.Engine) uint16 { + switch engine { + case model.Postgres: + return 5432 + case model.Oracle: + return 1521 + case model.MySQL, model.MariaDB: + return 3306 + case model.SQLServer: + return 1433 + case model.Redis: + return 6379 + case model.Cassandra: + return 9042 + } + return 0 +} + +func portOr(s string, def uint16) uint16 { + if n, ok := parseU16(strings.TrimSpace(s)); ok && n > 0 { + return n + } + return def +} + +type reasonError string + +func (e reasonError) Error() string { return string(e) } + +// urlTarget reads the address from a JDBC URL (configurationType URL and +// Oracle "Custom"). +func urlTarget(url string, p *model.ConnectionProfile) error { + url = strings.TrimSpace(url) + if url == "" { + return reasonError("the URL is empty") + } + if strings.Contains(url, "{") { + return reasonError("the URL is a DBeaver template") + } + // The OCI driver takes the same addresses as the thin one. + thin := url + if tail, ok := stripPrefixFold(url, "jdbc:oracle:oci:"); ok { + thin = "jdbc:oracle:thin:" + tail + } + if err := applyURL(thin, p); err != nil { + return err + } + if p.Engine == model.SQLServer { + // DBeaver writes jdbc:sqlserver://;serverName=host\inst;port=... + for _, kv := range strings.Split(url, ";")[1:] { + k, v, ok := splitOnce(kv, "=") + if !ok { + continue + } + v = strings.TrimSpace(v) + if eqFold(strings.TrimSpace(k), "servername") && v != "" { + host, instance := splitInstance(v) + p.Host = host + if instance != "" { + p.Instance = instance + } + } + } + } + return nil +} + +func splitInstance(server string) (string, string) { + if h, i, ok := splitOnce(server, `\`); ok { + return strings.TrimSpace(h), strings.TrimSpace(i) + } + return server, "" +} + +// manualTarget reads the address from the host, port and database fields. +func manualTarget(engine model.Engine, cfg, providerProps *ojson.Object, p *model.ConnectionProfile) { + host := text(cfg.Get("host")) + port := text(cfg.Get("port")) + database := text(cfg.Get("database")) + switch engine { + case model.SQLite: + p.Host = "" + p.Port = 0 + p.Database = database + if p.Database == "" { + probe := model.DefaultProfile() + if applyURL(text(cfg.Get("url")), &probe) == nil && probe.Engine == model.SQLite { + p.Database = probe.Database + } + } + case model.Oracle: + if upperASCII(text(providerProps.Get(oraConnectionType))) == "TNS" { + p.OracleConnectType = model.OracleTNS + p.TnsAlias = database + if tns := text(providerProps.Get(oraTnsPath)); tns != "" { + dir := tnsDir(tns) + p.ConfigDir = &dir + } + if host != "" { + p.Host = host + } + } else { + if eqFold(text(providerProps.Get(oraSidService)), "SID") { + p.OracleConnectType = model.OracleSID + } else { + p.OracleConnectType = model.OracleService + } + p.Host = host + p.Port = portOr(port, p.Port) + p.Database = database + } + case model.SQLServer: + // A named instance is typed as host\INSTANCE. + p.Host, p.Instance = splitInstance(host) + p.Port = portOr(port, p.Port) + p.Database = database + case model.Redis: + p.Host = host + p.Port = portOr(port, p.Port) + p.Database = "" + if parseU32(database) { + p.Database = database + } + case model.Postgres, model.MySQL, model.MariaDB: + p.Host = host + p.Port = portOr(port, p.Port) + p.Database = database + case model.Cassandra: + // The database field holds the keyspace; contact points may be a + // comma-separated list. + points := strings.Split(strings.ReplaceAll(host, ";", ","), ",") + for i := range points { + points[i] = strings.TrimSpace(points[i]) + } + p.Host = strings.Join(points, ",") + p.Port = portOr(port, p.Port) + p.Database = database + } +} + +// tnsDir: DBeaver's TNS path is the folder of tnsnames.ora; accept the file +// too. +func tnsDir(path string) string { + if eqFold(fileName(path), "tnsnames.ora") { + if parent, ok := parentDir(path); ok { + return parent + } + } + return path +} + +func sslHandlerID(engine model.Engine) string { + switch engine { + case model.Postgres: + return "postgre_ssl" + case model.MySQL, model.MariaDB: + return "mysql_ssl" + case model.SQLServer: + return "mssql_ssl" + } + return "" +} + +func enabledHandler(handlers *ojson.Object, id string) *ojson.Object { + h := handlers.Field(id) + if h != nil && truthy(h.Get("enabled")) { + return h + } + return nil +} + +func handlerProp(h *ojson.Object, key string) string { + return text(h.Field("properties").Get(key)) +} + +// prop finds a property ignoring ASCII case; ok is false when missing. +func prop(props *ojson.Object, key string) (any, bool) { + for _, k := range props.Keys() { + if eqFold(k, key) { + return props.Get(k), true + } + } + return nil, false +} + +// postgresSsl follows PostgreDataSource.initServerSSL: the handler sets +// ssl=true (pgjdbc then verifies the certificate) unless it names an +// sslMode. +func postgresSsl(p *model.ConnectionProfile, handler, props *ojson.Object, urlMode bool) { + if handler != nil { + if mode, ok := pgSslMode(handlerProp(handler, "sslMode")); ok { + p.SslMode = mode + } else { + p.SslMode = model.SslVerifyFull + } + return + } + if urlMode { + return + } + if v, ok := prop(props, "sslmode"); ok { + if mode, ok := pgSslMode(text(v)); ok { + p.SslMode = mode + return + } + } + if v, ok := prop(props, "ssl"); ok && truthy(v) { + p.SslMode = model.SslVerifyFull + } +} + +// mysqlSsl follows MySQLDataSource: without the SSL handler DBeaver sends +// useSSL=false. +func mysqlSsl(p *model.ConnectionProfile, handler, props *ojson.Object, urlMode bool) { + if handler != nil { + if eqFold(handlerProp(handler, "ssl.verify.server"), "true") { + p.SslMode = model.SslVerifyFull + } else { + p.SslMode = model.SslRequire + } + return + } + if urlMode { + return + } + p.SslMode = model.SslDisable + if v, ok := prop(props, "sslMode"); ok { + p.SslMode = mysqlSslMode(text(v)) + } else if v, ok := prop(props, "useSSL"); ok && truthy(v) { + p.SslMode = model.SslRequire + } +} + +func sqlserverOptions(p *model.ConnectionProfile, driver string, handler, props, providerProps *ojson.Object, urlMode bool) { + var encrypt *bool + if v, ok := prop(props, "encrypt"); ok { + on := sqlserverEncrypt(text(v)) + encrypt = &on + } + trustV, _ := prop(props, "trustServerCertificate") + trust := truthy(trustV) + if handler != nil { + on := true + encrypt = &on + trust = trust || eqFold(handlerProp(handler, "sslTrustServerCertificate"), "true") + } + // The Azure driver template adds encrypt=true. + if encrypt == nil && strings.Contains(lowerASCII(driver), "azure") { + on := true + encrypt = &on + } + if !urlMode || encrypt != nil || trust { + p.SslMode = sqlserverSsl(encrypt, trust) + } + integrated, _ := prop(props, "integratedSecurity") + if truthy(integrated) || truthy(providerProps.Get(mssqlWindowsAuth)) { + p.WindowsAuth = true + } +} + +// dbeaverOraclePrivilege reads "Logon as" from the auth properties (kept in +// the credentials file), the older provider properties, or a "user AS +// SYSDBA" user name. +func dbeaverOraclePrivilege(p *model.ConnectionProfile, secret, auth, provider *ojson.Object) { + for _, v := range []any{ + secret.Get(oraLogonAs), + auth.Get(oraLogonAs), + provider.Get(oraLogonAs), + provider.Get(oraInternalLogon), + } { + if r, ok := oraclePrivilege(text(v)); ok { + p.OraclePrivilege = r + break + } + } + if user, r, ok := splitOracleRole(p.User); ok { + p.User = user + p.OraclePrivilege = r + } +} + +func authModelWarnings(p *model.ConnectionProfile, m string, warnings []string) []string { + switch { + case m == "" || m == "native" || m == "oracle_native" || m == "sqlserver_database": + case m == "sqlserver_windows": + p.WindowsAuth = true + case m == "sqlserver_ntlm": + p.WindowsAuth = true + warnings = append(warnings, "Uses NTLM with a named account; LowQuery signs in as the current Windows user.") + case m == "oracle_os": + warnings = append(warnings, "Uses Oracle OS authentication, which LowQuery does not support.") + case m == "postgres_pgpass": + warnings = append(warnings, "Reads its password from .pgpass in DBeaver; LowQuery asks for it on first connect.") + case strings.HasPrefix(m, "sqlserver_ad") || m == "sqlserver_msi" || m == "sqlserver_mfa": + warnings = append(warnings, "Uses Microsoft Entra ID (Azure AD) sign-in, which LowQuery does not support.") + default: + warnings = append(warnings, `Uses the DBeaver sign-in method "`+m+`", which is not carried over.`) + } + return warnings +} + +func contains(list []string, s string) bool { + for _, v := range list { + if v == s { + return true + } + } + return false +} + +// handlerWarnings reports enabled network handlers other than the engine's +// SSL handler. +func handlerWarnings(handlers *ojson.Object, ssl string, warnings []string) []string { + for _, id := range handlers.Keys() { + h := handlers.Field(id) + if h == nil || !truthy(h.Get("enabled")) || (ssl != "" && id == ssl) { + continue + } + kind := upperASCII(text(h.Get("type"))) + var message string + switch { + case strings.Contains(id, "ssh") || kind == "TUNNEL": + message = "Uses an SSH tunnel, which LowQuery does not support; open the tunnel yourself and " + + "point the connection at it." + case strings.Contains(id, "proxy") || kind == "PROXY": + message = "Connects through a proxy, which LowQuery does not support." + case strings.Contains(id, "ssl"): + message = "Uses SSL settings LowQuery does not read for this database." + default: + message = `Uses the DBeaver network handler "` + id + `", which is not carried over.` + } + if !contains(warnings, message) { + warnings = append(warnings, message) + } + } + return warnings +} + +// certificateWarnings reports certificates in the SSL handler +// (SSLHandlerTrustStoreImpl and the older per-driver keys). +func certificateWarnings(h *ojson.Object, warnings []string) []string { + anyOf := func(keys ...string) bool { + for _, k := range keys { + if handlerProp(h, k) != "" { + return true + } + } + return false + } + if anyOf("ssl.client.cert", "clientCert", "ssl.keystore") { + warnings = append(warnings, "Uses a client certificate, which is not carried over.") + } + if anyOf("ssl.ca.cert", "rootCert") { + warnings = append(warnings, "Trusts a custom CA certificate; LowQuery checks the server against the system "+ + "certificates.") + } + return warnings +} + +func propertyWarnings(engine model.Engine, props *ojson.Object, warnings []string) []string { + var used []string + switch engine { + case model.Postgres: + used = []string{"sslmode", "ssl", "user"} + case model.MySQL, model.MariaDB: + used = []string{"sslMode", "useSSL", "user"} + case model.SQLServer: + used = []string{"encrypt", "trustServerCertificate", "integratedSecurity", "user"} + } + kerberos, entra := false, false + var others []string + for _, k := range props.Keys() { + skip := false + for _, u := range append(append([]string{}, used...), harmlessProperties...) { + if eqFold(u, k) { + skip = true + break + } + } + if skip { + continue + } + value := text(props.Get(k)) + if engine == model.SQLServer && eqFold(k, "authenticationScheme") { + kerberos = kerberos || eqFold(value, "JavaKerberos") + continue + } + if engine == model.SQLServer && eqFold(k, "authentication") { + entra = entra || strings.HasPrefix(lowerASCII(value), "activedirectory") + continue + } + others = append(others, k) + } + if kerberos { + warnings = append(warnings, "Uses Kerberos authentication, which LowQuery does not support.") + } + if entra { + warnings = append(warnings, "Uses Microsoft Entra ID (Azure AD) sign-in, which LowQuery does not support.") + } + if len(others) > 0 { + shown := others + more := "" + if len(shown) > 5 { + shown = shown[:5] + more = ", ..." + } + warnings = append(warnings, fmt.Sprintf("Driver properties are not carried over: %s%s.", strings.Join(shown, ", "), more)) + } + return warnings +} + +func otherWarnings(conn, cfg *ojson.Object, warnings []string) []string { + if truthy(conn.Get("read-only")) { + warnings = append(warnings, "Is read-only in DBeaver; LowQuery does not enforce that.") + } + if b := cfg.Field("bootstrap"); b != nil { + q := b.Get("initQueries") + if !b.Has("initQueries") { + q = b.Get("query") + } + if list, ok := q.([]any); ok && len(list) > 0 { + warnings = append(warnings, "Runs SQL on connect (bootstrap queries), which is not carried over.") + } + if text(b.Get("defaultCatalog")) != "" || text(b.Get("defaultSchema")) != "" { + warnings = append(warnings, "Opens a default catalog or schema, which is not carried over.") + } + if v, ok := b.Get("autocommit").(bool); ok && !v { + warnings = append(warnings, "Turns auto-commit off on connect, which is not carried over.") + } + } + events := cfg.Field("events") + for _, k := range events.Keys() { + if truthy(events.Field(k).Get("enabled")) { + warnings = append(warnings, "Runs shell commands on connection events, which are not carried over.") + break + } + } + return warnings +} + +// dbeaverColor: production is red; otherwise the connection's own color, +// then the connection type's. +func dbeaverColor(cfg, types *ojson.Object) *string { + kind := text(cfg.Get("type")) + if eqFold(kind, "prod") { + return model.Str(red) + } + if c, ok := rgb(text(cfg.Get("color"))); ok { + return &c + } + other := lowerASCII(kind) + switch other { + case "", "dev": + return nil + case "test": + return model.Str(green) + } + t := types.Field(other) + if t == nil { + t = types.Field(kind) + } + if t == nil { + return nil + } + name := lowerASCII(text(t.Get("name"))) + if strings.Contains(other, "prod") || strings.Contains(name, "prod") { + return model.Str(red) + } + if c, ok := rgb(text(t.Get("color"))); ok { + return &c + } + return nil +} + +// rgb reads "r,g,b" (DBeaver's format) or "#rrggbb"; white means no color. +func rgb(s string) (string, bool) { + s = strings.TrimSpace(s) + var hex string + if h, ok := strings.CutPrefix(s, "#"); ok { + if len(h) != 6 || !isHex(h) { + return "", false + } + hex = lowerASCII(h) + } else { + parts := strings.Split(s, ",") + if len(parts) != 3 { + // Rust collects every part first: a bad part fails either way. + return "", false + } + var v [3]uint8 + for i, part := range parts { + n, ok := parseU8(strings.TrimSpace(part)) + if !ok { + return "", false + } + v[i] = n + } + hex = fmt.Sprintf("%02x%02x%02x", v[0], v[1], v[2]) + } + if hex == "ffffff" { + return "", false + } + return "#" + hex, true +} + +func isHex(s string) bool { + for i := 0; i < len(s); i++ { + c := s[i] + if !('0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F') { + return false + } + } + return true +} + +// incomplete is the check profiles.validate makes, as a skip reason. +func incomplete(p *model.ConnectionProfile) string { + switch { + case p.Engine == model.Oracle && p.OracleConnectType == model.OracleCustom: + if strings.TrimSpace(p.ConnectString) == "" { + return "The Oracle connect string is empty." + } + return "" + case p.Engine == model.Oracle && p.OracleConnectType == model.OracleTNS: + if strings.TrimSpace(p.TnsAlias) == "" { + return "No TNS alias is set." + } + return "" + case p.Engine == model.SQLite: + if strings.TrimSpace(p.Database) == "" { + return "No database file is set." + } + return "" + case strings.TrimSpace(p.Host) == "": + return "No host is set." + } + return "" +} diff --git a/internal/importers/dbeaver_fixtures_test.go b/internal/importers/dbeaver_fixtures_test.go new file mode 100644 index 0000000..6d6733a --- /dev/null +++ b/internal/importers/dbeaver_fixtures_test.go @@ -0,0 +1,259 @@ +package importers + +// Fixtures ported from the Rust dbeaver.rs tests. + +const dbeaverDataSources = `{ + "folders": { + "Production": {}, + "Production/ERP": { "description": "ERP databases" } + }, + "connection-types": { + "dev": { "name": "Development", "color": "255,255,255", "auto-commit": true }, + "uat": { "name": "UAT", "color": "255,200,0", "auto-commit": true }, + "live": { "name": "Production 2", "color": "247,159,129", "confirm-execute": true } + }, + "connections": { + "postgres-jdbc-18c2f0a1b2c-6d1e4f": { + "provider": "postgresql", + "driver": "postgres-jdbc", + "name": "Sales PG", + "save-password": true, + "folder": "Production/ERP", + "configuration": { + "host": "pg.internal", + "port": "5433", + "database": "sales", + "url": "jdbc:postgresql://pg.internal:5433/sales", + "configurationType": "MANUAL", + "home": "", + "type": "prod", + "provider-properties": { "@dbeaver-show-non-default-db@": "true" }, + "auth-model": "native", + "handlers": { + "postgre_ssl": { + "type": "CONFIG", + "enabled": true, + "save-password": false, + "properties": { "sslMode": "verify-ca", "ssl.method": "CERTIFICATES", "ssl.ca.cert": "C:\\certs\\ca.pem" } + }, + "ssh_tunnel": { + "type": "TUNNEL", + "enabled": true, + "save-password": true, + "properties": { "host": "bastion", "port": 22, "authType": "PASSWORD" } + } + }, + "bootstrap": { "initQueries": ["set search_path to app"] } + } + }, + "oracle_thin-1a2b": { + "provider": "oracle", + "driver": "oracle_thin", + "name": "ERP SID", + "save-password": true, + "folder": "Production/ERP", + "configuration": { + "host": "erp-db", + "port": "1521", + "database": "ERPPRD", + "url": "jdbc:oracle:thin:@erp-db:1521:ERPPRD", + "configurationType": "MANUAL", + "type": "dev", + "provider-properties": { + "@dbeaver-connection-type@": "BASIC", + "@dbeaver-sid-service@": "SID" + }, + "auth-model": "oracle_native" + } + }, + "oracle_thin-3c4d": { + "provider": "oracle", + "driver": "oracle_thin", + "name": "ERP service as SYSDBA", + "save-password": true, + "configuration": { + "host": "erp-db.internal", + "port": "1522", + "database": "erppdb", + "configurationType": "MANUAL", + "type": "uat", + "provider-properties": { + "@dbeaver-connection-type@": "BASIC", + "@dbeaver-sid-service@": "SERVICE" + }, + "auth-model": "oracle_native" + } + }, + "oracle_thin-5e6f": { + "provider": "oracle", + "driver": "oracle_thin", + "name": "ERP TNS", + "configuration": { + "database": "ERP_TNS", + "configurationType": "MANUAL", + "type": "live", + "provider-properties": { + "@dbeaver-connection-type@": "TNS", + "@dbeaver-tns-path@": "C:\\oracle\\network\\admin", + "@dbeaver-internal-logon@": "SYSOPER" + } + } + }, + "oracle_thin-7a8b": { + "provider": "oracle", + "driver": "oracle_thin", + "name": "ERP custom", + "configuration": { + "url": "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=h)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=s)))", + "configurationType": "MANUAL", + "provider-properties": { "@dbeaver-connection-type@": "CUSTOM" }, + "user": "scott AS SYSDBA" + } + }, + "microsoft-9c0d": { + "provider": "sqlserver", + "driver": "microsoft", + "name": "Finance", + "save-password": false, + "configuration": { + "host": "fin-sql\\REPORTING", + "port": "1433", + "database": "Finance", + "configurationType": "MANUAL", + "color": "0,128,255", + "auth-model": "sqlserver_windows", + "properties": { "trustServerCertificate": "true", "encrypt": "true", "selectMethod": "cursor" } + } + }, + "mssql_jdbc_azure-1e2f": { + "provider": "mssql", + "driver": "mssql_jdbc_azure", + "name": "Azure SQL", + "save-password": true, + "configuration": { + "host": "corp.database.windows.net", + "database": "app", + "configurationType": "MANUAL", + "type": "test", + "auth-model": "sqlserver_ad_password" + } + }, + "jtds-3a4b": { + "provider": "sqlserver", + "driver": "jtds", + "name": "Legacy jTDS URL", + "configuration": { + "url": "jdbc:jtds:sqlserver://old-sql:1500/Legacy;instance=SQLEXPRESS", + "configurationType": "URL" + } + }, + "microsoft-5c6d": { + "provider": "sqlserver", + "driver": "microsoft", + "name": "Generated URL", + "configuration": { + "url": "jdbc:sqlserver://;serverName=bi-sql\\OLAP;port=1500;databaseName=Cube", + "configurationType": "URL" + } + }, + "mysql8-7e8f": { + "provider": "mysql", + "driver": "mysql8", + "name": "Shop", + "save-password": true, + "read-only": true, + "configuration": { + "host": "shop-db", + "port": "3307", + "database": "shop", + "configurationType": "MANUAL", + "properties": { "allowPublicKeyRetrieval": "true" } + } + }, + "mariaDB-9a0b": { + "provider": "mysql", + "driver": "mariaDB", + "name": "Maria", + "configuration": { + "host": "maria", + "configurationType": "MANUAL", + "handlers": { + "mysql_ssl": { + "type": "CONFIG", + "enabled": true, + "properties": { "ssl.require": true, "ssl.verify.server": true } + } + } + } + }, + "sqlite_jdbc-1c2d": { + "provider": "sqlite", + "driver": "sqlite_jdbc", + "name": "", + "configuration": { + "database": "C:\\data\\app.db", + "url": "jdbc:sqlite:C:\\data\\app.db", + "configurationType": "MANUAL" + } + }, + "redis-3e4f": { + "provider": "redis", + "driver": "redis", + "name": "Cache", + "configuration": { "host": "cache", "database": "2", "configurationType": "MANUAL" } + }, + "cassandra-2b3c": { + "provider": "cassandra", + "driver": "cassandra_jdbc", + "name": "Events", + "configuration": { "host": "n1, n2", "database": "events", "configurationType": "MANUAL" } + }, + "cassandra-url-4d5e": { + "provider": "generic", + "driver": "18f0c2a1-cassandra-custom", + "name": "Cassandra by URL", + "configuration": { + "url": "jdbc:cassandra://c1:9043,c2/shop?localdc=dc1", + "configurationType": "URL" + } + }, + "db2_luw-5a6b": { + "provider": "db2", + "driver": "db2_luw", + "name": "Mainframe", + "configuration": { "host": "db2", "port": "50000", "database": "SAMPLE" } + }, + "postgres-redshift-jdbc-7c8d": { + "provider": "postgresql", + "driver": "postgres-redshift-jdbc", + "name": "Warehouse", + "configuration": { "host": "wh", "port": "5439", "database": "dw" } + }, + "h2_embedded-9e0f": { + "provider": "generic", + "driver": "h2_embedded_v2", + "name": "Local H2", + "configuration": { "url": "jdbc:h2:~/test", "configurationType": "MANUAL" } + }, + "custom-pg-1a1a": { + "provider": "generic", + "driver": "18f0c2a1-custom", + "name": "Custom PG driver", + "configuration": { "url": "jdbc:postgresql://custom:6543/db", "configurationType": "URL" } + }, + "postgres-jdbc-nohost": { + "provider": "postgresql", + "driver": "postgres-jdbc", + "name": "No host", + "configuration": { "host": "", "configurationType": "MANUAL" } + } + } +}` + +const dbeaverCredentials = `{ + "postgres-jdbc-18c2f0a1b2c-6d1e4f": { "#connection": { "user": "sales_app", "password": "fake-pass-1" } }, + "oracle_thin-1a2b": { "#connection": { "user": "erp", "password": "fake-pass-2" } }, + "oracle_thin-3c4d": { "#connection": { "user": "sys", "password": "fake-pass-3", "oracle.logon-as": "sysdba" } }, + "mysql8-7e8f": { "#connection": { "user": "shop" } }, + "mssql_jdbc_azure-1e2f": { "#connection": { "user": "ana@corp.com", "password": "fake-pass-4" }, "network/ssh_tunnel": { "user": "tunnel", "password": "fake-pass-5" } } +}` diff --git a/internal/importers/dbeaver_test.go b/internal/importers/dbeaver_test.go new file mode 100644 index 0000000..a2973dd --- /dev/null +++ b/internal/importers/dbeaver_test.go @@ -0,0 +1,396 @@ +package importers + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/LowBloat/LowQuery/internal/model" +) + +func encryptCredentials(plain []byte) []byte { + iv := bytes.Repeat([]byte{7}, 16) + pad := 16 - len(plain)%16 + buf := append(append([]byte{}, plain...), bytes.Repeat([]byte{byte(pad)}, pad)...) + block, _ := aes.NewCipher(credentialsKey) + cipher.NewCBCEncrypter(block, iv).CryptBlocks(buf, buf) + return append(iv, buf...) +} + +// dbeaverProject writes a project's .dbeaver folder and returns the path of +// data-sources.json. +func dbeaverProject(t *testing.T, dir, data string, creds []byte) string { + t.Helper() + path := writeFile(t, dir, ".dbeaver/data-sources.json", data) + if creds != nil { + if err := os.WriteFile(filepath.Join(dir, ".dbeaver", "credentials-config.json"), creds, 0o644); err != nil { + t.Fatal(err) + } + } + return path +} + +func TestDBeaverFullProject(t *testing.T) { + path := dbeaverProject(t, t.TempDir(), dbeaverDataSources, encryptCredentials([]byte(dbeaverCredentials))) + p, err := parse(DBeaver, path) + if err != nil { + t.Fatal(err) + } + if len(p.notes) != 0 { + t.Fatalf("notes: %v", p.notes) + } + + pg := find(t, p, "postgres-jdbc-18c2f0a1b2c-6d1e4f") + if pg.Profile.Engine != model.Postgres || pg.Profile.Host != "pg.internal" || pg.Profile.Port != 5433 || pg.Profile.Database != "sales" { + t.Fatalf("%+v", pg.Profile) + } + if pg.Profile.User != "sales_app" || pg.Profile.SslMode != model.SslRequire || deref(pg.Profile.Color) != red { + t.Fatalf("%+v", pg.Profile) + } + if deref(pg.Folder) != "Production/ERP" || !pg.HasPassword || !pg.Profile.SavePassword { + t.Fatalf("%+v", pg) + } + for _, w := range []string{"SSH tunnel", "CA certificate", "bootstrap"} { + if !anyContains(pg.Warnings, w) { + t.Fatalf("no %q warning: %v", w, pg.Warnings) + } + } + if p.passwords[pg.Key] != "fake-pass-1" { + t.Fatal("postgres password") + } + + sid := find(t, p, "oracle_thin-1a2b") + if sid.Profile.Engine != model.Oracle || sid.Profile.OracleConnectType != model.OracleSID { + t.Fatalf("%+v", sid.Profile) + } + if sid.Profile.Host != "erp-db" || sid.Profile.Port != 1521 || sid.Profile.Database != "ERPPRD" || sid.Profile.User != "erp" { + t.Fatalf("%+v", sid.Profile) + } + if sid.Profile.Color != nil || len(sid.Warnings) != 0 { + t.Fatalf("%+v %v", sid.Profile, sid.Warnings) + } + + svc := find(t, p, "oracle_thin-3c4d") + if svc.Profile.OracleConnectType != model.OracleService || svc.Profile.Port != 1522 || svc.Profile.Database != "erppdb" { + t.Fatalf("%+v", svc.Profile) + } + if svc.Profile.OraclePrivilege != "sysdba" || deref(svc.Profile.Color) != "#ffc800" || svc.Folder != nil { + t.Fatalf("%+v", svc) + } + + tns := find(t, p, "oracle_thin-5e6f") + if tns.Profile.OracleConnectType != model.OracleTNS || tns.Profile.TnsAlias != "ERP_TNS" { + t.Fatalf("%+v", tns.Profile) + } + if deref(tns.Profile.ConfigDir) != `C:\oracle\network\admin` || tns.Profile.OraclePrivilege != "sysoper" { + t.Fatalf("%+v", tns.Profile) + } + if deref(tns.Profile.Color) != red || tns.Profile.SavePassword || tns.HasPassword { + t.Fatalf("%+v", tns) + } + + custom := find(t, p, "oracle_thin-7a8b") + if custom.Profile.OracleConnectType != model.OracleCustom || !strings.HasPrefix(custom.Profile.ConnectString, "(DESCRIPTION=") { + t.Fatalf("%+v", custom.Profile) + } + if custom.Profile.User != "scott" || custom.Profile.OraclePrivilege != "sysdba" { + t.Fatalf("%+v", custom.Profile) + } + + fin := find(t, p, "microsoft-9c0d") + if fin.Profile.Engine != model.SQLServer || fin.Profile.Host != "fin-sql" || fin.Profile.Instance != "REPORTING" { + t.Fatalf("%+v", fin.Profile) + } + if !fin.Profile.WindowsAuth || fin.Profile.SslMode != model.SslRequire || deref(fin.Profile.Color) != "#0080ff" || fin.Profile.SavePassword { + t.Fatalf("%+v", fin.Profile) + } + if !anyContains(fin.Warnings, "selectMethod") { + t.Fatalf("%v", fin.Warnings) + } + + azure := find(t, p, "mssql_jdbc_azure-1e2f") + if azure.Profile.SslMode != model.SslVerifyFull || azure.Profile.Port != 1433 || deref(azure.Profile.Color) != green { + t.Fatalf("%+v", azure.Profile) + } + if !anyContains(azure.Warnings, "Entra") || p.passwords[azure.Key] != "fake-pass-4" { + t.Fatalf("%v", azure.Warnings) + } + + jtds := find(t, p, "jtds-3a4b") + if jtds.Profile.Host != "old-sql" || jtds.Profile.Port != 1500 || jtds.Profile.Database != "Legacy" || jtds.Profile.Instance != "SQLEXPRESS" { + t.Fatalf("%+v", jtds.Profile) + } + + gen := find(t, p, "microsoft-5c6d") + if gen.Profile.Host != "bi-sql" || gen.Profile.Instance != "OLAP" || gen.Profile.Port != 1500 || gen.Profile.Database != "Cube" { + t.Fatalf("%+v", gen.Profile) + } + + shop := find(t, p, "mysql8-7e8f") + if shop.Profile.Engine != model.MySQL || shop.Profile.Port != 3307 || shop.Profile.User != "shop" || shop.Profile.SslMode != model.SslDisable { + t.Fatalf("%+v", shop.Profile) + } + if shop.HasPassword || !shop.Profile.SavePassword { + t.Fatalf("%+v", shop) + } + if len(shop.Warnings) != 1 || !strings.Contains(shop.Warnings[0], "read-only") { + t.Fatalf("%v", shop.Warnings) + } + + maria := find(t, p, "mariaDB-9a0b") + if maria.Profile.Engine != model.MariaDB || maria.Profile.Port != 3306 || maria.Profile.SslMode != model.SslVerifyFull { + t.Fatalf("%+v", maria.Profile) + } + + lite := find(t, p, "sqlite_jdbc-1c2d") + if lite.Profile.Engine != model.SQLite || lite.Profile.Database != `C:\data\app.db` || lite.Profile.Host != "" || lite.Profile.Name == "" { + t.Fatalf("%+v", lite.Profile) + } + + redis := find(t, p, "redis-3e4f") + if redis.Profile.Engine != model.Redis || redis.Profile.Port != 6379 || redis.Profile.Database != "2" { + t.Fatalf("%+v", redis.Profile) + } + + cass := find(t, p, "cassandra-2b3c") + if cass.Profile.Engine != model.Cassandra || cass.Profile.Host != "n1,n2" || cass.Profile.Port != 9042 || cass.Profile.Database != "events" { + t.Fatalf("%+v", cass.Profile) + } + cassURL := find(t, p, "cassandra-url-4d5e") + if cassURL.Profile.Engine != model.Cassandra || cassURL.Profile.Host != "c1,c2" || cassURL.Profile.Port != 9043 { + t.Fatalf("%+v", cassURL.Profile) + } + if cassURL.Profile.Database != "shop" || cassURL.Profile.Datacenter != "dc1" { + t.Fatalf("%+v", cassURL.Profile) + } + + customPG := find(t, p, "custom-pg-1a1a") + if customPG.Profile.Engine != model.Postgres || customPG.Profile.Host != "custom" || customPG.Profile.Port != 6543 { + t.Fatalf("%+v", customPG.Profile) + } + + for name, want := range map[string]string{ + "Mainframe": "DB2 is not supported by LowQuery.", + "Warehouse": "Amazon Redshift is not supported by LowQuery.", + "Local H2": "H2 is not supported by LowQuery.", + "No host": "No host is set.", + } { + if got := skipped(t, p, name); got != want { + t.Fatalf("%s: %q", name, got) + } + } + if len(p.candidates) != 16 || len(p.passwords) != 4 { + t.Fatalf("%d candidates, %d passwords", len(p.candidates), len(p.passwords)) + } + // Tunnel credentials are not connection passwords. + for _, v := range p.passwords { + if v == "fake-pass-5" { + t.Fatal("tunnel password imported") + } + } + // Passwords never leak into messages. + for _, c := range p.candidates { + if anyContains(c.Warnings, "fake-pass") { + t.Fatalf("%v", c.Warnings) + } + } + // Candidates keep the file order. + if p.candidates[0].Key != "postgres-jdbc-18c2f0a1b2c-6d1e4f" || p.candidates[1].Key != "oracle_thin-1a2b" { + t.Fatalf("order: %s, %s", p.candidates[0].Key, p.candidates[1].Key) + } +} + +func TestDBeaverCredentialsMissingOrBroken(t *testing.T) { + data := `{"folders":{},"connections":{"postgres-jdbc-1":{"provider":"postgresql","driver":"postgres-jdbc","name":"A","save-password":true,"configuration":{"host":"a","port":"5432","database":"x","configurationType":"MANUAL"}}}}` + + p, err := parseDBeaver(dbeaverProject(t, t.TempDir(), data, nil)) + if err != nil { + t.Fatal(err) + } + if len(p.candidates) != 1 || p.candidates[0].Profile.User != "" || len(p.passwords) != 0 { + t.Fatalf("%+v", p) + } + if len(p.notes) != 1 || !strings.Contains(p.notes[0], "secure storage") { + t.Fatalf("%v", p.notes) + } + + p, err = parseDBeaver(dbeaverProject(t, t.TempDir(), data, []byte("not encrypted at all, 32 bytes!!"))) + if err != nil { + t.Fatal(err) + } + if len(p.candidates) != 1 || len(p.notes) != 1 || !strings.Contains(p.notes[0], "could not be decrypted") { + t.Fatalf("%+v", p) + } + + // Decrypts but is not JSON. + p, err = parseDBeaver(dbeaverProject(t, t.TempDir(), data, encryptCredentials([]byte("garbage")))) + if err != nil { + t.Fatal(err) + } + if len(p.notes) == 0 || !strings.Contains(p.notes[0], "could not be decrypted") { + t.Fatalf("%v", p.notes) + } + + // Nothing saved: no note. + p, err = parseDBeaver(dbeaverProject(t, t.TempDir(), strings.ReplaceAll(data, "true", "false"), nil)) + if err != nil { + t.Fatal(err) + } + if len(p.notes) != 0 { + t.Fatalf("%v", p.notes) + } +} + +func TestDBeaverPlainPasswordInConfiguration(t *testing.T) { + data := `{"connections":{"c1":{"provider":"postgresql","driver":"postgres-jdbc","name":"Old","configuration":{"host":"h","user":"u","password":"fake-pass-6"}}}}` + p, err := parseDBeaver(dbeaverProject(t, t.TempDir(), data, nil)) + if err != nil { + t.Fatal(err) + } + if p.candidates[0].Profile.User != "u" || !p.candidates[0].Profile.SavePassword || p.passwords["c1"] != "fake-pass-6" { + t.Fatalf("%+v", p) + } +} + +func TestDBeaverMalformedInput(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "data-sources.json") + for _, bad := range []string{"", " ", "not json", "[1,2]", "{}", `{"other": 1}`, `"x"`} { + if err := os.WriteFile(path, []byte(bad), 0o644); err != nil { + t.Fatal(err) + } + _, err := parseDBeaver(path) + if !strings.Contains(errMessage(err), "DBeaver") { + t.Fatalf("%q: %v", bad, err) + } + } + // Odd types inside a valid file never panic. + odd := `{"connections": { + "a": 5, + "b": {"name": "", "configuration": "x"}, + "c": {"provider": "postgresql", "driver": "postgres-jdbc", "configuration": {"host": 7, "port": "99999", "handlers": [1], "properties": "x", "bootstrap": {"initQueries": "x"}}}, + "d": {"provider": "oracle", "configuration": {"provider-properties": {"@dbeaver-connection-type@": "TNS"}}}, + "e": {"provider": "sqlite", "configuration": {}}, + "f": {"provider": "sqlserver", "configuration": {"configurationType": "URL", "url": "jdbc:sqlserver://{host}"}}, + "g": {"provider": "mysql", "configuration": {"configurationType": "URL", "url": "jdbc:db2://x/y"}} + }, "folders": []}` + if err := os.WriteFile(path, []byte(odd), 0o644); err != nil { + t.Fatal(err) + } + p, err := parseDBeaver(path) + if err != nil { + t.Fatal(err) + } + c := find(t, p, "c") + if c.Profile.Host != "7" || c.Profile.Port != 5432 { + t.Fatalf("%+v", c.Profile) + } + if got := skipped(t, p, "a"); got != "The connection entry is not readable." { + t.Fatal(got) + } + if got := skipped(t, p, "b"); got != "The connection has no DBeaver driver." { + t.Fatal(got) + } + if got := skipped(t, p, "d"); got != "No TNS alias is set." { + t.Fatal(got) + } + if got := skipped(t, p, "e"); got != "No database file is set." { + t.Fatal(got) + } + if got := skipped(t, p, "f"); !strings.Contains(got, "template") { + t.Fatal(got) + } + if got := skipped(t, p, "g"); !strings.HasPrefix(got, "Uses a JDBC URL LowQuery cannot read") { + t.Fatal(got) + } + if len(p.candidates) != 1 { + t.Fatalf("%d candidates", len(p.candidates)) + } + if _, err := parseDBeaver(filepath.Join(dir, "missing.json")); err == nil { + t.Fatal("parsed a missing file") + } +} + +func TestDBeaverWorkspaceLayout(t *testing.T) { + dir := t.TempDir() + ws := filepath.Join(dir, "workspace6") + writeFile(t, ws, "General/.dbeaver/data-sources.json", "{}") + writeFile(t, ws, "General/.dbeaver/credentials-config.json", "x") + writeFile(t, ws, "Clients/.dbeaver/data-sources.json", "{}") + writeFile(t, ws, "Clients/.dbeaver/data-sources-2.json", "{}") + writeFile(t, ws, ".metadata/.dbeaver/data-sources.json", "{}") + if err := os.MkdirAll(filepath.Join(ws, "Empty"), 0o755); err != nil { + t.Fatal(err) + } + + files := workspaceFiles(ws, " (Snap)") + var labels []string + for _, f := range files { + labels = append(labels, f.label) + } + want := []string{ + "DBeaver (Snap) · Clients · data-sources-2.json", + "DBeaver (Snap) · Clients · data-sources.json", + "DBeaver (Snap) · General", + } + if strings.Join(labels, "|") != strings.Join(want, "|") { + t.Fatalf("%q", labels) + } + if len(workspaceFiles(filepath.Join(dir, "nope"), "")) != 0 { + t.Fatal("files in a missing workspace") + } + + // default files under a fake data folder. + fakeHome(t) + writeFile(t, dirs.data(), "DBeaverData/workspace6/General/.dbeaver/data-sources.json", "{}") + found := dbeaverFiles() + if len(found) != 1 || found[0].label != "DBeaver · General" { + t.Fatalf("%+v", found) + } +} + +func TestDBeaverCredentialsFileNames(t *testing.T) { + p := filepath.Join("x", ".dbeaver", "data-sources-2.json") + got, ok := credentialsPath(p) + if !ok || fileName(got) != "credentials-config-2.json" || filepath.Dir(got) != filepath.Dir(p) { + t.Fatal(got) + } + if got, ok := credentialsPath("data-sources.json"); !ok || got != "credentials-config.json" { + t.Fatal(got) + } + if _, ok := credentialsPath("other.json"); ok { + t.Fatal("other.json has credentials") + } +} + +func TestDBeaverColors(t *testing.T) { + for in, want := range map[string]string{ + "255,0,0": "#ff0000", + "#00FF00": "#00ff00", + "255,255,255": "", + "1,2": "", + "red": "", + } { + if got, _ := rgb(in); got != want { + t.Fatalf("%s: %q", in, got) + } + } + if got := tnsDir("/opt/oracle/tnsnames.ora"); got != "/opt/oracle" { + t.Fatal(got) + } +} + +func TestDBeaverDecryptsKnownKey(t *testing.T) { + data := encryptCredentials([]byte(`{"a":{"#connection":{"user":"u"}}}`)) + plain := decrypt(data) + if !bytes.HasPrefix(plain, []byte(`{"a"`)) { + t.Fatalf("%q", plain) + } + if decrypt(data[:20]) != nil { + t.Fatal("decrypted a cut file") + } +} diff --git a/internal/importers/helpers_test.go b/internal/importers/helpers_test.go new file mode 100644 index 0000000..a6be383 --- /dev/null +++ b/internal/importers/helpers_test.go @@ -0,0 +1,90 @@ +package importers + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// fakeHome points the importers at empty user folders in a temp dir, so no +// test reads the real tool files of this machine. It returns the home. +func fakeHome(t *testing.T) string { + t.Helper() + root := t.TempDir() + home := filepath.Join(root, "home") + config := filepath.Join(root, "config") + data := filepath.Join(root, "data") + for _, d := range []string{home, config, data} { + if err := os.MkdirAll(d, 0o755); err != nil { + t.Fatal(err) + } + } + saved := dirs + dirs.home = func() string { return home } + dirs.config = func() string { return config } + dirs.data = func() string { return data } + t.Cleanup(func() { dirs = saved }) + for _, env := range []string{"SQLITE_PATH", "PGPASSFILE", "SQLDEVELOPER_USER_DIR"} { + t.Setenv(env, "") + } + return home +} + +// writeFile writes text to rel under dir, creating folders. +func writeFile(t *testing.T, dir, rel, text string) string { + t.Helper() + path := filepath.Join(dir, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(text), 0o644); err != nil { + t.Fatal(err) + } + return path +} + +func find(t *testing.T, p *parsed, key string) *ImportCandidate { + t.Helper() + for i := range p.candidates { + if p.candidates[i].Key == key { + return &p.candidates[i] + } + } + t.Fatalf("missing %s", key) + return nil +} + +func skipped(t *testing.T, p *parsed, name string) string { + t.Helper() + for _, s := range p.skipped { + if s.Name == name { + return s.Reason + } + } + t.Fatalf("not skipped: %s", name) + return "" +} + +func anyContains(list []string, sub string) bool { + for _, s := range list { + if strings.Contains(s, sub) { + return true + } + } + return false +} + +func deref(s *string) string { + if s == nil { + return "" + } + return *s +} + +func errMessage(err error) string { + if err == nil { + return "" + } + return err.Error() +} diff --git a/internal/importers/importers.go b/internal/importers/importers.go new file mode 100644 index 0000000..015457b --- /dev/null +++ b/internal/importers/importers.go @@ -0,0 +1,322 @@ +// Package importers imports connection profiles from other database tools. +// +// Each tool finds its configuration files on this machine (defaultFiles) +// and turns one file into candidates (parse). Passwords read from a tool's +// store stay in this process: the preview only says that one exists, and +// Apply writes it straight to the OS credential store. +package importers + +import ( + "errors" + "io/fs" + "os" + "path/filepath" + "runtime" + "strings" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" + "github.com/LowBloat/LowQuery/internal/profiles" +) + +// ImportTool is the tool a file comes from. +type ImportTool string + +const ( + DBeaver ImportTool = "dbeaver" + DataGrip ImportTool = "datagrip" + PgAdmin ImportTool = "pgadmin" + SQLDeveloper ImportTool = "sql-developer" +) + +var tools = []ImportTool{DBeaver, DataGrip, PgAdmin, SQLDeveloper} + +// ImportSource is a configuration file found on this machine. +type ImportSource struct { + Tool ImportTool `json:"tool"` + // Where it comes from, such as the DBeaver project name. + Label string `json:"label"` + Path string `json:"path"` + // Connections LowQuery can import from it. + Count int `json:"count"` + Error *string `json:"error"` +} + +// ImportCandidate is one connection that can be imported. +type ImportCandidate struct { + // Stable within the file (the tool's own id when it has one). + Key string `json:"key"` + // The profile to create; ID is empty. + Profile model.ConnectionProfile `json:"profile"` + // Folder or group in the tool, shown in the preview. + Folder *string `json:"folder"` + // A password can be imported with the connection. + HasPassword bool `json:"hasPassword"` + // Settings that could not be carried over (SSH tunnels, driver + // options...). + Warnings []string `json:"warnings"` +} + +// SkippedConnection is a connection in the file that LowQuery cannot use. +type SkippedConnection struct { + Name string `json:"name"` + Reason string `json:"reason"` +} + +type ImportPreview struct { + Tool ImportTool `json:"tool"` + Path string `json:"path"` + Candidates []ImportCandidate `json:"candidates"` + Skipped []SkippedConnection `json:"skipped"` + // Notes about the whole file (for example, passwords kept in a store + // LowQuery cannot read). + Notes []string `json:"notes"` +} + +type ImportResult struct { + Created int `json:"created"` + Passwords int `json:"passwords"` +} + +// parsed is what a tool returns for one file. passwords is keyed by +// candidate key and never leaves the Go side. +type parsed struct { + candidates []ImportCandidate + skipped []SkippedConnection + notes []string + passwords map[string]string +} + +func newParsed() *parsed { return &parsed{passwords: map[string]string{}} } + +func (p *parsed) skip(name, reason string) { + p.skipped = append(p.skipped, SkippedConnection{Name: name, Reason: reason}) +} + +// source is a file found by a tool: a label and a path. +type source struct { + label string + path string +} + +func defaultFiles(tool ImportTool) []source { + switch tool { + case DBeaver: + return dbeaverFiles() + case DataGrip: + return datagripFiles() + case PgAdmin: + return pgadminFiles() + case SQLDeveloper: + return sqldeveloperFiles() + } + return nil +} + +func parse(tool ImportTool, path string) (*parsed, error) { + var p *parsed + var err error + switch tool { + case DBeaver: + p, err = parseDBeaver(path) + case DataGrip: + p, err = parseDataGrip(path) + case PgAdmin: + p, err = parsePgAdmin(path) + case SQLDeveloper: + p, err = parseSQLDeveloper(path) + default: + return nil, apperr.Invalidf("Unknown import tool %q.", string(tool)) + } + if err != nil { + return nil, err + } + for i := range p.candidates { + c := &p.candidates[i] + c.Profile.ID = "" + if strings.TrimSpace(c.Profile.Name) == "" { + c.Profile.Name = c.Profile.Host + } + _, c.HasPassword = p.passwords[c.Key] + if c.Warnings == nil { + c.Warnings = []string{} + } + } + return p, nil +} + +// Detect lists the configuration files of every supported tool found on +// this machine. +func Detect() []ImportSource { + out := []ImportSource{} + for _, tool := range tools { + for _, f := range defaultFiles(tool) { + src := ImportSource{Tool: tool, Label: f.label, Path: f.path} + if p, err := parse(tool, f.path); err != nil { + msg := apperr.From(err).Message + src.Error = &msg + } else { + src.Count = len(p.candidates) + } + out = append(out, src) + } + } + return out +} + +// Preview reads one tool file and lists what can be imported (without +// passwords). +func Preview(tool ImportTool, path string) (*ImportPreview, error) { + p, err := parse(tool, path) + if err != nil { + return nil, err + } + out := &ImportPreview{ + Tool: tool, + Path: path, + Candidates: p.candidates, + Skipped: p.skipped, + Notes: p.notes, + } + if out.Candidates == nil { + out.Candidates = []ImportCandidate{} + } + if out.Skipped == nil { + out.Skipped = []SkippedConnection{} + } + if out.Notes == nil { + out.Notes = []string{} + } + return out, nil +} + +// Apply creates the profiles of the chosen candidates. The file is read +// again so passwords never travel through the interface. +func Apply(store *profiles.Store, tool ImportTool, path string, keys []string, withPasswords bool) (*ImportResult, error) { + p, err := parse(tool, path) + if err != nil { + return nil, err + } + result := &ImportResult{} + for _, key := range keys { + var c *ImportCandidate + for i := range p.candidates { + if p.candidates[i].Key == key { + c = &p.candidates[i] + break + } + } + if c == nil { + return nil, apperr.New(apperr.Invalid, + "The file changed since it was read. Open it again to import.") + } + var password *string + if withPasswords { + if pw, ok := p.passwords[key]; ok { + password = &pw + delete(p.passwords, key) + } + } + profile := c.Profile + profile.SavePassword = profile.SavePassword || password != nil + if password != nil { + result.Passwords++ + } + if _, err := store.Save(profile, password); err != nil { + return nil, err + } + result.Created++ + } + return result, nil +} + +// dirs are the user folders the importers search; tests replace them. +var dirs = struct { + // The user's home directory. + home func() string + // Roaming application data on Windows, ~/Library/Application Support + // on macOS and $XDG_CONFIG_HOME (or ~/.config) on Linux. + config func() string + // %APPDATA% on Windows, ~/Library/Application Support on macOS and + // $XDG_DATA_HOME (or ~/.local/share) on Linux. + data func() string +}{userHome, userConfig, userData} + +func userHome() string { + h, err := os.UserHomeDir() + if err != nil { + return "" + } + return h +} + +func userConfig() string { + if runtime.GOOS == "linux" || runtime.GOOS == "freebsd" || runtime.GOOS == "openbsd" || runtime.GOOS == "netbsd" { + return xdg("XDG_CONFIG_HOME", ".config") + } + d, err := os.UserConfigDir() + if err != nil { + return "" + } + return d +} + +func userData() string { + switch runtime.GOOS { + case "windows", "darwin", "ios": + return userConfig() + } + return xdg("XDG_DATA_HOME", filepath.Join(".local", "share")) +} + +// xdg is an absolute XDG folder variable, else the folder under home. +func xdg(env, fallback string) string { + if d := os.Getenv(env); filepath.IsAbs(d) { + return d + } + if h := userHome(); h != "" { + return filepath.Join(h, fallback) + } + return "" +} + +func isFile(path string) bool { + st, err := os.Stat(path) + return err == nil && st.Mode().IsRegular() +} + +func isDir(path string) bool { + st, err := os.Stat(path) + return err == nil && st.IsDir() +} + +func exists(path string) bool { + _, err := os.Stat(path) + return err == nil +} + +// fileID identifies a file for de-duplication: the resolved path, with +// forward slashes, lowercase where file names ignore case. +func fileID(path string, fold bool) string { + id := path + if r, err := filepath.EvalSymlinks(path); err == nil { + if abs, err := filepath.Abs(r); err == nil { + id = abs + } + } + id = strings.ReplaceAll(id, `\`, "/") + if fold { + id = strings.ToLower(id) + } + return id +} + +// ioError is an I/O failure as the Rust io::Error read: the OS message +// without the operation and path. +func ioError(err error) *apperr.Error { + var pe *fs.PathError + if errors.As(err, &pe) { + err = pe.Err + } + return apperr.New(apperr.Internal, err.Error()) +} diff --git a/internal/importers/importers_test.go b/internal/importers/importers_test.go new file mode 100644 index 0000000..c227ab9 --- /dev/null +++ b/internal/importers/importers_test.go @@ -0,0 +1,125 @@ +package importers + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/profiles" +) + +const twoServers = `{"Servers": { + "1": {"Name": "", "Host": "pg.local", "Port": 5432, "MaintenanceDB": "app", "Username": "app"}, + "2": {"Name": "B", "Group": "Prod", "Host": "b.local", "Port": 5433, "MaintenanceDB": "b", "Username": "b"} +}}` + +func TestDetectFindsFilesOfEveryTool(t *testing.T) { + home := fakeHome(t) + writeFile(t, dirs.data(), "DBeaverData/workspace6/General/.dbeaver/data-sources.json", "not json") + writeFile(t, home, "DataGripProjects/shop/.idea/dataSources.xml", datagripProject) + writeFile(t, home, ".sqldeveloper/system23.1.0.097.1607/o.jdeveloper.db.connection/connections.json", sqldevJSON) + pg := writeFile(t, t.TempDir(), "servers.json", twoServers) + t.Setenv("SQLITE_PATH", pg) + + got := map[ImportTool]ImportSource{} + for _, s := range Detect() { + got[s.Tool] = s + } + if s := got[DBeaver]; s.Error == nil || !strings.Contains(*s.Error, "DBeaver") || s.Count != 0 { + t.Fatalf("%+v", s) + } + if s := got[DataGrip]; s.Error != nil || s.Count != 12 || s.Label != "DataGrip · shop" { + t.Fatalf("%+v", s) + } + if s := got[PgAdmin]; s.Error != nil || s.Count != 2 || s.Path != pg { + t.Fatalf("%+v", s) + } + if s := got[SQLDeveloper]; s.Error != nil || s.Count == 0 || s.Label != "SQL Developer 23.1" { + t.Fatalf("%+v", s) + } + + data, err := json.Marshal(got[PgAdmin]) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(data), `"tool":"pgadmin"`) || !strings.Contains(string(data), `"error":null`) { + t.Fatal(string(data)) + } + data, _ = json.Marshal(got[SQLDeveloper].Tool) + if string(data) != `"sql-developer"` { + t.Fatal(string(data)) + } +} + +func TestPreviewShape(t *testing.T) { + path := writeFile(t, t.TempDir(), "servers.json", twoServers) + p, err := Preview(PgAdmin, path) + if err != nil { + t.Fatal(err) + } + // An empty name falls back to the host. + if p.Candidates[0].Profile.Name != "pg.local" || p.Candidates[0].Profile.ID != "" { + t.Fatalf("%+v", p.Candidates[0].Profile) + } + data, err := json.Marshal(p) + if err != nil { + t.Fatal(err) + } + var doc map[string]any + if err := json.Unmarshal(data, &doc); err != nil { + t.Fatal(err) + } + for _, k := range []string{"tool", "path", "candidates", "skipped", "notes"} { + if _, ok := doc[k]; !ok { + t.Fatalf("missing %s: %s", k, data) + } + } + if doc["skipped"] == nil { + t.Fatal("skipped is null") + } + c := doc["candidates"].([]any)[0].(map[string]any) + for _, k := range []string{"key", "profile", "folder", "hasPassword", "warnings"} { + if _, ok := c[k]; !ok { + t.Fatalf("missing %s: %s", k, data) + } + } + if c["folder"] != nil || c["warnings"] == nil { + t.Fatalf("%s", data) + } + + if _, err := Preview("nope", path); apperr.From(err).Kind != apperr.Invalid { + t.Fatal(err) + } + if _, err := Preview(DBeaver, path); apperr.From(err).Message != "This is not a DBeaver data-sources.json file." { + t.Fatal(err) + } +} + +func TestApplyCreatesProfiles(t *testing.T) { + store, err := profiles.NewStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + path := writeFile(t, t.TempDir(), "servers.json", twoServers) + // No passwords: the credential store is not touched. + res, err := Apply(store, PgAdmin, path, []string{"server-2", "server-1"}, false) + if err != nil { + t.Fatal(err) + } + if res.Created != 2 || res.Passwords != 0 { + t.Fatalf("%+v", res) + } + all, err := store.List() + if err != nil { + t.Fatal(err) + } + if len(all) != 2 || all[0].Name != "B" || all[1].Name != "pg.local" || all[0].ID == "" || all[0].Port != 5433 { + t.Fatalf("%+v", all) + } + + _, err = Apply(store, PgAdmin, path, []string{"server-9"}, false) + if e := apperr.From(err); e.Kind != apperr.Invalid || e.Message != "The file changed since it was read. Open it again to import." { + t.Fatal(err) + } +} diff --git a/internal/importers/jdbc.go b/internal/importers/jdbc.go new file mode 100644 index 0000000..c01c057 --- /dev/null +++ b/internal/importers/jdbc.go @@ -0,0 +1,442 @@ +package importers + +// JDBC URLs, the common address format of Java database tools. + +import ( + "errors" + "strings" + + "github.com/LowBloat/LowQuery/internal/model" +) + +// applyURL fills engine, address, database and TLS settings of p from a +// JDBC URL. The error is a short reason when the URL is not one LowQuery +// can use. +func applyURL(url string, p *model.ConnectionProfile) error { + url = strings.TrimSpace(url) + rest, ok := stripPrefixFold(url, "jdbc:") + if !ok { + return errors.New("not a JDBC URL") + } + if r, ok := stripPrefixFold(rest, "postgresql:"); ok { + return hostDB(r, model.Postgres, 5432, p, pgParams) + } + if r, ok := stripPrefixFold(rest, "mysql:"); ok { + return hostDB(r, model.MySQL, 3306, p, mysqlParams) + } + if r, ok := stripPrefixFold(rest, "mariadb:"); ok { + return hostDB(r, model.MariaDB, 3306, p, mysqlParams) + } + if r, ok := stripPrefixFold(rest, "sqlserver:"); ok { + sqlserverURL(r, p) + return nil + } + if r, ok := stripPrefixFold(rest, "jtds:sqlserver:"); ok { + return jtdsURL(r, p) + } + if r, ok := stripPrefixFold(rest, "oracle:thin:"); ok { + oracleURL(r, p) + return nil + } + if r, ok := stripPrefixFold(rest, "sqlite:"); ok { + p.Engine = model.SQLite + path, _ := splitOr(r, "?") + if path == "" || path == ":memory:" { + return errors.New("in-memory SQLite databases cannot be imported") + } + p.Database = path + p.Host = "" + p.Port = 0 + return nil + } + if r, ok := stripPrefixFold(rest, "cassandra:"); ok { + return cassandraURL(r, p) + } + scheme, _ := splitOr(rest, ":") + return errors.New(scheme + " URLs are not supported") +} + +// cassandraURL reads //host1[:port][,host2...][/keyspace][?params] +// (Cassandra JDBC wrappers also join the hosts with "--"). The contact +// points stay in Host, comma-separated; the port is the first one given. +// Cassandra's native protocol is plain text unless the URL asks for TLS. +func cassandraURL(rest string, p *model.ConnectionProfile) error { + p.Engine = model.Cassandra + r, ok := strings.CutPrefix(rest, "//") + if !ok { + return errors.New("missing //host") + } + main, query := splitOr(r, "?") + hosts, keyspace := splitOr(main, "/") + var port uint16 + var points []string + for _, a := range strings.FieldsFunc(hosts, func(r rune) bool { return r == ',' || r == ';' }) { + for _, h := range strings.Split(a, "--") { + h = strings.TrimSpace(h) + if h == "" { + continue + } + host, hp := splitHostPort(h, 0) + if port == 0 && hp != 0 { + port = hp + } + points = append(points, host) + } + } + if len(points) == 0 { + p.Host = "localhost" + } else { + p.Host = strings.Join(points, ",") + } + if port == 0 { + port = 9042 + } + p.Port = port + p.Database = percentDecode(keyspace) + p.SslMode = model.SslDisable + forEachParam(query, func(k, v string) { cassandraParams(k, percentDecode(v), p) }) + return nil +} + +func cassandraParams(k, v string, p *model.ConnectionProfile) { + switch lowerASCII(k) { + case "localdc", "localdatacenter", "datacenter": + if v != "" { + p.Datacenter = v + } + case "ssl", "usessl", "enablessl", "tls": + if eqFold(v, "true") { + p.SslMode = model.SslRequire + } + case "user", "username": + if p.User == "" { + p.User = v + } + } +} + +// forEachParam calls f with each key=value pair of a query string (the +// value is empty without '='). +func forEachParam(query string, f func(k, v string)) { + for _, pair := range strings.Split(query, "&") { + if pair == "" { + continue + } + k, v := splitOr(pair, "=") + f(k, v) + } +} + +// splitHostPort splits host[:port], including [ipv6]:port. +func splitHostPort(s string, defaultPort uint16) (string, uint16) { + s = strings.TrimSpace(s) + if r, ok := strings.CutPrefix(s, "["); ok { + if h, tail, ok := splitOnce(r, "]"); ok { + port := defaultPort + if ps, ok := strings.CutPrefix(tail, ":"); ok { + if n, ok := parseU16(ps); ok { + port = n + } + } + return h, port + } + } + if h, ps, ok := rsplitOnce(s, ":"); ok && !strings.Contains(h, ":") { + if n, ok := parseU16(ps); ok { + return h, n + } + } + return s, defaultPort +} + +// hostDB reads //host[:port][,host2...][/database][?params]. +func hostDB(rest string, engine model.Engine, defaultPort uint16, p *model.ConnectionProfile, + params func(k, v string, p *model.ConnectionProfile)) error { + p.Engine = engine + r, ok := strings.CutPrefix(rest, "//") + if !ok { + return errors.New("missing //host") + } + main, query := splitOr(r, "?") + hosts, db := splitOr(main, "/") + // Failover lists keep the first host. + first, _ := splitOr(hosts, ",") + host, port := splitHostPort(first, defaultPort) + if host == "" { + host = "localhost" + } + p.Host = host + p.Port = port + p.Database = percentDecode(db) + forEachParam(query, func(k, v string) { params(k, percentDecode(v), p) }) + return nil +} + +func pgParams(k, v string, p *model.ConnectionProfile) { + switch k { + case "sslmode": + if mode, ok := pgSslMode(v); ok { + p.SslMode = mode + } + case "ssl": + if eqFold(v, "true") && p.SslMode == model.SslPrefer { + p.SslMode = model.SslRequire + } + case "user": + if p.User == "" { + p.User = v + } + } +} + +// pgSslMode maps libpq sslmode names (also used by pgAdmin and DBeaver). +func pgSslMode(v string) (model.SslMode, bool) { + switch lowerASCII(v) { + case "disable", "allow": + return model.SslDisable, true + case "prefer": + return model.SslPrefer, true + case "require", "verify-ca": + return model.SslRequire, true + case "verify-full": + return model.SslVerifyFull, true + } + return "", false +} + +func mysqlParams(k, v string, p *model.ConnectionProfile) { + switch lowerASCII(k) { + case "sslmode": + p.SslMode = mysqlSslMode(v) + case "usessl": + if eqFold(v, "true") { + p.SslMode = model.SslRequire + } else { + p.SslMode = model.SslDisable + } + case "user": + if p.User == "" { + p.User = v + } + } +} + +// mysqlSslMode maps MySQL Connector/J sslMode values. +func mysqlSslMode(v string) model.SslMode { + switch upperASCII(v) { + case "DISABLED": + return model.SslDisable + case "REQUIRED", "VERIFY_CA": + return model.SslRequire + case "VERIFY_IDENTITY": + return model.SslVerifyFull + } + return model.SslPrefer +} + +// sqlserverURL reads //host[\instance][:port][;key=value...]. +func sqlserverURL(rest string, p *model.ConnectionProfile) { + p.Engine = model.SQLServer + r := strings.TrimPrefix(rest, "//") + parts := strings.Split(r, ";") + server, port := splitHostPort(parts[0], 1433) + host, instance := splitOr(server, `\`) + if host == "" { + host = "localhost" + } + p.Host = host + p.Port = port + p.Instance = instance + var encrypt *bool + trust := false + for _, kv := range parts[1:] { + if kv == "" { + continue + } + k, v := splitOr(kv, "=") + v = strings.TrimSpace(v) + switch lowerASCII(strings.TrimSpace(k)) { + case "databasename", "database": + p.Database = v + case "instancename": + p.Instance = v + case "portnumber", "port": + if n, ok := parseU16(v); ok { + p.Port = n + } + case "integratedsecurity": + p.WindowsAuth = eqFold(v, "true") + case "encrypt": + on := sqlserverEncrypt(v) + encrypt = &on + case "trustservercertificate": + trust = eqFold(v, "true") + case "user": + if p.User == "" { + p.User = v + } + } + } + p.SslMode = sqlserverSsl(encrypt, trust) +} + +// sqlserverEncrypt reads the driver's encrypt value. +func sqlserverEncrypt(v string) bool { + switch lowerASCII(v) { + case "true", "mandatory", "strict": + return true + } + return false +} + +// sqlserverSsl maps the Microsoft driver's encrypt / trustServerCertificate +// to LowQuery modes. The driver encrypts by default since version 10. +func sqlserverSsl(encrypt *bool, trustServerCertificate bool) model.SslMode { + switch { + case encrypt != nil && !*encrypt: + return model.SslPrefer + case trustServerCertificate: + return model.SslRequire + case encrypt != nil: + return model.SslVerifyFull + } + return model.SslPrefer +} + +// jtdsURL reads //host[:port][/database][;instance=x;...]. +func jtdsURL(rest string, p *model.ConnectionProfile) error { + p.Engine = model.SQLServer + r, ok := strings.CutPrefix(rest, "//") + if !ok { + return errors.New("missing //host") + } + parts := strings.Split(r, ";") + server, db := splitOr(parts[0], "/") + host, port := splitHostPort(server, 1433) + p.Host = host + p.Port = port + p.Database = db + for _, kv := range parts[1:] { + k, v := splitOr(kv, "=") + switch lowerASCII(k) { + case "instance": + p.Instance = v + case "user": + if p.User == "" { + p.User = v + } + } + } + return nil +} + +// oracleURL reads the thin driver address after jdbc:oracle:thin:: +// [user/pass]@host:port:SID, @//host:port/service, @host:port/service, a +// descriptor, an Easy Connect Plus string or a TNS alias. +func oracleURL(rest string, p *model.ConnectionProfile) { + p.Engine = model.Oracle + target := strings.TrimSpace(rest) + if creds, t, ok := splitOnce(rest, "@"); ok { + if user, _, ok := splitOnce(creds, "/"); ok && p.User == "" { + p.User = user + } + target = strings.TrimSpace(t) + } + applyOracleTarget(target, p) +} + +// applyOracleTarget sets the Oracle connect type and fields from an address +// written the way Oracle tools accept it. +func applyOracleTarget(target string, p *model.ConnectionProfile) { + p.Engine = model.Oracle + t := strings.TrimSpace(target) + custom := func() { + p.OracleConnectType = model.OracleCustom + p.ConnectString = t + } + if strings.HasPrefix(t, "(") || strings.Contains(t, "://") || strings.Contains(t, "?") { + custom() + return + } + firstPart := func(s string) string { + if i := strings.IndexAny(s, "/:"); i >= 0 { + return s[:i] + } + return s + } + if r, ok := strings.CutPrefix(t, "//"); ok { + // //host[:port]/service[:server][/instance] + addr, service := splitOr(r, "/") + host, port := splitHostPort(addr, 1521) + p.OracleConnectType = model.OracleService + p.Host = host + p.Port = port + p.Database = firstPart(service) + return + } + if !strings.ContainsAny(t, ":/") { + // A bare name is a TNS alias. + p.OracleConnectType = model.OracleTNS + p.TnsAlias = t + return + } + if addr, service, ok := splitOnce(t, "/"); ok { + host, port := splitHostPort(addr, 1521) + p.OracleConnectType = model.OracleService + p.Host = host + p.Port = port + p.Database = firstPart(service) + return + } + // host:port:SID + if parts := strings.Split(t, ":"); len(parts) == 3 { + if port, ok := parseU16(parts[1]); ok { + p.OracleConnectType = model.OracleSID + p.Host = parts[0] + p.Port = port + p.Database = parts[2] + return + } + } + custom() +} + +func percentDecode(s string) string { + out := make([]byte, 0, len(s)) + for i := 0; i < len(s); i++ { + if s[i] == '%' && i+2 < len(s) { + if b, ok := hexByte(s[i+1 : i+3]); ok { + out = append(out, b) + i += 2 + continue + } + } + out = append(out, s[i]) + } + return lossy(out) +} + +// hexByte is u8::from_str_radix(h, 16) for a two-character h. +func hexByte(h string) (byte, bool) { + var n byte + digits := h + if digits[0] == '+' { + digits = digits[1:] + } + for i := 0; i < len(digits); i++ { + c := digits[i] + var d byte + switch { + case '0' <= c && c <= '9': + d = c - '0' + case 'a' <= c && c <= 'f': + d = c - 'a' + 10 + case 'A' <= c && c <= 'F': + d = c - 'A' + 10 + default: + return 0, false + } + n = n*16 + d + } + return n, true +} diff --git a/internal/importers/jdbc_test.go b/internal/importers/jdbc_test.go new file mode 100644 index 0000000..82efe5a --- /dev/null +++ b/internal/importers/jdbc_test.go @@ -0,0 +1,143 @@ +package importers + +import ( + "strings" + "testing" + + "github.com/LowBloat/LowQuery/internal/model" +) + +func parseURL(t *testing.T, url string) model.ConnectionProfile { + t.Helper() + p := model.DefaultProfile() + if err := applyURL(url, &p); err != nil { + t.Fatalf("%s: %v", url, err) + } + return p +} + +func TestJDBCPostgresAndMySQL(t *testing.T) { + p := parseURL(t, "jdbc:postgresql://db.internal:5433/sales?sslmode=verify-full&user=ana") + if p.Engine != model.Postgres || p.Host != "db.internal" || p.Port != 5433 { + t.Fatalf("%+v", p) + } + if p.Database != "sales" || p.SslMode != model.SslVerifyFull || p.User != "ana" { + t.Fatalf("%+v", p) + } + p = parseURL(t, "jdbc:postgresql://a,b:5432/x") + if p.Host != "a" || p.Port != 5432 { + t.Fatalf("%+v", p) + } + p = parseURL(t, "jdbc:mysql://[::1]:3307/shop?useSSL=false") + if p.Engine != model.MySQL || p.Host != "::1" || p.Port != 3307 || p.SslMode != model.SslDisable { + t.Fatalf("%+v", p) + } + p = parseURL(t, "jdbc:mariadb://m/db%20x") + if p.Engine != model.MariaDB || p.Port != 3306 || p.Database != "db x" { + t.Fatalf("%+v", p) + } +} + +func TestJDBCSQLServerForms(t *testing.T) { + p := parseURL(t, `jdbc:sqlserver://fin-sql\REPORTING;databaseName=Finance;integratedSecurity=true;encrypt=true;trustServerCertificate=true`) + if p.Engine != model.SQLServer || p.Host != "fin-sql" || p.Instance != "REPORTING" { + t.Fatalf("%+v", p) + } + if p.Database != "Finance" || !p.WindowsAuth || p.SslMode != model.SslRequire { + t.Fatalf("%+v", p) + } + p = parseURL(t, "jdbc:sqlserver://h:1500;database=d;encrypt=false") + if p.Port != 1500 || p.Database != "d" || p.SslMode != model.SslPrefer { + t.Fatalf("%+v", p) + } + p = parseURL(t, "jdbc:jtds:sqlserver://h:1433/db;instance=SQLEXPRESS") + if p.Database != "db" || p.Instance != "SQLEXPRESS" { + t.Fatalf("%+v", p) + } +} + +func TestJDBCOracleForms(t *testing.T) { + p := parseURL(t, "jdbc:oracle:thin:@erp:1521:ERPPRD") + if p.OracleConnectType != model.OracleSID || p.Host != "erp" || p.Port != 1521 || p.Database != "ERPPRD" { + t.Fatalf("%+v", p) + } + p = parseURL(t, "jdbc:oracle:thin:@//erp.internal:1522/erppdb") + if p.OracleConnectType != model.OracleService || p.Host != "erp.internal" || p.Port != 1522 || p.Database != "erppdb" { + t.Fatalf("%+v", p) + } + p = parseURL(t, "jdbc:oracle:thin:@erp/erppdb") + if p.Port != 1521 || p.Database != "erppdb" { + t.Fatalf("%+v", p) + } + p = parseURL(t, "jdbc:oracle:thin:@ERPPRD") + if p.OracleConnectType != model.OracleTNS || p.TnsAlias != "ERPPRD" { + t.Fatalf("%+v", p) + } + d := "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=h)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=s)))" + p = parseURL(t, "jdbc:oracle:thin:@"+d) + if p.OracleConnectType != model.OracleCustom || p.ConnectString != d { + t.Fatalf("%+v", p) + } + p = parseURL(t, "jdbc:oracle:thin:scott/tiger@h:1521:X") + if p.User != "scott" { + t.Fatalf("%+v", p) + } +} + +func TestJDBCCassandraForms(t *testing.T) { + p := parseURL(t, "jdbc:cassandra://10.0.0.1:9043,10.0.0.2/shop?localdc=dc1&user=ana") + if p.Engine != model.Cassandra || p.Host != "10.0.0.1,10.0.0.2" || p.Port != 9043 { + t.Fatalf("%+v", p) + } + if p.Database != "shop" || p.Datacenter != "dc1" || p.User != "ana" || p.SslMode != model.SslDisable { + t.Fatalf("%+v", p) + } + p = parseURL(t, "jdbc:cassandra://a--b--c/?ssl=true&localdatacenter=eu") + if p.Host != "a,b,c" || p.Port != 9042 || p.Database != "" || p.Datacenter != "eu" || p.SslMode != model.SslRequire { + t.Fatalf("%+v", p) + } + p = parseURL(t, "jdbc:cassandra://[::1]:9142/ks%201") + if p.Host != "::1" || p.Port != 9142 || p.Database != "ks 1" { + t.Fatalf("%+v", p) + } + p = parseURL(t, "jdbc:cassandra://") + if p.Host != "localhost" || p.Port != 9042 { + t.Fatalf("%+v", p) + } + q := model.DefaultProfile() + if applyURL("jdbc:cassandra:host/ks", &q) == nil { + t.Fatal("accepted a Cassandra URL without //") + } +} + +func TestJDBCSQLiteAndUnsupported(t *testing.T) { + p := parseURL(t, `jdbc:sqlite:C:\data\app.db`) + if p.Engine != model.SQLite || p.Database != `C:\data\app.db` { + t.Fatalf("%+v", p) + } + q := model.DefaultProfile() + if err := applyURL("jdbc:db2://h:50000/x", &q); err == nil || !strings.Contains(err.Error(), "db2") { + t.Fatalf("db2: %v", err) + } + if applyURL("jdbc:sqlite::memory:", &q) == nil { + t.Fatal("accepted an in-memory SQLite URL") + } + if applyURL("postgres://h/x", &q) == nil { + t.Fatal("accepted a non-JDBC URL") + } +} + +func TestJDBCSmallParsers(t *testing.T) { + if h, p := splitHostPort("h:+12", 1); h != "h" || p != 12 { + t.Fatalf("%s %d", h, p) + } + if h, p := splitHostPort("h:x", 7); h != "h:x" || p != 7 { + t.Fatalf("%s %d", h, p) + } + if got := percentDecode("a%2"); got != "a%2" { + t.Fatal(got) + } + if got := percentDecode("%41%zz"); got != "A%zz" { + t.Fatal(got) + } +} diff --git a/internal/importers/pgadmin.go b/internal/importers/pgadmin.go new file mode 100644 index 0000000..03561d6 --- /dev/null +++ b/internal/importers/pgadmin.go @@ -0,0 +1,670 @@ +package importers + +// pgAdmin 4: the servers.json export (Tools > Import/Export Servers) and +// the desktop configuration database pgadmin4.db (server and servergroup +// tables), read without writing to it. Saved passwords are encrypted with +// the pgAdmin master password and are not imported; a passfile (pgpass +// format) set on a server is read. + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "time" + + "github.com/ncruces/go-sqlite3" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" + "github.com/LowBloat/LowQuery/internal/ojson" +) + +// pgadminFiles: DATA_DIR of desktop mode in pgAdmin's config.py is +// %APPDATA%\pgAdmin on Windows and ~/.pgadmin elsewhere. SQLITE_PATH +// overrides the file. +func pgadminFiles() []source { + var candidates []string + if p := os.Getenv("SQLITE_PATH"); p != "" { + candidates = append(candidates, p) + } + if runtime.GOOS == "windows" { + if dir := dirs.config(); dir != "" { + candidates = append(candidates, filepath.Join(dir, "pgAdmin", "pgadmin4.db")) + } + } else if home := dirs.home(); home != "" { + candidates = append(candidates, filepath.Join(home, ".pgadmin", "pgadmin4.db")) + } + seen := map[string]bool{} + var out []source + for _, p := range candidates { + if !isFile(p) { + continue + } + id := fileID(p, true) + if seen[id] { + continue + } + seen[id] = true + out = append(out, source{"pgAdmin 4", p}) + } + return out +} + +const pgadminNotOurs = "This is not a pgAdmin 4 servers.json export or pgadmin4.db file." + +func parsePgAdmin(path string) (*parsed, error) { + f, err := os.Open(path) + if err != nil { + return nil, ioError(err) + } + head := make([]byte, 16) + n, err := io.ReadFull(f, head) + f.Close() + if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) { + return nil, ioError(err) + } + isSQLite := n == 16 && string(head) == "SQLite format 3\x00" + var servers []pgServer + if isSQLite { + servers, err = readPgAdminDB(path) + } else { + servers, err = readServersJSON(path) + } + if err != nil { + return nil, err + } + out := newParsed() + for _, s := range servers { + pgadminConvert(s, out) + } + if len(out.candidates) > len(out.passwords) { + if isSQLite { + out.notes = append(out.notes, "pgAdmin encrypts saved passwords with its master password, so LowQuery does not import them: type them on first connect.") + } else { + out.notes = append(out.notes, "pgAdmin exports do not include passwords: type them on first connect.") + } + } + return out, nil +} + +// pgServer is one server as both formats describe it. Empty strings stand +// for missing values. +type pgServer struct { + key string + name string + group string + host string + port *int64 + database string + user string + sharedUser string + role string + bgcolor string + service string + ssh bool + tunnelHost string + kerberos bool + passexec string + postSQL string + savePassword *bool + // libpq parameters (sslmode, hostaddr, passfile, sslcert...). + params *ojson.Object +} + +func readServersJSON(path string) ([]pgServer, error) { + text, err := readText(path) + if err != nil { + return nil, err + } + v, err := ojson.Parse([]byte(text)) + if err != nil { + return nil, apperr.New(apperr.Invalid, pgadminNotOurs) + } + servers := ojson.Obj(v).Field("Servers") + if servers == nil { + return nil, apperr.New(apperr.Invalid, pgadminNotOurs) + } + var out []pgServer + for _, id := range servers.Keys() { + o := servers.Field(id) + if o == nil { + continue + } + txt := func(k string) string { return valueText(o.Get(k)) } + params := o.Field("ConnectionParameters") + if params == nil { + params = ojson.NewObject() + } + // Before pgAdmin 6.0 libpq settings were top-level keys. + for _, m := range [][2]string{ + {"SSLMode", "sslmode"}, + {"HostAddr", "hostaddr"}, + {"PassFile", "passfile"}, + {"SSLCert", "sslcert"}, + {"SSLKey", "sslkey"}, + {"SSLRootCert", "sslrootcert"}, + } { + if v := txt(m[0]); v != "" && !params.Has(m[1]) { + params.Set(m[1], v) + } + } + out = append(out, pgServer{ + key: "server-" + id, + name: txt("Name"), + group: txt("Group"), + host: txt("Host"), + port: valueInt(o.Get("Port")), + database: txt("MaintenanceDB"), + user: txt("Username"), + sharedUser: txt("SharedUsername"), + role: txt("Role"), + bgcolor: txt("BGColor"), + service: txt("Service"), + ssh: pgTruthy(o.Get("UseSSHTunnel")), + tunnelHost: txt("TunnelHost"), + kerberos: pgTruthy(o.Get("KerberosAuthentication")), + passexec: txt("PasswordExecCommand"), + postSQL: txt("PostConnectionSQL"), + params: params, + }) + } + return out, nil +} + +// valueText is a JSON scalar as trimmed text; empty for anything else. +func valueText(v any) string { + switch v.(type) { + case string, json.Number, bool: + return text(v) + } + return "" +} + +func valueInt(v any) *int64 { + switch t := v.(type) { + case json.Number: + if n, err := strconv.ParseInt(t.String(), 10, 64); err == nil { + return &n + } + case string: + if n, ok := parseI64(strings.TrimSpace(t)); ok { + return &n + } + } + return nil +} + +func pgTruthy(v any) bool { + switch t := v.(type) { + case bool: + return t + case json.Number: + n, err := strconv.ParseInt(t.String(), 10, 64) + return err == nil && n != 0 + case string: + s := lowerASCII(strings.TrimSpace(t)) + return s == "1" || s == "true" + } + return false +} + +// pgadminColumns are read from server; missing ones (older schemas) read as +// NULL. +var pgadminColumns = []string{ + "id", + "servergroup_id", + "name", + "host", + "port", + "maintenance_db", + "username", + "shared_username", + "role", + "bgcolor", + "service", + "use_ssh_tunnel", + "tunnel_host", + "kerberos_conn", + "passexec_cmd", + "post_connection_sql", + "save_password", + "connection_params", + "is_adhoc", + // Before connection_params (schema 30, pgAdmin 6.0). + "ssl_mode", + "hostaddr", + "passfile", + "sslcert", + "sslkey", + "sslrootcert", +} + +func readPgAdminDB(path string) ([]pgServer, error) { + servers, ok, err := queryPgAdminFile(path, false) + if err != nil && isBusy(err) { + // A running pgAdmin may hold a write lock: read the file as it is. + servers, ok, err = queryPgAdminFile(path, true) + } + if err != nil { + if errors.Is(err, sqlite3.NOTADB) { + return nil, apperr.New(apperr.Invalid, pgadminNotOurs) + } + return nil, apperr.Internalf("pgAdmin's database could not be read: %v", err) + } + if !ok { + return nil, apperr.New(apperr.Invalid, pgadminNotOurs) + } + return servers, nil +} + +func isBusy(err error) bool { + return errors.Is(err, sqlite3.BUSY) || errors.Is(err, sqlite3.LOCKED) +} + +func queryPgAdminFile(path string, immutable bool) ([]pgServer, bool, error) { + name := path + if immutable { + name = fileURI(path, "immutable=1") + // The Go VFS opens the URI path as it is: "/C:/x" is not a Windows + // path, "C:/x" is. + if rest, ok := strings.CutPrefix(name, "file:///"); ok && runtime.GOOS == "windows" && + len(rest) >= 2 && rest[1] == ':' { + name = "file:" + rest + } + } + conn, err := sqlite3.OpenFlags(name, sqlite3.OPEN_READONLY|sqlite3.OPEN_URI) + if err != nil { + return nil, false, err + } + defer conn.Close() + if err := conn.BusyTimeout(500 * time.Millisecond); err != nil { + return nil, false, err + } + return queryPgAdmin(conn) +} + +// fileURI is a file: URI for SQLite with the reserved characters escaped. +func fileURI(path, query string) string { + var b strings.Builder + b.WriteString("file:") + p := strings.ReplaceAll(path, `\`, "/") + if strings.HasPrefix(p, "/") { + b.WriteString("//") + } else { + b.WriteString("///") + } + for _, c := range p { + switch c { + case '%': + b.WriteString("%25") + case '?': + b.WriteString("%3f") + case '#': + b.WriteString("%23") + case ' ': + b.WriteString("%20") + default: + b.WriteRune(c) + } + } + b.WriteByte('?') + b.WriteString(query) + return b.String() +} + +// sqlValue is one column value: nil, int64, float64, string or []byte. +type sqlValue any + +func readValue(st *sqlite3.Stmt, i int) sqlValue { + switch st.ColumnType(i) { + case sqlite3.INTEGER: + return st.ColumnInt64(i) + case sqlite3.FLOAT: + return st.ColumnFloat(i) + case sqlite3.TEXT: + return st.ColumnText(i) + case sqlite3.BLOB: + return append([]byte(nil), st.ColumnRawBlob(i)...) + } + return nil +} + +// queryRows runs sql and calls row for each result row. +func queryRows(conn *sqlite3.Conn, sql string, row func(*sqlite3.Stmt)) error { + st, _, err := conn.Prepare(sql) + if err != nil { + return err + } + defer st.Close() + for st.Step() { + row(st) + } + return st.Err() +} + +// queryPgAdmin reads the servers; ok is false when the database has no +// pgAdmin server table. +func queryPgAdmin(conn *sqlite3.Conn) ([]pgServer, bool, error) { + present := map[string]bool{} + err := queryRows(conn, "SELECT name FROM pragma_table_info('server')", func(st *sqlite3.Stmt) { + present[st.ColumnText(0)] = true + }) + if err != nil { + return nil, false, err + } + if !present["name"] || !present["id"] { + return nil, false, nil + } + groups := map[int64]string{} + hasGroups := false + err = queryRows(conn, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'servergroup'", + func(*sqlite3.Stmt) { hasGroups = true }) + if err != nil { + return nil, false, err + } + if hasGroups { + err = queryRows(conn, "SELECT id, name FROM servergroup", func(st *sqlite3.Stmt) { + id, ok := sqlInt(readValue(st, 0)) + name := sqlText(readValue(st, 1)) + if ok && name != "" { + groups[id] = name + } + }) + if err != nil { + return nil, false, err + } + } + cols := make([]string, len(pgadminColumns)) + index := map[string]int{} + for i, c := range pgadminColumns { + index[c] = i + if present[c] { + cols[i] = `"` + c + `"` + } else { + cols[i] = "NULL" + } + } + var out []pgServer + err = queryRows(conn, "SELECT "+strings.Join(cols, ", ")+" FROM server ORDER BY id", func(st *sqlite3.Stmt) { + row := make([]sqlValue, len(pgadminColumns)) + for i := range row { + row[i] = readValue(st, i) + } + col := func(name string) sqlValue { return row[index[name]] } + txt := func(name string) string { return sqlText(col(name)) } + flag := func(name string) bool { + if n, ok := sqlInt(col(name)); ok && n != 0 { + return true + } + return eqFold(txt(name), "true") + } + // Ad hoc servers come from the Workspace and are not in the tree. + if flag("is_adhoc") { + return + } + id, ok := sqlInt(col("id")) + if !ok { + return + } + var params *ojson.Object + if t := txt("connection_params"); t != "" { + if v, err := ojson.Parse([]byte(t)); err == nil { + params = ojson.Obj(v) + } + } + if params == nil { + params = ojson.NewObject() + } + for _, m := range [][2]string{ + {"ssl_mode", "sslmode"}, + {"hostaddr", "hostaddr"}, + {"passfile", "passfile"}, + {"sslcert", "sslcert"}, + {"sslkey", "sslkey"}, + {"sslrootcert", "sslrootcert"}, + } { + if v := txt(m[0]); v != "" && !params.Has(m[1]) { + params.Set(m[1], v) + } + } + var port *int64 + if n, ok := sqlInt(col("port")); ok { + port = &n + } + group := "" + if g, ok := sqlInt(col("servergroup_id")); ok { + group = groups[g] + } + save := flag("save_password") + out = append(out, pgServer{ + key: fmt.Sprintf("server-%d", id), + name: txt("name"), + group: group, + host: txt("host"), + port: port, + database: txt("maintenance_db"), + user: txt("username"), + sharedUser: txt("shared_username"), + role: txt("role"), + bgcolor: txt("bgcolor"), + service: txt("service"), + ssh: flag("use_ssh_tunnel"), + tunnelHost: txt("tunnel_host"), + kerberos: flag("kerberos_conn"), + passexec: txt("passexec_cmd"), + postSQL: txt("post_connection_sql"), + savePassword: &save, + params: params, + }) + }) + if err != nil { + return nil, false, err + } + return out, true, nil +} + +func sqlText(v sqlValue) string { + switch t := v.(type) { + case string: + return strings.TrimSpace(t) + case int64: + return strconv.FormatInt(t, 10) + case []byte: + return strings.TrimSpace(lossy(t)) + } + return "" +} + +func sqlInt(v sqlValue) (int64, bool) { + switch t := v.(type) { + case int64: + return t, true + case float64: + return int64(t), true + case string: + return parseI64(strings.TrimSpace(t)) + } + return 0, false +} + +func pgParam(s pgServer, k string) string { return valueText(s.params.Get(k)) } + +func pgadminConvert(s pgServer, out *parsed) { + name := s.name + if name == "" { + name = s.host + if name == "" { + name = s.key + } + } + hosts := s.host + if hosts == "" { + hosts = pgParam(s, "hostaddr") + } + if hosts == "" { + if s.service != "" { + out.skip(name, fmt.Sprintf("Uses the pg_service.conf service %s, which LowQuery cannot read.", s.service)) + } else { + out.skip(name, "Has no host.") + } + return + } + warnings := []string{} + // libpq accepts a comma-separated list of hosts and ports. + first, _ := splitOr(hosts, ",") + host := strings.TrimSpace(first) + if strings.Contains(hosts, ",") { + warnings = append(warnings, fmt.Sprintf("Only the first host (%s) is used.", host)) + } + var port uint16 = 5432 + if s.port != nil && *s.port > 0 && *s.port <= 65535 { + port = uint16(*s.port) + } + p := model.DefaultProfile() + p.Name = name + p.Engine = model.Postgres + p.Host = host + p.Port = port + p.Database = s.database + if p.Database == "" { + p.Database = "postgres" + } + p.User = s.user + if p.User == "" { + p.User = s.sharedUser + } + if c, ok := hexColor(s.bgcolor); ok && s.bgcolor != "" { + p.Color = &c + } + if mode, ok := pgSslMode(pgParam(s, "sslmode")); ok { + p.SslMode = mode + } + if s.savePassword != nil { + p.SavePassword = *s.savePassword + } + + if s.service != "" { + warnings = append(warnings, fmt.Sprintf("The pg_service.conf service %s is not used.", s.service)) + } + if s.ssh { + if s.tunnelHost != "" { + warnings = append(warnings, fmt.Sprintf("The SSH tunnel through %s is not carried over.", s.tunnelHost)) + } else { + warnings = append(warnings, "The SSH tunnel is not carried over.") + } + } + if s.kerberos { + warnings = append(warnings, "Kerberos authentication is not carried over.") + } + if s.passexec != "" { + warnings = append(warnings, "The password exec command is not carried over.") + } + if s.postSQL != "" { + warnings = append(warnings, "The post-connection SQL is not carried over.") + } + if s.role != "" { + warnings = append(warnings, fmt.Sprintf("The role %s is not set after connecting.", s.role)) + } + if pgParam(s, "sslcert") != "" || pgParam(s, "sslkey") != "" { + warnings = append(warnings, "The SSL client certificate is not carried over.") + } + if ca := pgParam(s, "sslrootcert"); ca != "" { + warnings = append(warnings, fmt.Sprintf("The CA certificate %s is not carried over.", ca)) + } + if options := pgParam(s, "options"); options != "" { + warnings = append(warnings, fmt.Sprintf("The connection options %s are not carried over.", options)) + } + if file := pgParam(s, "passfile"); file != "" && filepath.IsAbs(file) { + if pw, ok := pgpassPassword(file, p.Host, p.Port, p.Database, p.User); ok { + out.passwords[s.key] = pw + } + } + if reason := invalidReason(&p); reason != "" { + delete(out.passwords, s.key) + out.skip(name, reason) + return + } + var folder *string + if s.group != "" && s.group != "Servers" { + folder = model.Str(s.group) + } + out.candidates = append(out.candidates, ImportCandidate{ + Key: s.key, + Profile: p, + Folder: folder, + Warnings: warnings, + }) +} + +// defaultPgpass is the libpq password file: PGPASSFILE, else +// %APPDATA%\postgresql\pgpass.conf on Windows and ~/.pgpass elsewhere. +// Empty when unknown. +func defaultPgpass() string { + if p := os.Getenv("PGPASSFILE"); p != "" { + return p + } + if runtime.GOOS == "windows" { + if d := dirs.config(); d != "" { + return filepath.Join(d, "postgresql", "pgpass.conf") + } + return "" + } + if h := dirs.home(); h != "" { + return filepath.Join(h, ".pgpass") + } + return "" +} + +// pgpassPassword returns the password of the first +// hostname:port:database:username:password line of a pgpass file that +// matches (* matches anything, \ escapes : and \). +func pgpassPassword(file, host string, port uint16, database, user string) (string, bool) { + if user == "" { + return "", false + } + b, err := readBytes(file) + if err != nil { + return "", false + } + ps := strconv.Itoa(int(port)) + for _, line := range strings.Split(lossy(b), "\n") { + line = strings.TrimRight(line, "\r") + if strings.TrimSpace(line) == "" || strings.HasPrefix(strings.TrimSpace(line), "#") { + continue + } + f := pgpassFields(line) + if len(f) < 5 { + continue + } + m := func(pattern, value string) bool { return pattern == "*" || pattern == value } + if m(f[0], host) && m(f[1], ps) && m(f[2], database) && m(f[3], user) { + return f[4], f[4] != "" + } + } + return "", false +} + +func pgpassFields(line string) []string { + fields := []string{""} + escaped := false + for _, c := range line { + switch { + case escaped: + fields[len(fields)-1] += string(c) + escaped = false + case c == '\\': + escaped = true + case c == ':': + fields = append(fields, "") + default: + fields[len(fields)-1] += string(c) + } + } + return fields +} diff --git a/internal/importers/pgadmin_fixtures_test.go b/internal/importers/pgadmin_fixtures_test.go new file mode 100644 index 0000000..2dd3917 --- /dev/null +++ b/internal/importers/pgadmin_fixtures_test.go @@ -0,0 +1,94 @@ +package importers + +// Fixtures ported from the Rust pgadmin.rs tests. + +const pgadminSchema = ` +CREATE TABLE version (name VARCHAR(32) NOT NULL PRIMARY KEY, value INTEGER NOT NULL); +CREATE TABLE servergroup (id INTEGER NOT NULL PRIMARY KEY, user_id INTEGER NOT NULL, name VARCHAR(128) NOT NULL); +CREATE TABLE server ( + id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, servergroup_id INTEGER NOT NULL, + name VARCHAR(128) NOT NULL, host VARCHAR(128), port INTEGER, maintenance_db VARCHAR(64), username VARCHAR(64), + comment VARCHAR(1024), password VARCHAR, role VARCHAR(64), discovery_id VARCHAR, db_res VARCHAR, + bgcolor VARCHAR(10), fgcolor VARCHAR(10), service VARCHAR, use_ssh_tunnel INTEGER DEFAULT '0', + tunnel_host VARCHAR, tunnel_port VARCHAR, tunnel_username VARCHAR, tunnel_authentication INTEGER DEFAULT '0', + tunnel_identity_file VARCHAR, tunnel_password VARCHAR, save_password INTEGER DEFAULT '0', shared BOOLEAN, + kerberos_conn BOOLEAN DEFAULT 'false', cloud_status INTEGER DEFAULT '0', passexec_cmd VARCHAR, + passexec_expiration INTEGER, connection_params JSON, shared_username VARCHAR(64), prepare_threshold INTEGER, + tunnel_keep_alive INTEGER DEFAULT '0', tags JSON, is_adhoc INTEGER DEFAULT '0', post_connection_sql VARCHAR, + db_res_type VARCHAR(32) DEFAULT 'databases', tunnel_prompt_password INTEGER DEFAULT '0'); +INSERT INTO version VALUES ('ConfigDB', 49); +INSERT INTO servergroup VALUES (1, 1, 'Servers'), (2, 1, 'Production'); +INSERT INTO server (id, user_id, servergroup_id, name, host, port, maintenance_db, username, password, bgcolor, + use_ssh_tunnel, tunnel_host, save_password, kerberos_conn, connection_params, is_adhoc) +VALUES + (1, 1, 2, 'Billing', 'billing.internal', 5434, 'billing', 'bill', 'ENCRYPTED', '#16A34A', 0, NULL, 1, 0, + '{"sslmode": "require", "connect_timeout": 10}', 0), + (2, 1, 1, 'Dev', 'localhost', 5432, 'postgres', 'postgres', NULL, NULL, 1, 'jump.local', 0, 1, + '{"sslmode": "prefer"}', 0), + (3, 1, 1, 'Ad hoc', 'adhoc.local', 5432, 'postgres', 'x', NULL, NULL, 0, NULL, 0, 0, NULL, 1), + (4, 1, 9, 'Odd', 'odd.local', 99999, NULL, NULL, NULL, 'blue', 0, NULL, 0, 0, 'not json', 0); +` + +// pgadminServersJSON has PASSFILE where the pgpass path goes. +const pgadminServersJSON = `{ + "Servers": { + "1": { + "Name": "ERP production", + "Group": "Production/ERP", + "Host": "erp-db.internal", + "Port": 5433, + "MaintenanceDB": "erp", + "Username": "erp_app", + "Role": "erp_owner", + "Comment": "main", + "BGColor": "#DC2626", + "FGColor": "#FFFFFF", + "UseSSHTunnel": 1, + "TunnelHost": "bastion.example.com", + "TunnelPort": "22", + "TunnelUsername": "ops", + "TunnelAuthentication": 1, + "TunnelIdentityFile": "/home/ana/.ssh/id_ed25519", + "KerberosAuthentication": false, + "ConnectionParameters": { + "sslmode": "verify-full", + "connect_timeout": 10, + "sslrootcert": "/etc/ssl/erp-ca.pem", + "passfile": "PASSFILE" + }, + "Tags": [{"color": "#000", "text": "prod"}], + "PostConnectionSQL": "set search_path to erp" + }, + "2": { + "Name": "Local", + "Group": "Servers", + "Host": "localhost", + "Port": "5432", + "MaintenanceDB": "postgres", + "Username": "postgres", + "SSLMode": "disable", + "PassFile": "PASSFILE" + }, + "3": { + "Name": "From service", + "Group": "Servers", + "Port": 5432, + "MaintenanceDB": "postgres", + "Username": "x", + "Service": "erp" + }, + "4": { + "Name": "Kerberos", + "Group": "Servers", + "Host": "a.example.com,b.example.com", + "Port": 5432, + "MaintenanceDB": "postgres", + "Shared": true, + "SharedUsername": "ana", + "KerberosAuthentication": true, + "PasswordExecCommand": "vault read pg", + "ConnectionParameters": {"sslmode": "require", "sslcert": "/c.crt", "sslkey": "/c.key", "options": "-c statement_timeout=0"} + }, + "5": "not an object" + } +}` diff --git a/internal/importers/pgadmin_test.go b/internal/importers/pgadmin_test.go new file mode 100644 index 0000000..70b6846 --- /dev/null +++ b/internal/importers/pgadmin_test.go @@ -0,0 +1,224 @@ +package importers + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/ncruces/go-sqlite3" + + "github.com/LowBloat/LowQuery/internal/model" +) + +func TestPgAdminServersJSONExport(t *testing.T) { + dir := t.TempDir() + pass := writeFile(t, dir, "pgpass", + "localhost:5432:*:postgres:fake-pass-1\nerp-db.internal:5433:erp:erp_app:fake\\:pass-2\n") + escaped := strings.ReplaceAll(pass, `\`, `\\`) + path := writeFile(t, dir, "servers.json", strings.ReplaceAll(pgadminServersJSON, "PASSFILE", escaped)) + p, err := parsePgAdmin(path) + if err != nil { + t.Fatal(err) + } + if len(p.candidates) != 3 { + t.Fatalf("%d candidates", len(p.candidates)) + } + + erp := find(t, p, "server-1") + if erp.Profile.Engine != model.Postgres || erp.Profile.Host != "erp-db.internal" || erp.Profile.Port != 5433 { + t.Fatalf("%+v", erp.Profile) + } + if erp.Profile.Database != "erp" || erp.Profile.User != "erp_app" || erp.Profile.SslMode != model.SslVerifyFull { + t.Fatalf("%+v", erp.Profile) + } + if deref(erp.Profile.Color) != "#dc2626" || deref(erp.Folder) != "Production/ERP" || len(erp.Warnings) != 4 { + t.Fatalf("%+v", erp) + } + for _, w := range []string{"bastion.example.com", "erp_owner", "erp-ca.pem", "post-connection"} { + if !anyContains(erp.Warnings, w) { + t.Fatalf("no %q: %v", w, erp.Warnings) + } + } + if p.passwords["server-1"] != "fake:pass-2" { + t.Fatal("server-1 password") + } + + local := find(t, p, "server-2") + if local.Profile.Port != 5432 || local.Profile.SslMode != model.SslDisable || local.Folder != nil || len(local.Warnings) != 0 { + t.Fatalf("%+v", local) + } + if p.passwords["server-2"] != "fake-pass-1" { + t.Fatal("server-2 password") + } + + krb := find(t, p, "server-4") + if krb.Profile.Host != "a.example.com" || krb.Profile.User != "ana" || krb.Profile.SslMode != model.SslRequire || len(krb.Warnings) != 5 { + t.Fatalf("%+v", krb) + } + if _, ok := p.passwords["server-4"]; ok { + t.Fatal("server-4 password") + } + + if len(p.skipped) != 1 || !strings.Contains(p.skipped[0].Reason, "pg_service.conf") { + t.Fatalf("%v", p.skipped) + } + if len(p.notes) != 1 || !strings.Contains(p.notes[0], "do not include passwords") { + t.Fatalf("%v", p.notes) + } +} + +func execSQL(t *testing.T, conn *sqlite3.Conn, sql string) { + t.Helper() + if err := conn.Exec(sql); err != nil { + t.Fatal(err) + } +} + +func TestPgAdmin4DB(t *testing.T) { + path := filepath.Join(t.TempDir(), "pgadmin4.db") + conn, err := sqlite3.Open(path) + if err != nil { + t.Fatal(err) + } + execSQL(t, conn, pgadminSchema) + conn.Close() + + p, err := parsePgAdmin(path) + if err != nil { + t.Fatal(err) + } + if len(p.candidates) != 3 { + t.Fatalf("%d candidates", len(p.candidates)) + } + billing := find(t, p, "server-1") + if billing.Profile.Host != "billing.internal" || billing.Profile.Port != 5434 || billing.Profile.Database != "billing" { + t.Fatalf("%+v", billing.Profile) + } + if billing.Profile.User != "bill" || billing.Profile.SslMode != model.SslRequire || deref(billing.Profile.Color) != "#16a34a" { + t.Fatalf("%+v", billing.Profile) + } + if deref(billing.Folder) != "Production" || !billing.Profile.SavePassword || len(billing.Warnings) != 0 { + t.Fatalf("%+v", billing) + } + + dev := find(t, p, "server-2") + if dev.Folder != nil || dev.Profile.SavePassword || len(dev.Warnings) != 2 { + t.Fatalf("%+v", dev) + } + + odd := find(t, p, "server-4") + if odd.Profile.Port != 5432 || odd.Profile.Database != "postgres" || odd.Profile.Color != nil || odd.Folder != nil { + t.Fatalf("%+v", odd) + } + + if len(p.passwords) != 0 || len(p.notes) != 1 || !strings.Contains(p.notes[0], "master password") { + t.Fatalf("%v %v", p.passwords, p.notes) + } +} + +func TestPgAdminLockedAndLegacyDB(t *testing.T) { + // Characters the file: URI must escape. + dir := filepath.Join(t.TempDir(), "pg admin #1 %20") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, "pgadmin4.db") + conn, err := sqlite3.Open(path) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + execSQL(t, conn, `CREATE TABLE servergroup (id INTEGER PRIMARY KEY, user_id INTEGER, name TEXT); + CREATE TABLE server (id INTEGER PRIMARY KEY, user_id INTEGER, servergroup_id INTEGER, + name TEXT NOT NULL, host TEXT, port INTEGER, maintenance_db TEXT, username TEXT, + ssl_mode TEXT, hostaddr TEXT, sslcert TEXT, sslkey TEXT, sslrootcert TEXT); + INSERT INTO servergroup VALUES (1, 1, 'Old servers'); + INSERT INTO server VALUES (7, 1, 1, 'Legacy', NULL, 5432, 'app', 'app', 'verify-full', + '10.0.0.5', '/c.crt', '/c.key', NULL);`) + // Another connection in the middle of a write. + execSQL(t, conn, "BEGIN EXCLUSIVE; UPDATE server SET name = 'Changing';") + p, err := parsePgAdmin(path) + execSQL(t, conn, "ROLLBACK") + if err != nil { + t.Fatal(err) + } + c := find(t, p, "server-7") + if c.Profile.Name != "Legacy" || c.Profile.Host != "10.0.0.5" || c.Profile.SslMode != model.SslVerifyFull { + t.Fatalf("%+v", c.Profile) + } + if deref(c.Folder) != "Old servers" || len(c.Warnings) != 1 { + t.Fatalf("%+v", c) + } +} + +func TestPgAdminRejectsOtherFiles(t *testing.T) { + dir := t.TempDir() + for _, c := range [][2]string{ + {"empty.json", ""}, + {"array.json", "[1, 2]"}, + {"other.json", `{"connections": []}`}, + {"servers.txt", "Servers"}, + } { + _, err := parsePgAdmin(writeFile(t, dir, c[0], c[1])) + if errMessage(err) != pgadminNotOurs { + t.Fatalf("%s: %v", c[0], err) + } + } + p, err := parsePgAdmin(writeFile(t, dir, "ok.json", `{"Servers": {}}`)) + if err != nil { + t.Fatal(err) + } + if len(p.candidates) != 0 || len(p.notes) != 0 { + t.Fatalf("%+v", p) + } + + otherDB := filepath.Join(dir, "other.db") + conn, err := sqlite3.Open(otherDB) + if err != nil { + t.Fatal(err) + } + execSQL(t, conn, "CREATE TABLE t (x INTEGER);") + conn.Close() + if _, err := parsePgAdmin(otherDB); errMessage(err) != pgadminNotOurs { + t.Fatal(err) + } + fake := append([]byte("SQLite format 3\x00"), bytes.Repeat([]byte{0xAB}, 4096)...) + fakeDB := filepath.Join(dir, "fake.db") + if err := os.WriteFile(fakeDB, fake, 0o644); err != nil { + t.Fatal(err) + } + if _, err := parsePgAdmin(fakeDB); err == nil { + t.Fatal("parsed a broken database") + } + if _, err := parsePgAdmin(filepath.Join(dir, "missing.db")); err == nil { + t.Fatal("parsed a missing file") + } +} + +func TestPgAdminURIAndPgpassDetails(t *testing.T) { + if got := fileURI(`C:\Users\a b\pg#1.db`, "immutable=1"); got != "file:///C:/Users/a%20b/pg%231.db?immutable=1" { + t.Fatal(got) + } + if got := fileURI("/home/a/.pgadmin/pgadmin4.db", "immutable=1"); got != "file:///home/a/.pgadmin/pgadmin4.db?immutable=1" { + t.Fatal(got) + } + got := pgpassFields(`h:5432:d\:x:u:p\\w`) + if strings.Join(got, "|") != `h|5432|d:x|u|p\w` { + t.Fatalf("%q", got) + } + + home := fakeHome(t) + var db string + if filepath.Separator == '\\' { + db = writeFile(t, dirs.config(), "pgAdmin/pgadmin4.db", "") + } else { + db = writeFile(t, home, ".pgadmin/pgadmin4.db", "") + } + t.Setenv("SQLITE_PATH", db) + files := pgadminFiles() + if len(files) != 1 || files[0].path != db || files[0].label != "pgAdmin 4" { + t.Fatalf("%+v", files) + } +} diff --git a/internal/importers/sqldeveloper.go b/internal/importers/sqldeveloper.go new file mode 100644 index 0000000..1cd7bf9 --- /dev/null +++ b/internal/importers/sqldeveloper.go @@ -0,0 +1,378 @@ +package importers + +// Oracle SQL Developer: connections.json (19.x and later) or the older +// connections.xml (JNDI References), both in +// system/o.jdeveloper.db.connection*/ under the user folder. Saved +// passwords are encrypted with a key derived from the installation's +// db.system.id and are not imported. + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "runtime" + "strings" + "unicode" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" + "github.com/LowBloat/LowQuery/internal/ojson" +) + +// sqldeveloperFiles: %APPDATA%\SQL Developer on Windows, ~/.sqldeveloper +// on macOS and Linux, or SQLDEVELOPER_USER_DIR; one file per system* +// folder. +func sqldeveloperFiles() []source { + var roots []string + if d := os.Getenv("SQLDEVELOPER_USER_DIR"); d != "" { + roots = append(roots, d) + } + if runtime.GOOS == "windows" { + if d := dirs.config(); d != "" { + roots = append(roots, filepath.Join(d, "SQL Developer")) + } + } + if h := dirs.home(); h != "" { + roots = append(roots, filepath.Join(h, ".sqldeveloper")) + } + return sqldeveloperFilesIn(roots) +} + +func sqldeveloperFilesIn(roots []string) []source { + seen := map[string]bool{} + var out []source + for _, root := range roots { + for _, system := range subdirs(root) { + version, ok := strings.CutPrefix(fileName(system), "system") + if !ok { + continue + } + for _, connDir := range subdirs(system) { + if !strings.HasPrefix(fileName(connDir), "o.jdeveloper.db.connection") { + continue + } + file := filepath.Join(connDir, "connections.json") + if !isFile(file) { + file = filepath.Join(connDir, "connections.xml") + if !isFile(file) { + continue + } + } + id := fileID(file, true) + if !seen[id] { + seen[id] = true + out = append(out, source{versionLabel(version), file}) + } + } + } + } + return out +} + +// versionLabel turns "23.1.0.097.1607" into "SQL Developer 23.1" and +// "23.1.1.345.2114" into "SQL Developer 23.1.1". +func versionLabel(version string) string { + parts := strings.Split(version, ".") + if len(parts) > 3 { + parts = parts[:3] + } + var short string + if len(parts) == 3 && parts[2] == "0" { + short = parts[0] + "." + parts[1] + } else { + for _, p := range parts { + if p == "" { + return "SQL Developer" + } + } + short = strings.Join(parts, ".") + } + return "SQL Developer " + short +} + +const sqldeveloperNotOurs = "This is not a SQL Developer connections.json or connections.xml file." + +type sqldevConn struct { + name string + info map[string]string +} + +func parseSQLDeveloper(path string) (*parsed, error) { + text, err := readText(path) + if err != nil { + return nil, err + } + var conns []sqldevConn + switch t := strings.TrimLeftFunc(text, unicode.IsSpace); { + case strings.HasPrefix(t, "{"): + conns, err = sqldevFromJSON(text) + case strings.HasPrefix(t, "<"): + conns, err = sqldevFromXML(text) + default: + err = apperr.New(apperr.Invalid, sqldeveloperNotOurs) + } + if err != nil { + return nil, err + } + out := newParsed() + keys := map[string]bool{} + saved := false + for i, c := range conns { + name := c.name + if name == "" { + name = fmt.Sprintf("Connection %d", i+1) + } + key := name + for n := 2; keys[key]; n++ { + key = fmt.Sprintf("%s#%d", name, n) + } + keys[key] = true + if cand := sqldevConvert(key, name, c.info, out); cand != nil { + saved = saved || cand.Profile.SavePassword + out.candidates = append(out.candidates, *cand) + } + } + if saved { + out.notes = append(out.notes, "SQL Developer encrypts saved passwords with a key tied to its installation (db.system.id), so LowQuery does not import them: type them on first connect.") + } + return out, nil +} + +// sqldevFromJSON reads {"connections": [{"name", "type", "info": {...}}]}. +func sqldevFromJSON(doc string) ([]sqldevConn, error) { + v, err := ojson.Parse([]byte(doc)) + if err != nil { + return nil, apperr.New(apperr.Invalid, sqldeveloperNotOurs) + } + list, ok := ojson.Obj(v).Get("connections").([]any) + if !ok { + return nil, apperr.New(apperr.Invalid, sqldeveloperNotOurs) + } + var out []sqldevConn + for _, item := range list { + c := ojson.Obj(item) + info := map[string]string{} + m := c.Field("info") + for _, k := range m.Keys() { + switch t := m.Get(k).(type) { + case string: + info[k] = t + case json.Number: + info[k] = t.String() + case bool: + info[k] = text(t) + } + } + if t, ok := c.Get("type").(string); ok { + info["type"] = t + } + name, ok := c.Get("name").(string) + if !ok { + name = info["ConnName"] + } + out = append(out, sqldevConn{strings.TrimSpace(name), info}) + } + return out, nil +} + +// sqldevFromXML reads +// . +func sqldevFromXML(text string) ([]sqldevConn, error) { + root := parseXML(text) + if root == nil || root.name != "References" { + return nil, apperr.New(apperr.Invalid, sqldeveloperNotOurs) + } + var out []sqldevConn + for _, r := range root.all("Reference") { + info := map[string]string{} + for _, addrs := range r.all("RefAddresses") { + for _, a := range addrs.children { + k, ok := a.attr("addrType") + if !ok { + continue + } + v := "" + if c := a.child("Contents"); c != nil { + v = strings.TrimSpace(c.text) + } + info[k] = v + } + } + name, ok := r.attr("name") + if !ok { + name = info["ConnName"] + } + out = append(out, sqldevConn{strings.TrimSpace(name), info}) + } + return out, nil +} + +func sqldevConvert(key, name string, info map[string]string, out *parsed) *ImportCandidate { + get := func(k string) string { return strings.TrimSpace(info[k]) } + flag := func(k string) bool { return eqFold(get(k), "true") } + p := model.DefaultProfile() + p.Name = name + p.SavePassword = flag("SavePassword") + warnings := []string{} + url := get("customUrl") + jdbcURL := "" + if _, ok := stripPrefixFold(url, "jdbc:"); ok { + jdbcURL = url + } + raptor := get("RaptorConnectionType") + if raptor == "" { + raptor = "Oracle" + } + skip := func(reason string) *ImportCandidate { + out.skip(name, reason) + return nil + } + urlReason := func(e *urlError) string { + if e.unsupported != "" { + return e.unsupported + " is not supported by LowQuery." + } + return "Uses a JDBC URL LowQuery cannot read: " + e.invalid + "." + } + + if eqFold(raptor, "Oracle") { + p.Engine = model.Oracle + p.Port = 1521 + kind := upperASCII(get("OracleConnectionType")) + if kind == "" { + kind = "BASIC" + } + target := get("sid") + if target == "" { + target = get("serviceName") + } + switch { + case kind == "BASIC": + switch { + case get("hostname") != "" && target != "": + p.Host = get("hostname") + p.Port = 1521 + if n, ok := parseU16(get("port")); ok { + p.Port = n + } + p.Database = target + if get("sid") != "" { + p.OracleConnectType = model.OracleSID + } else { + p.OracleConnectType = model.OracleService + } + case jdbcURL != "": + if e := applyJDBC(jdbcURL, &p); e != nil { + return skip(urlReason(e)) + } + default: + return skip("Has no host and SID or service name.") + } + case kind == "TNS": + // The alias is stored in customUrl. + switch { + case jdbcURL != "": + if e := applyJDBC(jdbcURL, &p); e != nil { + return skip(urlReason(e)) + } + case url != "": + p.OracleConnectType = model.OracleTNS + p.TnsAlias = url + default: + return skip("Has no TNS alias.") + } + case kind == "LDAP": + return skip("LDAP naming is not supported by LowQuery.") + case strings.Contains(kind, "WALLET") || strings.Contains(kind, "CLOUD"): + return skip("Cloud Wallet connections are not supported by LowQuery.") + default: + // ADVANCED is the Custom JDBC URL type. + if jdbcURL == "" { + return skip(fmt.Sprintf("The %s connection type is not supported by LowQuery.", kind)) + } + if e := applyJDBC(jdbcURL, &p); e != nil { + return skip(urlReason(e)) + } + } + if p.Engine != model.Oracle { + return skip("Uses a JDBC URL that is not Oracle's.") + } + if privilege, ok := oraclePrivilege(get("role")); ok { + p.OraclePrivilege = privilege + } + if flag("OS_AUTHENTICATION") { + warnings = append(warnings, "OS authentication is not carried over: LowQuery signs in with a user and password.") + } + if flag("KERBEROS_AUTHENTICATION") { + warnings = append(warnings, "Kerberos authentication is not carried over.") + } + if flag("IS_PROXY") { + if u := get("PROXY_USER_NAME"); u != "" { + warnings = append(warnings, fmt.Sprintf("Proxy authentication as %s is not carried over.", u)) + } else { + warnings = append(warnings, "Proxy authentication is not carried over.") + } + } + } else { + lower := lowerASCII(raptor) + if strings.Contains(lower, "sybase") { + return skip("Sybase is not supported by LowQuery.") + } + if jdbcURL != "" { + if e := applyJDBC(jdbcURL, &p); e != nil { + return skip(urlReason(e)) + } + } else { + var engine model.Engine + var port uint16 + switch { + case strings.Contains(lower, "mysql"): + engine, port = model.MySQL, 3306 + case strings.Contains(lower, "postgres"): + engine, port = model.Postgres, 5432 + case strings.Contains(lower, "sqlserver") || strings.Contains(lower, "jtds"): + engine, port = model.SQLServer, 1433 + default: + return skip(raptor + " is not supported by LowQuery.") + } + host := get("hostname") + if host == "" { + return skip("Has no host.") + } + p.Engine = engine + p.Host = host + p.Port = port + if n, ok := parseU16(get("port")); ok { + p.Port = n + } + p.Database = get("databaseName") + if p.Database == "" { + p.Database = get("database") + } + } + } + + if u := get("user"); u != "" { + p.User = u + } + if c, ok := javaColor(get("Connection-Color-For-Editors")); ok { + p.Color = &c + } + if reason := invalidReason(&p); reason != "" { + return skip(reason) + } + var folder *string + if f := get("NAV_FOLDER"); f != "" { + folder = &f + } + return &ImportCandidate{Key: key, Profile: p, Folder: folder, Warnings: warnings} +} + +// javaColor reads Java's Color.getRGB() (signed ARGB) as #rrggbb. +func javaColor(v string) (string, bool) { + n, ok := parseI64(strings.TrimSpace(v)) + if !ok { + return "", false + } + return fmt.Sprintf("#%06x", uint32(n)&0x00ffffff), true +} diff --git a/internal/importers/sqldeveloper_fixtures_test.go b/internal/importers/sqldeveloper_fixtures_test.go new file mode 100644 index 0000000..04bdf65 --- /dev/null +++ b/internal/importers/sqldeveloper_fixtures_test.go @@ -0,0 +1,50 @@ +package importers + +// Fixtures ported from the Rust sqldeveloper.rs tests. + +const sqldevJSON = `{"connections":[ +{"info":{"role":"SYSDBA","SavePassword":"true","OracleConnectionType":"BASIC","PROXY_TYPE":"USER NAME","RaptorConnectionType":"Oracle","sid":"FREE","NAV_FOLDER":"OraDBA/cdbfree","customUrl":"jdbc:oracle:thin:@localhost:1526:FREE","oraDriverType":"thin","NoPasswordConnection":"TRUE","hostname":"localhost","password":"v2_ZmFrZQ==","driver":"oracle.jdbc.OracleDriver","subtype":"oraJDBC","port":"1526","OS_AUTHENTICATION":"false","IS_PROXY":"false","KERBEROS_AUTHENTICATION":"false","user":"sys","PROXY_USER_NAME":""},"name":"cdbfree CDB$ROOT","type":"jdbc"}, +{"info":{"role":"","SavePassword":"false","OracleConnectionType":"BASIC","RaptorConnectionType":"Oracle","serviceName":"erppdb","Connection-Color-For-Editors":"-2350809","customUrl":"jdbc:oracle:thin:@//erp-db:1522/erppdb","hostname":"erp-db","port":"1522","OS_AUTHENTICATION":"false","IS_PROXY":"true","PROXY_USER_NAME":"app_proxy","KERBEROS_AUTHENTICATION":"true","user":"erp"},"name":"ERP","type":"jdbc"}, +{"info":{"OracleConnectionType":"TNS","RaptorConnectionType":"Oracle","customUrl":"ERPPRD.WORLD","user":"app","OS_AUTHENTICATION":"true"},"name":"tns","type":"jdbc"}, +{"info":{"OracleConnectionType":"ADVANCED","RaptorConnectionType":"Oracle","customUrl":"jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=a)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=eam)))","user":"maximo"},"name":"advanced","type":"jdbc"}, +{"info":{"OracleConnectionType":"ADVANCED","RaptorConnectionType":"Oracle","customUrl":"jdbc:oracle:thin:@db_high?TNS_ADMIN=/opt/wallet","user":"admin"},"name":"url-tns","type":"jdbc"}, +{"info":{"OracleConnectionType":"LDAP","RaptorConnectionType":"Oracle","user":"x"},"name":"ldap","type":"jdbc"}, +{"info":{"OracleConnectionType":"CLOUD_WALLET","RaptorConnectionType":"Oracle","user":"x"},"name":"cloud","type":"jdbc"}, +{"info":{"RaptorConnectionType":"MySQL","customUrl":"jdbc:mysql://my.local:3307/shop","hostname":"my.local","port":"3307","user":"root","SavePassword":"true"},"name":"mysql","type":"jdbc"}, +{"info":{"RaptorConnectionType":"SQLServer","customUrl":"jdbc:jtds:sqlserver://mssql.local:1433/Sales;instance=SQL2019","user":"sa"},"name":"mssql","type":"jdbc"}, +{"info":{"RaptorConnectionType":"PostgreSQL","hostname":"pg.local","port":"5433","databaseName":"app","user":"app"},"name":"pg","type":"jdbc"}, +{"info":{"RaptorConnectionType":"DB2","hostname":"db2.local","port":"50000","user":"x"},"name":"db2","type":"jdbc"}, +{"info":{"RaptorConnectionType":"Sybase","hostname":"syb.local"},"name":"sybase","type":"jdbc"}, +{"info":{"OracleConnectionType":"BASIC","RaptorConnectionType":"Oracle","hostname":"h"},"name":"no-target","type":"jdbc"}, +{"info":{"OracleConnectionType":"BASIC"},"name":"ERP","type":"jdbc"}, +{"name":"broken","info":"x"}, +{"info":{"OracleConnectionType":"BASIC","sid":"X","hostname":"h","port":"x","role":"default"},"type":"jdbc","name":""} +]}` + +const sqldevXML = ` + + + + + TNS + plateau + + Oracle + SMDEV1 + false + + + + + BASIC + ORCL + db & co + 1521 + matthew + SYSOPER + fake-encrypted + true + Oracle + + +` diff --git a/internal/importers/sqldeveloper_test.go b/internal/importers/sqldeveloper_test.go new file mode 100644 index 0000000..969e41e --- /dev/null +++ b/internal/importers/sqldeveloper_test.go @@ -0,0 +1,176 @@ +package importers + +import ( + "path/filepath" + "strings" + "testing" + + "github.com/LowBloat/LowQuery/internal/model" +) + +func TestSQLDeveloperConnectionsJSON(t *testing.T) { + p, err := parseSQLDeveloper(writeFile(t, t.TempDir(), "connections.json", sqldevJSON)) + if err != nil { + t.Fatal(err) + } + + cdb := find(t, p, "cdbfree CDB$ROOT") + if cdb.Profile.Engine != model.Oracle || cdb.Profile.OracleConnectType != model.OracleSID { + t.Fatalf("%+v", cdb.Profile) + } + if cdb.Profile.Host != "localhost" || cdb.Profile.Port != 1526 || cdb.Profile.Database != "FREE" || cdb.Profile.User != "sys" { + t.Fatalf("%+v", cdb.Profile) + } + if cdb.Profile.OraclePrivilege != "sysdba" || deref(cdb.Folder) != "OraDBA/cdbfree" || !cdb.Profile.SavePassword || len(cdb.Warnings) != 0 { + t.Fatalf("%+v", cdb) + } + + erp := find(t, p, "ERP") + if erp.Profile.OracleConnectType != model.OracleService || erp.Profile.Port != 1522 || erp.Profile.Database != "erppdb" { + t.Fatalf("%+v", erp.Profile) + } + if deref(erp.Profile.Color) != "#dc2127" || erp.Profile.SavePassword || len(erp.Warnings) != 2 || !anyContains(erp.Warnings, "app_proxy") { + t.Fatalf("%+v", erp) + } + + tns := find(t, p, "tns") + if tns.Profile.OracleConnectType != model.OracleTNS || tns.Profile.TnsAlias != "ERPPRD.WORLD" || !strings.Contains(tns.Warnings[0], "OS authentication") { + t.Fatalf("%+v", tns) + } + + adv := find(t, p, "advanced") + if adv.Profile.OracleConnectType != model.OracleCustom || !strings.HasPrefix(adv.Profile.ConnectString, "(DESCRIPTION=") { + t.Fatalf("%+v", adv.Profile) + } + urlTNS := find(t, p, "url-tns") + if urlTNS.Profile.TnsAlias != "db_high" || deref(urlTNS.Profile.ConfigDir) != "/opt/wallet" { + t.Fatalf("%+v", urlTNS.Profile) + } + + if !strings.Contains(skipped(t, p, "ldap"), "LDAP") || !strings.Contains(skipped(t, p, "cloud"), "Cloud Wallet") { + t.Fatal("ldap / cloud") + } + + my := find(t, p, "mysql") + if my.Profile.Engine != model.MySQL || my.Profile.Port != 3307 || my.Profile.Database != "shop" || my.Profile.SslMode != model.SslPrefer { + t.Fatalf("%+v", my.Profile) + } + ms := find(t, p, "mssql") + if ms.Profile.Engine != model.SQLServer || ms.Profile.Instance != "SQL2019" || ms.Profile.Database != "Sales" || ms.Profile.User != "sa" { + t.Fatalf("%+v", ms.Profile) + } + pg := find(t, p, "pg") + if pg.Profile.Engine != model.Postgres || pg.Profile.Port != 5433 || pg.Profile.Database != "app" { + t.Fatalf("%+v", pg.Profile) + } + + if got := skipped(t, p, "db2"); got != "DB2 is not supported by LowQuery." { + t.Fatal(got) + } + if got := skipped(t, p, "sybase"); got != "Sybase is not supported by LowQuery." { + t.Fatal(got) + } + if !strings.Contains(skipped(t, p, "no-target"), "SID or service") { + t.Fatal("no-target") + } + // The second "ERP" gets its own key. + if got := skipped(t, p, "ERP"); got == "" { + t.Fatal("second ERP") + } + if !strings.Contains(skipped(t, p, "broken"), "SID or service") { + t.Fatal("broken") + } + unnamed := find(t, p, "Connection 16") + if unnamed.Profile.Name != "Connection 16" || unnamed.Profile.Port != 1521 || unnamed.Profile.OraclePrivilege != "none" { + t.Fatalf("%+v", unnamed.Profile) + } + + if len(p.passwords) != 0 || len(p.notes) != 1 || !strings.Contains(p.notes[0], "db.system.id") { + t.Fatalf("%v %v", p.passwords, p.notes) + } +} + +func TestSQLDeveloperConnectionsXML(t *testing.T) { + p, err := parseSQLDeveloper(writeFile(t, t.TempDir(), "connections.xml", sqldevXML)) + if err != nil { + t.Fatal(err) + } + if len(p.candidates) != 2 { + t.Fatalf("%d candidates", len(p.candidates)) + } + tns := find(t, p, "SMDEV1") + if tns.Profile.OracleConnectType != model.OracleTNS || tns.Profile.TnsAlias != "SMDEV1" || tns.Profile.User != "plateau" || tns.Profile.SavePassword { + t.Fatalf("%+v", tns.Profile) + } + orcl := find(t, p, "Orcl") + if orcl.Profile.OracleConnectType != model.OracleSID || orcl.Profile.Host != "db & co" || orcl.Profile.OraclePrivilege != "sysoper" { + t.Fatalf("%+v", orcl.Profile) + } + if len(p.passwords) != 0 || len(p.notes) != 1 { + t.Fatalf("%v %v", p.passwords, p.notes) + } +} + +func TestSQLDeveloperRejectsOtherFiles(t *testing.T) { + dir := t.TempDir() + for _, c := range [][2]string{ + {"empty.json", ""}, + {"other.json", `{"Servers": {}}`}, + {"list.json", `{"connections": 3}`}, + {"cut.json", `{"connections": [`}, + {"other.xml", ""}, + {"cut.xml", ""}, + {"text.txt", "hello"}, + } { + _, err := parseSQLDeveloper(writeFile(t, dir, c[0], c[1])) + if errMessage(err) != sqldeveloperNotOurs { + t.Fatalf("%s: %v", c[0], err) + } + } + p, err := parseSQLDeveloper(writeFile(t, dir, "ok.json", `{"connections": []}`)) + if err != nil || len(p.candidates) != 0 { + t.Fatal(err) + } +} + +func TestSQLDeveloperLabelsAndColors(t *testing.T) { + for in, want := range map[string]string{ + "23.1.0.097.1607": "SQL Developer 23.1", + "23.1.1.345.2114": "SQL Developer 23.1.1", + "x.x": "SQL Developer x.x", + "": "SQL Developer", + } { + if got := versionLabel(in); got != want { + t.Fatalf("%q: %q", in, got) + } + } + for in, want := range map[string]string{"-3750202": "#c6c6c6", "-65536": "#ff0000", "red": ""} { + if got, _ := javaColor(in); got != want { + t.Fatalf("%q: %q", in, got) + } + } +} + +func TestSQLDeveloperFindsEveryVersion(t *testing.T) { + dir := t.TempDir() + writeFile(t, dir, "system23.1.0.097.1607/o.jdeveloper.db.connection/connections.json", `{"connections": []}`) + writeFile(t, dir, "system17.3.0.271.2323/o.jdeveloper.db.connection.17.3.0.271.2323/connections.xml", sqldevXML) + writeFile(t, dir, "system4.1.5.21.78/o.sqldeveloper/product-preferences.xml", "") + files := sqldeveloperFilesIn([]string{dir, filepath.Join(dir, "missing")}) + var labels []string + for _, f := range files { + labels = append(labels, f.label) + } + if strings.Join(labels, "|") != "SQL Developer 17.3|SQL Developer 23.1" { + t.Fatalf("%q", labels) + } + + // The same folder through SQLDEVELOPER_USER_DIR and the home folder is + // listed once. + home := fakeHome(t) + writeFile(t, home, ".sqldeveloper/system23.1.0.097.1607/o.jdeveloper.db.connection/connections.json", `{"connections": []}`) + t.Setenv("SQLDEVELOPER_USER_DIR", filepath.Join(home, ".sqldeveloper")) + if files := sqldeveloperFiles(); len(files) != 1 { + t.Fatalf("%+v", files) + } +} diff --git a/internal/importers/text.go b/internal/importers/text.go new file mode 100644 index 0000000..54c852c --- /dev/null +++ b/internal/importers/text.go @@ -0,0 +1,177 @@ +package importers + +import ( + "os" + "runtime" + "strconv" + "strings" + "unicode/utf8" +) + +// String helpers with the semantics of the Rust code: ASCII-only case +// folding, split_once / rsplit_once, and integer parsing that accepts a +// leading '+'. + +// bom is the byte order mark some editors put at the start of a file. +var bom = string(rune(0xFEFF)) + +func lowerASCII(s string) string { + b := []byte(s) + for i, c := range b { + if 'A' <= c && c <= 'Z' { + b[i] = c + 'a' - 'A' + } + } + return string(b) +} + +func upperASCII(s string) string { + b := []byte(s) + for i, c := range b { + if 'a' <= c && c <= 'z' { + b[i] = c - ('a' - 'A') + } + } + return string(b) +} + +// eqFold compares ignoring ASCII case. +func eqFold(a, b string) bool { + return len(a) == len(b) && lowerASCII(a) == lowerASCII(b) +} + +// stripPrefixFold removes prefix (ASCII case ignored); ok is false when s +// does not start with it. +func stripPrefixFold(s, prefix string) (string, bool) { + if len(s) < len(prefix) || !eqFold(s[:len(prefix)], prefix) { + return s, false + } + return s[len(prefix):], true +} + +// splitOnce splits at the first sep; ok is false when sep is missing. +func splitOnce(s, sep string) (string, string, bool) { + return strings.Cut(s, sep) +} + +// splitOr is split_once(sep).unwrap_or((s, "")). +func splitOr(s, sep string) (string, string) { + a, b, _ := strings.Cut(s, sep) + return a, b +} + +// rsplitOnce splits at the last sep. +func rsplitOnce(s, sep string) (string, string, bool) { + i := strings.LastIndex(s, sep) + if i < 0 { + return s, "", false + } + return s[:i], s[i+len(sep):], true +} + +func trimPlus(s string) string { + if strings.HasPrefix(s, "+") && len(s) > 1 && s[1] != '+' && s[1] != '-' { + return s[1:] + } + return s +} + +// parseU16 is Rust's str::parse::. +func parseU16(s string) (uint16, bool) { + n, err := strconv.ParseUint(trimPlus(s), 10, 16) + return uint16(n), err == nil +} + +// parseU8 is Rust's str::parse::. +func parseU8(s string) (uint8, bool) { + n, err := strconv.ParseUint(trimPlus(s), 10, 8) + return uint8(n), err == nil +} + +// parseU32 is Rust's str::parse::. +func parseU32(s string) bool { + _, err := strconv.ParseUint(trimPlus(s), 10, 32) + return err == nil +} + +// parseI64 is Rust's str::parse::. +func parseI64(s string) (int64, bool) { + if strings.HasPrefix(s, "+") && len(s) > 1 && s[1] == '-' { + return 0, false + } + n, err := strconv.ParseInt(trimPlus(s), 10, 64) + return n, err == nil +} + +// lossy is String::from_utf8_lossy. +func lossy(b []byte) string { + if utf8.Valid(b) { + return string(b) + } + return strings.ToValidUTF8(string(b), "�") +} + +func isPathSep(c byte) bool { + return c == '/' || (runtime.GOOS == "windows" && c == '\\') +} + +// fileName is the last component of a path (Rust's Path::file_name), empty +// for a root or "..". +func fileName(p string) string { + end := len(p) + for end > 0 && isPathSep(p[end-1]) { + end-- + } + p = p[:end] + i := len(p) - 1 + for i >= 0 && !isPathSep(p[i]) { + i-- + } + name := p[i+1:] + if runtime.GOOS == "windows" && i < 0 && len(name) == 2 && name[1] == ':' { + return "" + } + if name == ".." || name == "." { + return "" + } + return name +} + +// parentDir is the folder part of a path (Rust's Path::parent) without +// cleaning it; ok is false for a root. +func parentDir(p string) (string, bool) { + i := len(p) - 1 + for i >= 0 && isPathSep(p[i]) { + i-- + } + for i >= 0 && !isPathSep(p[i]) { + i-- + } + if i < 0 { + if p == "" || isPathSep(p[0]) { + return "", false + } + return "", true + } + parent := p[:i+1] + trimmed := strings.TrimRightFunc(parent, func(r rune) bool { return r < 0x80 && isPathSep(byte(r)) }) + if trimmed == "" { + return parent[:1], true + } + if runtime.GOOS == "windows" && len(trimmed) == 2 && trimmed[1] == ':' { + return parent[:3], true + } + return trimmed, true +} + +// joinRaw appends a relative path to a folder the way Rust's Path::join +// does, without cleaning either. +func joinRaw(dir, rel string) string { + if dir == "" { + return rel + } + if isPathSep(dir[len(dir)-1]) { + return dir + rel + } + return dir + string(os.PathSeparator) + rel +} diff --git a/internal/ojson/ojson.go b/internal/ojson/ojson.go new file mode 100644 index 0000000..858d700 --- /dev/null +++ b/internal/ojson/ojson.go @@ -0,0 +1,214 @@ +// Package ojson reads and writes JSON objects keeping their key order, as +// the Rust code did with serde_json's preserve_order: connections are listed +// in file order, and configuration files of other programs are rewritten +// without shuffling their keys. +// +// Parsed values are *Object, []any, string, json.Number, bool or nil. +package ojson + +import ( + "bytes" + "encoding/json" + "errors" + "io" +) + +// Object is a JSON object in file order. A repeated key keeps its first +// position and its last value. The zero value and nil are empty objects. +type Object struct { + keys []string + vals map[string]any +} + +// NewObject returns an empty object. +func NewObject() *Object { return &Object{vals: map[string]any{}} } + +// Get returns the value of k, nil when missing. +func (o *Object) Get(k string) any { + if o == nil { + return nil + } + return o.vals[k] +} + +// Has reports whether k is present (even with a null value). +func (o *Object) Has(k string) bool { + if o == nil { + return false + } + _, ok := o.vals[k] + return ok +} + +// Keys returns the keys in order. +func (o *Object) Keys() []string { + if o == nil { + return nil + } + return o.keys +} + +func (o *Object) Len() int { + if o == nil { + return 0 + } + return len(o.keys) +} + +// Set replaces the value of k in place, or appends k. +func (o *Object) Set(k string, v any) { + if o.vals == nil { + o.vals = map[string]any{} + } + if _, ok := o.vals[k]; !ok { + o.keys = append(o.keys, k) + } + o.vals[k] = v +} + +// Obj returns v as an object, nil when it is something else. +func Obj(v any) *Object { + o, _ := v.(*Object) + return o +} + +// Field is Obj(o.Get(k)). +func (o *Object) Field(k string) *Object { return Obj(o.Get(k)) } + +var errSyntax = errors.New("invalid JSON") + +// Parse reads one JSON value; trailing data other than whitespace is an +// error. +func Parse(data []byte) (any, error) { + dec := json.NewDecoder(bytes.NewReader(data)) + dec.UseNumber() + v, err := value(dec) + if err != nil { + return nil, err + } + if _, err := dec.Token(); err != io.EOF { + return nil, errSyntax + } + return v, nil +} + +func value(dec *json.Decoder) (any, error) { + tok, err := dec.Token() + if err != nil { + return nil, err + } + switch t := tok.(type) { + case json.Delim: + switch t { + case '{': + o := NewObject() + for dec.More() { + kt, err := dec.Token() + if err != nil { + return nil, err + } + k, ok := kt.(string) + if !ok { + return nil, errSyntax + } + v, err := value(dec) + if err != nil { + return nil, err + } + o.Set(k, v) + } + if _, err := dec.Token(); err != nil { + return nil, err + } + return o, nil + case '[': + list := []any{} + for dec.More() { + v, err := value(dec) + if err != nil { + return nil, err + } + list = append(list, v) + } + if _, err := dec.Token(); err != nil { + return nil, err + } + return list, nil + } + return nil, errSyntax + default: + return t, nil + } +} + +// MarshalJSON writes the object in key order, without HTML escaping. +func (o *Object) MarshalJSON() ([]byte, error) { + var buf bytes.Buffer + if err := write(&buf, o); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +// Pretty is v indented by two spaces, the layout of serde_json's +// to_string_pretty. +func Pretty(v any) ([]byte, error) { + var compact bytes.Buffer + if err := write(&compact, v); err != nil { + return nil, err + } + var out bytes.Buffer + if err := json.Indent(&out, compact.Bytes(), "", " "); err != nil { + return nil, err + } + return out.Bytes(), nil +} + +func write(buf *bytes.Buffer, v any) error { + switch t := v.(type) { + case *Object: + if t == nil { + buf.WriteString("{}") + return nil + } + buf.WriteByte('{') + for i, k := range t.keys { + if i > 0 { + buf.WriteByte(',') + } + if err := scalar(buf, k); err != nil { + return err + } + buf.WriteByte(':') + if err := write(buf, t.vals[k]); err != nil { + return err + } + } + buf.WriteByte('}') + return nil + case []any: + buf.WriteByte('[') + for i, e := range t { + if i > 0 { + buf.WriteByte(',') + } + if err := write(buf, e); err != nil { + return err + } + } + buf.WriteByte(']') + return nil + default: + return scalar(buf, v) + } +} + +func scalar(buf *bytes.Buffer, v any) error { + enc := json.NewEncoder(buf) + enc.SetEscapeHTML(false) + if err := enc.Encode(v); err != nil { + return err + } + buf.Truncate(buf.Len() - 1) // Encode ends with a newline. + return nil +} diff --git a/internal/ojson/ojson_test.go b/internal/ojson/ojson_test.go new file mode 100644 index 0000000..800649d --- /dev/null +++ b/internal/ojson/ojson_test.go @@ -0,0 +1,48 @@ +package ojson + +import ( + "strings" + "testing" +) + +func TestKeepsOrderAndRewrites(t *testing.T) { + v, err := Parse([]byte(`{"z": 1, "a": {"y": [1.50, "", true, null]}, "m": 2, "z": 3}`)) + if err != nil { + t.Fatal(err) + } + o := Obj(v) + if strings.Join(o.Keys(), ",") != "z,a,m" { + t.Fatal(o.Keys()) + } + // A repeated key keeps its place and its last value. + if o.Get("z").(interface{ String() string }).String() != "3" { + t.Fatal(o.Get("z")) + } + o.Set("a", "x") + o.Set("new", NewObject()) + out, err := Pretty(o) + if err != nil { + t.Fatal(err) + } + want := "{\n \"z\": 3,\n \"a\": \"x\",\n \"m\": 2,\n \"new\": {}\n}" + if string(out) != want { + t.Fatalf("%s", out) + } + v, _ = Parse([]byte(`{"a": [1.50, ""]}`)) + out, _ = Pretty(v) + if string(out) != "{\n \"a\": [\n 1.50,\n \"\"\n ]\n}" { + t.Fatalf("%s", out) + } +} + +func TestRejectsBadInput(t *testing.T) { + for _, bad := range []string{"", " ", "{", "{} {}", "[1,]", "{\"a\" 1}", "x"} { + if _, err := Parse([]byte(bad)); err == nil { + t.Fatalf("parsed %q", bad) + } + } + var nilObj *Object + if nilObj.Get("a") != nil || nilObj.Has("a") || nilObj.Len() != 0 || nilObj.Field("a") != nil { + t.Fatal("nil object") + } +} From 7b35fd5d00cfe99e8de4c961d7359830d993f4c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A1bio=20Henrique=20Ara=C3=BAjo?= Date: Fri, 4 Dec 2026 12:29:23 -0300 Subject: [PATCH 6/8] feat(go): lowquery mcp server and AI activity log; CI runs transfer and MCP tests on every database --- .github/workflows/ci.yml | 20 +- internal/app/integrations.go | 14 + internal/drivers/redis/args.go | 4 +- internal/drivers/redis/redis.go | 2 +- internal/drivers/redis/redis_test.go | 10 +- internal/mcp/audit.go | 141 +++ internal/mcp/catalog.go | 1584 ++++++++++++++++++++++++++ internal/mcp/catalog_test.go | 767 +++++++++++++ internal/mcp/e2e_test.go | 1184 +++++++++++++++++++ internal/mcp/format.go | 185 +++ internal/mcp/format_test.go | 165 +++ internal/mcp/guard.go | 1065 +++++++++++++++++ internal/mcp/guard_test.go | 441 +++++++ internal/mcp/helpers_test.go | 286 +++++ internal/mcp/json.go | 87 ++ internal/mcp/server.go | 911 +++++++++++++++ internal/mcp/server_test.go | 497 ++++++++ internal/mcp/tools.go | 1099 ++++++++++++++++++ internal/mcp/tools_test.go | 196 ++++ main.go | 7 + 20 files changed, 8647 insertions(+), 18 deletions(-) create mode 100644 internal/mcp/audit.go create mode 100644 internal/mcp/catalog.go create mode 100644 internal/mcp/catalog_test.go create mode 100644 internal/mcp/e2e_test.go create mode 100644 internal/mcp/format.go create mode 100644 internal/mcp/format_test.go create mode 100644 internal/mcp/guard.go create mode 100644 internal/mcp/guard_test.go create mode 100644 internal/mcp/helpers_test.go create mode 100644 internal/mcp/json.go create mode 100644 internal/mcp/server.go create mode 100644 internal/mcp/server_test.go create mode 100644 internal/mcp/tools.go create mode 100644 internal/mcp/tools_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bd3104c..8056892 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -225,8 +225,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 +279,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 +321,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 +362,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 +406,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/app/integrations.go b/internal/app/integrations.go index 00aad17..3b5d63b 100644 --- a/internal/app/integrations.go +++ b/internal/app/integrations.go @@ -5,6 +5,7 @@ import ( "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: @@ -36,4 +37,17 @@ func (a *App) integrationCommands(m map[string]handler) { }) (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/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/mcp/audit.go b/internal/mcp/audit.go new file mode 100644 index 0000000..c63be2e --- /dev/null +++ b/internal/mcp/audit.go @@ -0,0 +1,141 @@ +package mcp + +// Activity log of AI agents: one JSON object per line in ai-activity.jsonl +// next to connections.json. The MCP server appends, the app reads the tail +// to show what agents did. + +import ( + "bufio" + "encoding/json" + "errors" + "io" + "io/fs" + "os" + "path/filepath" + "strings" + "sync" + + "github.com/LowBloat/LowQuery/internal/apperr" +) + +// auditMaxBytes: the log is cut to its newest half when it grows past this +// size. +const auditMaxBytes = 8 * 1024 * 1024 + +// AuditEntry is one tool call made by an AI agent. Its JSON shape is the +// AiActivity type of src/lib/api.ts. +type AuditEntry struct { + // RFC 3339 time in UTC, with milliseconds. + At string `json:"at"` + // MCP client name and version from initialize ("claude-ai 0.1.0"). + Client string `json:"client"` + // Tool name ("query", "execute", "describe_table"...). + Tool string `json:"tool"` + ConnectionID *string `json:"connectionId"` + ConnectionName *string `json:"connectionName"` + // SQL text, or the object/pattern for catalog tools. + Detail *string `json:"detail"` + OK bool `json:"ok"` + // Rows returned or affected. + Rows *uint64 `json:"rows"` + Error *string `json:"error"` + ElapsedMs uint64 `json:"elapsedMs"` +} + +// auditMu keeps the appends of concurrent calls whole. +var auditMu sync.Mutex + +// LogPath is the activity log in configDir. +func LogPath(configDir string) string { + return filepath.Join(configDir, "ai-activity.jsonl") +} + +// appendAudit adds one entry. Failures to write the log never fail the +// tool call. +func appendAudit(configDir string, entry AuditEntry) { + auditMu.Lock() + defer auditMu.Unlock() + path := LogPath(configDir) + _ = os.MkdirAll(configDir, 0o755) + if info, err := os.Stat(path); err == nil && info.Size() > auditMaxBytes { + _ = trimAudit(path) + } + line, err := marshal(entry) + if err != nil { + return + } + f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644) + if err != nil { + return + } + defer f.Close() + _, _ = f.Write(append(line, '\n')) +} + +// trimAudit keeps the newest half of the log. +func trimAudit(path string) error { + f, err := os.Open(path) + if err != nil { + return err + } + info, err := f.Stat() + if err != nil { + f.Close() + return err + } + if _, err := f.Seek(info.Size()/2, io.SeekStart); err != nil { + f.Close() + return err + } + reader := bufio.NewReader(f) + if _, err := reader.ReadString('\n'); err != nil && err != io.EOF { // partial line + f.Close() + return err + } + rest, err := io.ReadAll(reader) + f.Close() + if err != nil { + return err + } + tmp := path + ".tmp" + if err := os.WriteFile(tmp, rest, 0o644); err != nil { + return err + } + return os.Rename(tmp, path) +} + +// ReadRecent returns the newest limit entries of the activity log, newest +// first. A missing log is an empty one. +func ReadRecent(configDir string, limit int) ([]AuditEntry, error) { + out := []AuditEntry{} + data, err := os.ReadFile(LogPath(configDir)) + if errors.Is(err, fs.ErrNotExist) { + return out, nil + } + if err != nil { + return nil, apperr.Internalf("%v", err) + } + lines := strings.Split(string(data), "\n") + for i := len(lines) - 1; i >= 0 && len(out) < limit; i-- { + line := strings.TrimSuffix(lines[i], "\r") + if line == "" { + continue + } + var e AuditEntry + if json.Unmarshal([]byte(line), &e) == nil { + out = append(out, e) + } + } + return out, nil +} + +// ClearActivity deletes the activity log. +func ClearActivity(configDir string) error { + auditMu.Lock() + defer auditMu.Unlock() + err := os.Remove(LogPath(configDir)) + if err == nil || errors.Is(err, fs.ErrNotExist) { + return nil + } + return apperr.Internalf("%v", err) +} diff --git a/internal/mcp/catalog.go b/internal/mcp/catalog.go new file mode 100644 index 0000000..be116c4 --- /dev/null +++ b/internal/mcp/catalog.go @@ -0,0 +1,1584 @@ +package mcp + +// Catalog queries for agents, per engine: finding tables and columns by +// name, foreign keys of a table and execution plans. +// +// Everything runs through Session.Execute, which has no bind parameters, so +// every value that comes from the agent is embedded as a literal built by +// literal for the engine's dialect. Nothing here writes: the queries only +// read the catalogs, and explain asks for the plan without running the +// statement. The server runs these functions on its read-only sessions, so +// they also work inside a read-only transaction (see explain for Oracle and +// SQL Server). + +import ( + "context" + "fmt" + "slices" + "sort" + "strconv" + "strings" + "unicode" + "unicode/utf8" + + "github.com/google/uuid" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/drivers/oracle" + "github.com/LowBloat/LowQuery/internal/model" +) + +// objectMatch is a table, view or column whose name matches a search. +type objectMatch struct { + Schema *string `json:"schema"` + Table string `json:"table"` + // "table", "view", "materialized view"... as the engine names it. + Kind string `json:"kind"` + // Set when the match is a column of Table. + Column *string `json:"column"` + ColumnType *string `json:"columnType"` +} + +// foreignKey is a foreign key from a table to another table. +type foreignKey struct { + Name *string `json:"name"` + Columns []string `json:"columns"` + RefSchema *string `json:"refSchema"` + RefTable string `json:"refTable"` + RefColumns []string `json:"refColumns"` +} + +// incomingKey is a foreign key that references the table, with the schema +// and table that declare it. +type incomingKey struct { + Schema *string + Table string + Key foreignKey +} + +const ( + // maxPattern is the longest search pattern accepted. + maxPattern = 128 + // esc is the LIKE escape character: not special in any dialect's string + // literals. + esc = '!' + // fkRows: rows read for the foreign keys of one table. + fkRows = 10_000 + // planRows: plan lines read. + planRows = 5_000 + // Redis: keys examined per SCAN call and SCAN calls per search. + scanCount = 1_000 + scanRounds = 200 +) + +// oracleSystemOwners are the owners of Oracle-supplied objects, for servers +// before 12c (no ALL_USERS.ORACLE_MAINTAINED). +var oracleSystemOwners = []string{ + "ANONYMOUS", + "APEX_PUBLIC_USER", + "APPQOSSYS", + "AUDSYS", + "CTXSYS", + "DBSNMP", + "DIP", + "DVSYS", + "EXFSYS", + "FLOWS_FILES", + "GSMADMIN_INTERNAL", + "LBACSYS", + "MDDATA", + "MDSYS", + "MGMT_VIEW", + "OJVMSYS", + "OLAPSYS", + "ORACLE_OCM", + "ORDDATA", + "ORDPLUGINS", + "ORDSYS", + "OUTLN", + "OWBSYS", + "SI_INFORMTN_SCHEMA", + "SPATIAL_CSW_ADMIN_USR", + "SPATIAL_WFS_ADMIN_USR", + "SYS", + "SYSMAN", + "SYSTEM", + "WMSYS", + "XDB", + "XS$NULL", +} + +// --------------------------------------------------------------------------- +// Public API (of the package) + +// search finds tables, views and columns whose name contains pattern (case +// insensitive), across the schemas the user can see, at most limit. Table +// matches come first, then column matches; within each, exact names, then +// prefixes, then the current schema. System schemas are left out. +func search(ctx context.Context, s drivers.Session, pattern string, limit int) ([]objectMatch, error) { + pattern, err := normalizePattern(pattern) + if err != nil { + return nil, err + } + limit = max(limit, 1) + current := s.CurrentSchema() + var found []objectMatch + switch engine := s.Engine(); engine { + case model.Redis: + return redisSearch(ctx, s, pattern, limit) + case model.Cassandra: + if found, err = cassandraSearch(ctx, s, pattern); err != nil { + return nil, err + } + case model.SQLite: + if found, err = sqliteSearch(ctx, s, pattern, limit); err != nil { + return nil, err + } + case model.Oracle: + tables, columns, err := oracleSearchSQL(pattern, current, true) + if err != nil { + return nil, err + } + t, err := query(ctx, s, tables, limit) + if err != nil { + // ORACLE_MAINTAINED is missing before 12c. + if apperr.From(err).Code != "ORA-00904" { + return nil, err + } + if tables, columns, err = oracleSearchSQL(pattern, current, false); err != nil { + return nil, err + } + if t, err = query(ctx, s, tables, limit); err != nil { + return nil, err + } + } + c, err := query(ctx, s, columns, limit) + if err != nil { + return nil, err + } + found = append(tablesOf(t), columnsOf(c)...) + default: + tables, columns, err := searchSQL(catalogDialect(engine), pattern, current) + if err != nil { + return nil, err + } + t, err := query(ctx, s, tables, limit) + if err != nil { + return nil, err + } + c, err := query(ctx, s, columns, limit) + if err != nil { + return nil, err + } + found = append(tablesOf(t), columnsOf(c)...) + } + rankMatches(found, pattern, current) + if len(found) > limit { + found = found[:limit] + } + return found, nil +} + +// foreignKeys returns the foreign keys declared on table (outgoing) and +// those referencing it (incoming, with the schema and table that declares +// them). schema defaults to the session's current schema; names are exact. +func foreignKeys(ctx context.Context, s drivers.Session, schema *string, table string) ([]foreignKey, []incomingKey, error) { + engine := s.Engine() + // Neither Redis nor CQL has foreign keys. + if engine == model.Redis || engine == model.Cassandra { + return []foreignKey{}, []incomingKey{}, nil + } + if table == "" { + return nil, nil, apperr.New(apperr.Invalid, "Give the name of the table.") + } + var sc string + switch { + case schema != nil && *schema != "": + sc = *schema + case s.CurrentSchema() != nil: + sc = *s.CurrentSchema() + default: + return nil, nil, apperr.New(apperr.Invalid, "Give the schema of the table.") + } + if engine == model.SQLite { + return sqliteForeignKeys(ctx, s, sc, table) + } + sql, err := fkSQL(catalogDialect(engine), sc, table) + if err != nil { + return nil, nil, err + } + r, err := query(ctx, s, sql, fkRows) + if err != nil { + return nil, nil, err + } + out, in := groupForeignKeys(r) + return out, in, nil +} + +// explainPlan returns the engine's execution plan for sql, as text, without +// running it. Only queries and DML can be explained. +func explainPlan(ctx context.Context, s drivers.Session, sql string) (string, error) { + engine := s.Engine() + if engine == model.Redis { + return "", apperr.New(apperr.Invalid, "Redis has no execution plans: each command runs as it is.") + } + if engine == model.Cassandra { + return "", apperr.New(apperr.Invalid, "CQL has no EXPLAIN: Cassandra does not report execution plans. Filter on the partition key (and clustering columns in order) so the query reads one partition.") + } + if err := checkText(sql); err != nil { + return "", err + } + if engine == model.Oracle { + sql = oracle.PrepareSQL(sql) + } else { + sql = stripTerminator(sql) + } + if err := checkExplainable(engine, sql); err != nil { + return "", err + } + switch engine { + case model.Postgres: + const prefix = "EXPLAIN (FORMAT TEXT) " + r, err := query(ctx, s, prefix+sql, planRows) + if err != nil { + return "", shifted(err, prefix) + } + return lines(r, 0), nil + case model.MySQL, model.MariaDB: + return mysqlExplain(ctx, s, sql) + case model.Oracle: + return oracleExplain(ctx, s, sql) + case model.SQLServer: + return sqlserverExplain(ctx, s, sql) + case model.SQLite: + const prefix = "EXPLAIN QUERY PLAN " + r, err := query(ctx, s, prefix+sql, planRows) + if err != nil { + return "", shifted(err, prefix) + } + rows := make([]planRow, 0, len(r.Rows)) + for _, row := range r.Rows { + num := func(i int) int64 { + n, _ := strconv.ParseInt(cellText(row, i), 10, 64) + return n + } + rows = append(rows, planRow{num(0), num(1), cellText(row, 3)}) + } + return sqlitePlanTree(rows), nil + } + return "", apperr.Internalf("No execution plans for %s.", engine) +} + +// --------------------------------------------------------------------------- +// Literals + +// litDialect says how string literals are written. +type litDialect int + +const ( + lPostgres litDialect = iota + lOracle + lMysql + lSQLServer + lSqlite +) + +func catalogDialect(engine model.Engine) litDialect { + switch engine { + case model.Postgres: + return lPostgres + case model.Oracle: + return lOracle + case model.MySQL, model.MariaDB: + return lMysql + case model.SQLServer: + return lSQLServer + } + // CQL strings are quoted like SQLite's: '..' with '' inside, no + // backslash escapes. Redis and Cassandra never reach the SQL builders. + return lSqlite +} + +func checkText(s string) error { + if strings.ContainsRune(s, 0) { + return apperr.New(apperr.Invalid, "The text contains a NUL character.") + } + return nil +} + +// literal writes s as a string literal that means exactly s whatever the +// session settings: PostgreSQL uses E'...' when there are backslashes (immune +// to standard_conforming_strings), MySQL a hex literal (immune to +// NO_BACKSLASH_ESCAPES and the connection charset), SQL Server N'...'. +func literal(d litDialect, s string) (string, error) { + if err := checkText(s); err != nil { + return "", err + } + doubled := strings.ReplaceAll(s, "'", "''") + switch d { + case lPostgres: + if strings.Contains(s, `\`) { + return "E'" + strings.ReplaceAll(doubled, `\`, `\\`) + "'", nil + } + return "'" + doubled + "'", nil + case lSQLServer: + return "N'" + doubled + "'", nil + case lMysql: + return fmt.Sprintf("_utf8mb4 X'%X'", []byte(s)), nil + } + return "'" + doubled + "'", nil +} + +// likeEscape escapes the LIKE wildcards and the escape character with esc. +func likeEscape(d litDialect, s string) string { + var b strings.Builder + for _, c := range s { + if c == esc || c == '%' || c == '_' || (d == lSQLServer && c == '[') { + b.WriteRune(esc) + } + b.WriteRune(c) + } + return b.String() +} + +// nameTest holds the case-insensitive name tests for one pattern: the +// filter (contains) and a rank (0 exact, 1 prefix, 2 contains). +type nameTest struct { + exact, prefix, contains string +} + +func newNameTest(d litDialect, pattern string) (*nameTest, error) { + escaped := likeEscape(d, pattern) + exact, err := literal(d, pattern) + if err != nil { + return nil, err + } + prefix, err := literal(d, escaped+"%") + if err != nil { + return nil, err + } + contains, err := literal(d, "%"+escaped+"%") + if err != nil { + return nil, err + } + return &nameTest{exact, prefix, contains}, nil +} + +func (t *nameTest) filter(expr string) string { + return fmt.Sprintf("LOWER(%s) LIKE LOWER(%s) ESCAPE '%c'", expr, t.contains, esc) +} + +func (t *nameTest) rank(expr string) string { + return fmt.Sprintf("CASE WHEN LOWER(%s) = LOWER(%s) THEN 0 "+ + "WHEN LOWER(%s) LIKE LOWER(%s) ESCAPE '%c' THEN 1 ELSE 2 END", + expr, t.exact, expr, t.prefix, esc) +} + +// schemaRank sorts the current schema first, when there is one. +func schemaRank(d litDialect, expr string, current *string) (string, error) { + if current == nil { + return "1", nil + } + l, err := literal(d, *current) + if err != nil { + return "", err + } + return fmt.Sprintf("CASE WHEN %s = %s THEN 0 ELSE 1 END", expr, l), nil +} + +// normalizePattern trims the pattern and the % or * an agent may wrap it in +// ("contains" is implied). +func normalizePattern(pattern string) (string, error) { + if err := checkText(pattern); err != nil { + return "", err + } + p := strings.TrimSpace(pattern) + p = strings.Trim(p, "%*") + p = strings.TrimSpace(p) + if p == "" { + return "", apperr.New(apperr.Invalid, "Give a name or part of one to search for.") + } + if utf8.RuneCountInString(p) > maxPattern { + return "", apperr.Newf(apperr.Invalid, "The search pattern is too long (at most %d characters).", maxPattern) + } + return p, nil +} + +// --------------------------------------------------------------------------- +// Search SQL. Table queries return (schema, table, kind); column queries +// (schema, table, kind, column, type). + +// searchSQL builds the table and column queries for PostgreSQL, +// MySQL/MariaDB and SQL Server. +func searchSQL(d litDialect, pattern string, current *string) (string, string, error) { + t, err := newNameTest(d, pattern) + if err != nil { + return "", "", err + } + switch d { + case lPostgres: + from := "FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace" + kind := "CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' " + + "WHEN 'f' THEN 'foreign table' ELSE 'table' END" + schemas := "c.relkind IN ('r', 'p', 'v', 'm', 'f') AND NOT c.relispartition " + + "AND n.nspname <> 'information_schema' AND n.nspname NOT LIKE 'pg!_%' ESCAPE '!'" + inSchema, err := schemaRank(d, "n.nspname::text", current) + if err != nil { + return "", "", err + } + tables := fmt.Sprintf("SELECT n.nspname::text, c.relname::text, %s %s "+ + "WHERE %s AND %s ORDER BY %s, %s, 1, 2", + kind, from, schemas, t.filter("c.relname::text"), t.rank("c.relname::text"), inSchema) + columns := fmt.Sprintf("SELECT n.nspname::text, c.relname::text, %s, a.attname::text, "+ + "format_type(a.atttypid, a.atttypmod) "+ + "FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid "+ + "JOIN pg_namespace n ON n.oid = c.relnamespace "+ + "WHERE a.attnum > 0 AND NOT a.attisdropped AND %s AND %s "+ + "ORDER BY %s, %s, 1, 2, a.attnum", + kind, schemas, t.filter("a.attname::text"), t.rank("a.attname::text"), inSchema) + return tables, columns, nil + case lMysql: + kind := func(col string) string { + return fmt.Sprintf("CASE %s WHEN 'VIEW' THEN 'view' WHEN 'SYSTEM VIEW' THEN 'view' "+ + "WHEN 'SEQUENCE' THEN 'sequence' ELSE 'table' END", col) + } + visible := func(col string) (string, error) { + const system = "('mysql', 'information_schema', 'performance_schema', 'sys')" + if current == nil { + return fmt.Sprintf("%s NOT IN %s", col, system), nil + } + l, err := literal(d, *current) + if err != nil { + return "", err + } + return fmt.Sprintf("(%s = %s OR %s NOT IN %s)", col, l, col, system), nil + } + vt, err := visible("TABLE_SCHEMA") + if err != nil { + return "", "", err + } + rt, err := schemaRank(d, "TABLE_SCHEMA", current) + if err != nil { + return "", "", err + } + vc, err := visible("c.TABLE_SCHEMA") + if err != nil { + return "", "", err + } + rc, err := schemaRank(d, "c.TABLE_SCHEMA", current) + if err != nil { + return "", "", err + } + tables := fmt.Sprintf("SELECT TABLE_SCHEMA, TABLE_NAME, %s FROM information_schema.TABLES "+ + "WHERE %s AND %s ORDER BY %s, %s, TABLE_SCHEMA, TABLE_NAME", + kind("TABLE_TYPE"), vt, t.filter("TABLE_NAME"), t.rank("TABLE_NAME"), rt) + columns := fmt.Sprintf("SELECT c.TABLE_SCHEMA, c.TABLE_NAME, %s, c.COLUMN_NAME, c.COLUMN_TYPE "+ + "FROM information_schema.COLUMNS c JOIN information_schema.TABLES t "+ + "ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME "+ + "WHERE %s AND %s "+ + "ORDER BY %s, %s, c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION", + kind("t.TABLE_TYPE"), vc, t.filter("c.COLUMN_NAME"), t.rank("c.COLUMN_NAME"), rc) + return tables, columns, nil + case lSQLServer: + const base = "FROM sys.objects o JOIN sys.schemas s ON s.schema_id = o.schema_id" + const kind = "CASE o.type WHEN 'V' THEN 'view' ELSE 'table' END" + const user = "o.type IN ('U', 'V') AND o.is_ms_shipped = 0" + inSchema, err := schemaRank(d, "s.name", current) + if err != nil { + return "", "", err + } + tables := fmt.Sprintf("SELECT s.name, o.name, %s %s WHERE %s AND %s "+ + "ORDER BY %s, %s, s.name, o.name", + kind, base, user, t.filter("o.name"), t.rank("o.name"), inSchema) + columns := fmt.Sprintf("SELECT s.name, o.name, %s, c.name, %s "+ + "%s JOIN sys.columns c ON c.object_id = o.object_id "+ + "JOIN sys.types t ON t.user_type_id = c.user_type_id "+ + "WHERE %s AND %s ORDER BY %s, %s, s.name, o.name, c.column_id", + kind, sqlserverType, base, user, t.filter("c.name"), t.rank("c.name"), inSchema) + return tables, columns, nil + } + return "", "", apperr.Internalf("Use the engine's own search.") +} + +// sqlserverType is the column type as in DDL (nvarchar(40), decimal(10,2)). +const sqlserverType = "CASE WHEN t.is_user_defined = 1 THEN t.name " + + "WHEN t.name IN ('varchar', 'char', 'varbinary', 'binary') " + + "THEN t.name + '(' + CASE WHEN c.max_length = -1 THEN 'max' " + + "ELSE CAST(c.max_length AS varchar(10)) END + ')' " + + "WHEN t.name IN ('nvarchar', 'nchar') " + + "THEN t.name + '(' + CASE WHEN c.max_length = -1 THEN 'max' " + + "ELSE CAST(c.max_length / 2 AS varchar(10)) END + ')' " + + "WHEN t.name IN ('decimal', 'numeric') " + + "THEN t.name + '(' + CAST(c.precision AS varchar(10)) + ',' " + + "+ CAST(c.scale AS varchar(10)) + ')' " + + "WHEN t.name IN ('datetime2', 'time', 'datetimeoffset') " + + "THEN t.name + '(' + CAST(c.scale AS varchar(10)) + ')' " + + "ELSE t.name END" + +// oracleSearchSQL builds the Oracle table and column queries. modern +// filters Oracle-maintained owners through ALL_USERS.ORACLE_MAINTAINED (12c +// on); otherwise a fixed list is used. +func oracleSearchSQL(pattern string, current *string, modern bool) (string, string, error) { + d := lOracle + t, err := newNameTest(d, pattern) + if err != nil { + return "", "", err + } + const objects = "with objs as (" + + "select t.owner, t.table_name name, 'table' kind from all_tables t " + + "where t.nested = 'NO' and t.secondary = 'N' and t.dropped = 'NO' " + + "and (t.iot_type is null or t.iot_type = 'IOT') " + + "and not exists (select 1 from all_mviews m " + + "where m.owner = t.owner and m.mview_name = t.table_name) " + + "union all select v.owner, v.view_name, 'view' from all_views v " + + "union all select m.owner, m.mview_name, 'materialized view' from all_mviews m)" + var system string + if modern { + system = "o.owner not in (select username from all_users where oracle_maintained = 'Y')" + } else { + list := make([]string, len(oracleSystemOwners)) + for i, o := range oracleSystemOwners { + list[i] = "'" + o + "'" + } + system = fmt.Sprintf("o.owner not in (%s) and o.owner not like 'APEX!_%%' escape '!'", + strings.Join(list, ", ")) + } + visible := system + if current != nil { + l, err := literal(d, *current) + if err != nil { + return "", "", err + } + visible = fmt.Sprintf("(o.owner = %s or %s)", l, system) + } + inSchema, err := schemaRank(d, "o.owner", current) + if err != nil { + return "", "", err + } + const ty = "case " + + "when c.data_type in ('VARCHAR2','NVARCHAR2','CHAR','NCHAR','RAW') " + + "then c.data_type || '(' || case when c.char_length > 0 then c.char_length else c.data_length end || ')' " + + "when c.data_type = 'NUMBER' and c.data_precision is not null " + + "then 'NUMBER(' || c.data_precision || " + + "case when c.data_scale > 0 then ',' || c.data_scale end || ')' " + + "else c.data_type end" + tables := fmt.Sprintf("%s select o.owner, o.name, o.kind from objs o "+ + "where %s and %s and o.name not like 'BIN$%%' "+ + "order by %s, %s, o.owner, o.name", + objects, visible, t.filter("o.name"), t.rank("o.name"), inSchema) + columns := fmt.Sprintf("%s select o.owner, o.name, o.kind, c.column_name, %s "+ + "from all_tab_columns c join objs o on o.owner = c.owner and o.name = c.table_name "+ + "where %s and %s and o.name not like 'BIN$%%' "+ + "order by %s, %s, o.owner, o.name, c.column_id", + objects, ty, visible, t.filter("c.column_name"), t.rank("c.column_name"), inSchema) + return tables, columns, nil +} + +// sqliteIdent is a SQLite double-quoted identifier. +func sqliteIdent(name string) string { + return `"` + strings.ReplaceAll(name, `"`, `""`) + `"` +} + +// sqliteSearchSQL builds the SQLite table and column queries for one +// attached schema. +func sqliteSearchSQL(schema, pattern string) (string, string, error) { + d := lSqlite + t, err := newNameTest(d, pattern) + if err != nil { + return "", "", err + } + s, err := literal(d, schema) + if err != nil { + return "", "", err + } + master := sqliteIdent(schema) + ".sqlite_schema" + const user = "m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite!_%' ESCAPE '!'" + tables := fmt.Sprintf("SELECT %s, m.name, m.type FROM %s m WHERE %s AND %s ORDER BY %s, m.name", + s, master, user, t.filter("m.name"), t.rank("m.name")) + columns := fmt.Sprintf("SELECT %s, m.name, m.type, p.name, p.type FROM %s m "+ + "JOIN pragma_table_info(m.name, %s) p WHERE %s AND %s "+ + "ORDER BY %s, m.name, p.cid", + s, master, s, user, t.filter("p.name"), t.rank("p.name")) + return tables, columns, nil +} + +func sqliteSearch(ctx context.Context, s drivers.Session, pattern string, limit int) ([]objectMatch, error) { + schemas, err := s.ListSchemas(ctx) + if err != nil { + return nil, err + } + tables := []objectMatch{} + columns := []objectMatch{} + for _, schema := range schemas { + t, c, err := sqliteSearchSQL(schema, pattern) + if err != nil { + return nil, err + } + rt, err := query(ctx, s, t, limit) + if err != nil { + return nil, err + } + tables = append(tables, tablesOf(rt)...) + rc, err := query(ctx, s, c, limit) + if err != nil { + return nil, err + } + columns = append(columns, columnsOf(rc)...) + } + return append(tables, columns...), nil +} + +// --------------------------------------------------------------------------- +// Cassandra + +// cassandraSystem are the keyspaces of the server itself, left out of +// searches. +var cassandraSystem = []string{ + "system", + "system_schema", + "system_auth", + "system_distributed", + "system_traces", + "system_views", + "system_virtual_schema", +} + +// cassandraRows: rows read from one system_schema table for one keyspace. +const cassandraRows = 100_000 + +// cassandraKeyspace is what system_schema holds about one keyspace. +type cassandraKeyspace struct { + tables, views, types []string + // (table or view, column, CQL type) + columns [][3]string +} + +// cassandraMatches returns the matches of pattern in one keyspace: tables, +// materialized views and types by name, columns by name. system_schema +// tables only filter on their partition key, so the contains test happens +// here. +func cassandraMatches(keyspace string, k *cassandraKeyspace, pattern string) []objectMatch { + p := strings.ToLower(pattern) + hit := func(name string) bool { return strings.Contains(strings.ToLower(name), p) } + out := []objectMatch{} + add := func(names []string, kind string) { + for _, n := range names { + if hit(n) { + out = append(out, objectMatch{Schema: model.Str(keyspace), Table: n, Kind: kind}) + } + } + } + add(k.tables, "table") + add(k.views, "materialized view") + add(k.types, "type") + for _, c := range k.columns { + relation, column, ty := c[0], c[1], c[2] + if hit(column) { + kind := "table" + if slices.Contains(k.views, relation) { + kind = "materialized view" + } + out = append(out, objectMatch{ + Schema: model.Str(keyspace), + Table: relation, + Kind: kind, + Column: model.Str(column), + ColumnType: model.Str(ty), + }) + } + } + return out +} + +func cassandraSearch(ctx context.Context, s drivers.Session, pattern string) ([]objectMatch, error) { + keyspaces, err := s.ListSchemas(ctx) + if err != nil { + return nil, err + } + found := []objectMatch{} + for _, keyspace := range keyspaces { + if slices.Contains(cassandraSystem, keyspace) { + continue + } + ks, err := literal(lSqlite, keyspace) + if err != nil { + return nil, err + } + names := func(sql string) ([]string, error) { + r, err := query(ctx, s, sql, cassandraRows) + if err != nil { + return nil, err + } + out := make([]string, len(r.Rows)) + for i, row := range r.Rows { + out[i] = cellText(row, 0) + } + return out, nil + } + var k cassandraKeyspace + if k.tables, err = names("SELECT table_name FROM system_schema.tables WHERE keyspace_name = " + ks); err != nil { + return nil, err + } + if k.views, err = names("SELECT view_name FROM system_schema.views WHERE keyspace_name = " + ks); err != nil { + return nil, err + } + if k.types, err = names("SELECT type_name FROM system_schema.types WHERE keyspace_name = " + ks); err != nil { + return nil, err + } + r, err := query(ctx, s, "SELECT table_name, column_name, type FROM system_schema.columns "+ + "WHERE keyspace_name = "+ks, cassandraRows) + if err != nil { + return nil, err + } + for _, row := range r.Rows { + k.columns = append(k.columns, [3]string{cellText(row, 0), cellText(row, 1), cellText(row, 2)}) + } + found = append(found, cassandraMatches(keyspace, &k, pattern)...) + } + return found, nil +} + +func tablesOf(r *model.ExecResult) []objectMatch { + out := make([]objectMatch, 0, len(r.Rows)) + for _, row := range r.Rows { + out = append(out, objectMatch{ + Schema: cellPtr(row, 0), + Table: cellText(row, 1), + Kind: cellText(row, 2), + }) + } + return out +} + +func columnsOf(r *model.ExecResult) []objectMatch { + out := make([]objectMatch, 0, len(r.Rows)) + for _, row := range r.Rows { + out = append(out, objectMatch{ + Schema: cellPtr(row, 0), + Table: cellText(row, 1), + Kind: cellText(row, 2), + Column: model.Str(cellText(row, 3)), + ColumnType: cellPtr(row, 4), + }) + } + return out +} + +// rankMatches sorts tables before columns; then exact names, prefixes, the +// rest; then the current schema first. Stable, so the engine's order stays +// within ties. +func rankMatches(found []objectMatch, pattern string, current *string) { + p := strings.ToLower(pattern) + type key struct { + column bool + quality int + elsewhere bool + } + keyOf := func(m objectMatch) key { + name := m.Table + if m.Column != nil { + name = *m.Column + } + name = strings.ToLower(name) + quality := 2 + if name == p { + quality = 0 + } else if strings.HasPrefix(name, p) { + quality = 1 + } + elsewhere := current != nil && (m.Schema == nil || *m.Schema != *current) + return key{m.Column != nil, quality, elsewhere} + } + keys := make([]key, len(found)) + for i, m := range found { + keys[i] = keyOf(m) + } + idx := make([]int, len(found)) + for i := range idx { + idx[i] = i + } + less := func(a, b key) bool { + if a.column != b.column { + return !a.column + } + if a.quality != b.quality { + return a.quality < b.quality + } + return !a.elsewhere && b.elsewhere + } + sort.SliceStable(idx, func(i, j int) bool { return less(keys[idx[i]], keys[idx[j]]) }) + sorted := make([]objectMatch, len(found)) + for i, j := range idx { + sorted[i] = found[j] + } + copy(found, sorted) +} + +// --------------------------------------------------------------------------- +// Redis + +// redisGlob is the glob for keys containing pattern, ASCII letters in either +// case. +func redisGlob(pattern string) string { + var g strings.Builder + g.WriteString("*") + for _, c := range pattern { + switch { + case c == '*' || c == '?' || c == '[' || c == ']' || c == '\\': + g.WriteRune('\\') + g.WriteRune(c) + case c < 0x80 && isASCIIAlpha(byte(c)): + g.WriteRune('[') + g.WriteRune(unicode.ToLower(c)) + g.WriteRune(unicode.ToUpper(c)) + g.WriteRune(']') + default: + g.WriteRune(c) + } + } + g.WriteString("*") + return g.String() +} + +// redisQuote writes one argument for the Redis command line parser +// (redis-cli rules). +func redisQuote(arg string) string { + var out strings.Builder + out.WriteString(`"`) + for _, c := range arg { + switch { + case c == '\\': + out.WriteString(`\\`) + case c == '"': + out.WriteString(`\"`) + case c < 0x80 && isASCIIControl(byte(c)): + fmt.Fprintf(&out, `\x%02x`, c) + default: + out.WriteRune(c) + } + } + out.WriteString(`"`) + return out.String() +} + +// nextCursor reads the cursor in the driver's "Next cursor: N" notice. +func nextCursor(notices []string) (string, bool) { + for _, n := range notices { + rest, ok := strings.CutPrefix(n, "Next cursor: ") + if !ok { + continue + } + end := 0 + for end < len(rest) && isASCIIDigit(rest[end]) { + end++ + } + if end > 0 { + return rest[:end], true + } + } + return "", false +} + +func redisSearch(ctx context.Context, s drivers.Session, pattern string, limit int) ([]objectMatch, error) { + if s.TxState().InTransaction { + return nil, apperr.New(apperr.Invalid, "Finish the transaction with EXEC or DISCARD first.") + } + glob := redisQuote(redisGlob(pattern)) + keys := []string{} + cursor := "0" + for range scanRounds { + r, err := query(ctx, s, fmt.Sprintf("SCAN %s MATCH %s COUNT %d", cursor, glob, scanCount), 0) + if err != nil { + return nil, err + } + for _, row := range r.Rows { + keys = append(keys, cellText(row, 1)) + } + next, ok := nextCursor(r.Notices) + if !ok { + return nil, apperr.Internalf("Unexpected SCAN reply.") + } + cursor = next + if cursor == "0" || len(keys) >= limit { + break + } + } + // The exact key first, even when the scan stopped before reaching it. + if !slices.Contains(keys, pattern) { + r, err := query(ctx, s, "EXISTS "+redisQuote(pattern), 0) + if err != nil { + return nil, err + } + if len(r.Rows) > 0 && cellText(r.Rows[0], 0) == "1" { + keys = append(keys, pattern) + } + } + sort.Strings(keys) + keys = slices.Compact(keys) + schema := s.CurrentSchema() + found := make([]objectMatch, 0, len(keys)) + for _, k := range keys { + found = append(found, objectMatch{Schema: schema, Table: k, Kind: "key"}) + } + rankMatches(found, pattern, nil) + if len(found) > limit { + found = found[:limit] + } + return found, nil +} + +// --------------------------------------------------------------------------- +// Foreign keys. Rows: direction ('out'/'in'), constraint, schema, table, +// referenced schema, referenced table, position, column, referenced column; +// sorted so each constraint's rows are together, outgoing first. + +func fkSQL(d litDialect, schema, table string) (string, error) { + s, err := literal(d, schema) + if err != nil { + return "", err + } + t, err := literal(d, table) + if err != nil { + return "", err + } + switch d { + case lPostgres: + return fmt.Sprintf("WITH t AS (SELECT c.oid FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace "+ + "WHERE n.nspname = %s AND c.relname = %s), "+ + "fk AS (SELECT 'out' AS dir, con.oid FROM pg_constraint con "+ + "WHERE con.contype = 'f' AND con.conrelid IN (SELECT oid FROM t) "+ + "UNION ALL "+ + "SELECT 'in', con.oid FROM pg_constraint con "+ + "WHERE con.contype = 'f' AND con.confrelid IN (SELECT oid FROM t)) "+ + "SELECT fk.dir, con.conname::text, sn.nspname::text, sc.relname::text, "+ + "rn.nspname::text, rc.relname::text, k.ord, sa.attname::text, ra.attname::text "+ + "FROM fk JOIN pg_constraint con ON con.oid = fk.oid "+ + "JOIN pg_class sc ON sc.oid = con.conrelid "+ + "JOIN pg_namespace sn ON sn.oid = sc.relnamespace "+ + "JOIN pg_class rc ON rc.oid = con.confrelid "+ + "JOIN pg_namespace rn ON rn.oid = rc.relnamespace "+ + "CROSS JOIN LATERAL unnest(con.conkey, con.confkey) WITH ORDINALITY AS k(src, ref, ord) "+ + "JOIN pg_attribute sa ON sa.attrelid = con.conrelid AND sa.attnum = k.src "+ + "JOIN pg_attribute ra ON ra.attrelid = con.confrelid AND ra.attnum = k.ref "+ + "ORDER BY 1 DESC, 3, 4, 2, k.ord", s, t), nil + case lOracle: + part := func(dir, owner, name string) string { + return fmt.Sprintf("select '%s' dir, c.constraint_name, c.owner, c.table_name, r.owner r_owner, "+ + "r.table_name r_table, cc.position, cc.column_name, rc.column_name r_column "+ + "from all_constraints c "+ + "join all_constraints r on r.owner = c.r_owner "+ + "and r.constraint_name = c.r_constraint_name "+ + "join all_cons_columns cc on cc.owner = c.owner "+ + "and cc.constraint_name = c.constraint_name "+ + "join all_cons_columns rc on rc.owner = r.owner "+ + "and rc.constraint_name = r.constraint_name and rc.position = cc.position "+ + "where c.constraint_type = 'R' and %s = %s and %s = %s", dir, owner, s, name, t) + } + return fmt.Sprintf("%s union all %s order by 1 desc, 3, 4, 2, 7", + part("out", "c.owner", "c.table_name"), + part("in", "r.owner", "r.table_name")), nil + case lMysql: + part := func(dir, owner, name string) string { + return fmt.Sprintf("SELECT '%s', CONSTRAINT_NAME, TABLE_SCHEMA, TABLE_NAME, "+ + "REFERENCED_TABLE_SCHEMA, REFERENCED_TABLE_NAME, ORDINAL_POSITION, "+ + "COLUMN_NAME, REFERENCED_COLUMN_NAME "+ + "FROM information_schema.KEY_COLUMN_USAGE "+ + "WHERE REFERENCED_TABLE_NAME IS NOT NULL AND %s = %s AND %s = %s", dir, owner, s, name, t) + } + return fmt.Sprintf("%s UNION ALL %s ORDER BY 1 DESC, 3, 4, 2, 7", + part("out", "TABLE_SCHEMA", "TABLE_NAME"), + part("in", "REFERENCED_TABLE_SCHEMA", "REFERENCED_TABLE_NAME")), nil + case lSQLServer: + id := fmt.Sprintf("OBJECT_ID(QUOTENAME(%s) + N'.' + QUOTENAME(%s))", s, t) + return fmt.Sprintf("SELECT x.dir, fk.name, ss.name, st.name, rs.name, rt.name, "+ + "fkc.constraint_column_id, sc.name, rc.name "+ + "FROM (SELECT 'out' AS dir, f.object_id FROM sys.foreign_keys f "+ + "WHERE f.parent_object_id = %s "+ + "UNION ALL "+ + "SELECT 'in', f.object_id FROM sys.foreign_keys f "+ + "WHERE f.referenced_object_id = %s) x "+ + "JOIN sys.foreign_keys fk ON fk.object_id = x.object_id "+ + "JOIN sys.objects st ON st.object_id = fk.parent_object_id "+ + "JOIN sys.schemas ss ON ss.schema_id = st.schema_id "+ + "JOIN sys.objects rt ON rt.object_id = fk.referenced_object_id "+ + "JOIN sys.schemas rs ON rs.schema_id = rt.schema_id "+ + "JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id "+ + "JOIN sys.columns sc ON sc.object_id = fkc.parent_object_id "+ + "AND sc.column_id = fkc.parent_column_id "+ + "JOIN sys.columns rc ON rc.object_id = fkc.referenced_object_id "+ + "AND rc.column_id = fkc.referenced_column_id "+ + "ORDER BY x.dir DESC, ss.name, st.name, fk.name, fkc.constraint_column_id", id, id), nil + } + return "", apperr.Internalf("Use the SQLite pragmas.") +} + +// optText is a nullable value that can be compared. +type optText struct { + set bool + v string +} + +// groupForeignKeys groups the rows of fkSQL into constraints. +func groupForeignKeys(r *model.ExecResult) ([]foreignKey, []incomingKey) { + outgoing := []foreignKey{} + incoming := []incomingKey{} + var last *[6]optText + for _, row := range r.Rows { + var key [6]optText + for i := range key { + if v := cellPtr(row, i); v != nil { + key[i] = optText{true, *v} + } + } + column := cellText(row, 7) + refColumn := cellText(row, 8) + out := cellText(row, 0) == "out" + if last != nil && *last == key { + var fk *foreignKey + if out && len(outgoing) > 0 { + fk = &outgoing[len(outgoing)-1] + } else if !out && len(incoming) > 0 { + fk = &incoming[len(incoming)-1].Key + } + if fk != nil { + fk.Columns = append(fk.Columns, column) + fk.RefColumns = append(fk.RefColumns, refColumn) + continue + } + } + fk := foreignKey{ + Name: cellPtr(row, 1), + Columns: []string{column}, + RefSchema: cellPtr(row, 4), + RefTable: cellText(row, 5), + RefColumns: []string{refColumn}, + } + if out { + outgoing = append(outgoing, fk) + } else { + incoming = append(incoming, incomingKey{cellPtr(row, 2), cellText(row, 3), fk}) + } + last = &key + } + return outgoing, incoming +} + +// sqliteForeignKeys reads pragma_foreign_key_list of the table, and of every +// table of the schema for the incoming ones. A key without target columns +// references the primary key. +func sqliteForeignKeys(ctx context.Context, s drivers.Session, schema, table string) ([]foreignKey, []incomingKey, error) { + d := lSqlite + sl, err := literal(d, schema) + if err != nil { + return nil, nil, err + } + tl, err := literal(d, table) + if err != nil { + return nil, nil, err + } + out, err := query(ctx, s, fmt.Sprintf(`SELECT %s, id, seq, "table", "from", "to" `+ + `FROM pragma_foreign_key_list(%s, %s) ORDER BY id, seq`, tl, tl, sl), fkRows) + if err != nil { + return nil, nil, err + } + inc, err := query(ctx, s, fmt.Sprintf(`SELECT m.name, f.id, f.seq, f."table", f."from", f."to" `+ + `FROM %s.sqlite_schema m JOIN pragma_foreign_key_list(m.name, %s) f `+ + `WHERE m.type = 'table' AND LOWER(f."table") = LOWER(%s) `+ + `ORDER BY m.name, f.id, f.seq`, sqliteIdent(schema), sl, tl), fkRows) + if err != nil { + return nil, nil, err + } + + // (declaring table, constraint id) → key. + type grouped struct { + owner, id string + fk foreignKey + implicit bool + } + group := func(r *model.ExecResult) []grouped { + keys := []grouped{} + for _, row := range r.Rows { + owner, id := cellText(row, 0), cellText(row, 1) + to := cellPtr(row, 5) + implicit := to == nil + if n := len(keys); n > 0 && keys[n-1].owner == owner && keys[n-1].id == id { + k := &keys[n-1] + k.fk.Columns = append(k.fk.Columns, cellText(row, 4)) + if to != nil { + k.fk.RefColumns = append(k.fk.RefColumns, *to) + } + k.implicit = k.implicit || implicit + continue + } + refColumns := []string{} + if to != nil { + refColumns = append(refColumns, *to) + } + keys = append(keys, grouped{owner, id, foreignKey{ + Columns: []string{cellText(row, 4)}, + RefSchema: model.Str(schema), + RefTable: cellText(row, 3), + RefColumns: refColumns, + }, implicit}) + } + return keys + } + + outgoing := []foreignKey{} + for _, k := range group(out) { + if k.implicit { + if k.fk.RefColumns, err = sqlitePrimaryKey(ctx, s, schema, k.fk.RefTable); err != nil { + return nil, nil, err + } + } + outgoing = append(outgoing, k.fk) + } + incoming := []incomingKey{} + var ownKey []string + for _, k := range group(inc) { + if k.implicit { + if ownKey == nil { + if ownKey, err = sqlitePrimaryKey(ctx, s, schema, table); err != nil { + return nil, nil, err + } + } + k.fk.RefColumns = slices.Clone(ownKey) + } + incoming = append(incoming, incomingKey{model.Str(schema), k.owner, k.fk}) + } + return outgoing, incoming, nil +} + +func sqlitePrimaryKey(ctx context.Context, s drivers.Session, schema, table string) ([]string, error) { + d := lSqlite + tl, err := literal(d, table) + if err != nil { + return nil, err + } + sl, err := literal(d, schema) + if err != nil { + return nil, err + } + r, err := query(ctx, s, fmt.Sprintf("SELECT name FROM pragma_table_info(%s, %s) WHERE pk > 0 ORDER BY pk", tl, sl), fkRows) + if err != nil { + return nil, err + } + out := make([]string, len(r.Rows)) + for i, row := range r.Rows { + out[i] = cellText(row, 0) + } + return out, nil +} + +// --------------------------------------------------------------------------- +// Explain + +// stripTerminator drops trailing `;` and whitespace. +func stripTerminator(sql string) string { + text := strings.TrimRightFunc(sql, unicode.IsSpace) + for { + stripped, ok := strings.CutSuffix(text, ";") + if !ok { + return text + } + text = strings.TrimRightFunc(stripped, unicode.IsSpace) + } +} + +// afterComments is the text after leading whitespace and comments (`--`, +// `#` for MySQL, `/* */`). +func afterComments(sql string, hash bool) string { + s := strings.TrimLeftFunc(sql, unicode.IsSpace) + for { + switch { + case strings.HasPrefix(s, "--") || (hash && strings.HasPrefix(s, "#")): + if i := strings.IndexByte(s, '\n'); i >= 0 { + s = s[i+1:] + } else { + s = "" + } + case strings.HasPrefix(s, "/*"): + rest := s[2:] + if i := strings.Index(rest, "*/"); i >= 0 { + s = rest[i+2:] + } else { + s = "" + } + default: + return s + } + s = strings.TrimLeftFunc(s, unicode.IsSpace) + } +} + +// checkExplainable: only queries and DML can be explained. Anything else is +// refused before it reaches the server, so the wrapper cannot become +// something that runs (EXPLAIN ANALYZE, MySQL /*! */ code, a second +// statement). +func checkExplainable(engine model.Engine, sql string) error { + mysql := engine == model.MySQL || engine == model.MariaDB + var allowed []string + switch engine { + case model.Postgres: + allowed = []string{"SELECT", "WITH", "INSERT", "UPDATE", "DELETE", "MERGE", "VALUES", "TABLE"} + case model.MySQL, model.MariaDB: + allowed = []string{"SELECT", "WITH", "INSERT", "UPDATE", "DELETE", "REPLACE", "TABLE", "VALUES"} + case model.Oracle, model.SQLServer: + allowed = []string{"SELECT", "WITH", "INSERT", "UPDATE", "DELETE", "MERGE"} + case model.SQLite: + allowed = []string{"SELECT", "WITH", "INSERT", "UPDATE", "DELETE", "REPLACE", "VALUES"} + } + rest := afterComments(sql, mysql) + if rest == "" { + return apperr.New(apperr.Invalid, "Nothing to explain.") + } + ok := strings.HasPrefix(rest, "(") + if !ok { + first := drivers.FirstKeywords(rest, 1) + ok = len(first) > 0 && slices.Contains(allowed, first[0]) + } + if !ok { + listed := "" + if len(allowed) > 2 { + listed = strings.Join(allowed[2:], ", ") + } + return apperr.Newf(apperr.Invalid, "Only queries and %s statements can be explained. Pass the statement itself, without EXPLAIN.", listed) + } + if mysql { + upper := upperASCII(sql) + if strings.Contains(upper, "/*!") || strings.Contains(upper, "/*M!") { + return apperr.New(apperr.Invalid, "Remove the /*! */ comments to explain the statement.") + } + if mysqlHasSeparator(sql, true) || mysqlHasSeparator(sql, false) { + return apperr.New(apperr.Invalid, "Explain one statement at a time.") + } + } + return nil +} + +// mysqlHasSeparator reports a `;` outside literals, quoted identifiers and +// comments, reading backslashes in strings as escapes or not (the server's +// NO_BACKSLASH_ESCAPES decides; both readings are checked). +func mysqlHasSeparator(sql string, backslash bool) bool { + b := []byte(sql) + i := 0 + for i < len(b) { + switch c := b[i]; { + case c == '\'' || c == '"' || c == '`': + q := c + i++ + for i < len(b) { + if backslash && q != '`' && b[i] == '\\' { + i += 2 + } else if b[i] == q { + if i+1 < len(b) && b[i+1] == q { + i += 2 + } else { + break + } + } else { + i++ + } + } + i++ + case c == '#': + for i < len(b) && b[i] != '\n' { + i++ + } + case c == '-' && i+1 < len(b) && b[i+1] == '-' && + (i+2 >= len(b) || isASCIISpace(b[i+2]) || isASCIIControl(b[i+2])): + for i < len(b) && b[i] != '\n' { + i++ + } + case c == '/' && i+1 < len(b) && b[i+1] == '*': + i += 2 + for i < len(b) && !(b[i] == '*' && i+1 < len(b) && b[i+1] == '/') { + i++ + } + i += 2 + case c == ';': + return true + default: + i++ + } + } + return false +} + +// shifted makes the error position relative to the agent's statement +// instead of the wrapper. +func shifted(err error, prefix string) error { + e := apperr.From(err) + if e.Position != nil { + p := *e.Position - utf8.RuneCountInString(prefix) + if p < 0 { + e.Position = nil + } else { + e.Position = &p + } + } + return e +} + +// mysqlPlan: MySQL and MariaDB refuse EXPLAIN of a DML statement inside a +// READ ONLY transaction (1792), although EXPLAIN never runs it. That plan is +// made in a read-write transaction that is rolled back, so nothing can +// change. +func mysqlPlan(ctx context.Context, s drivers.Session, text string) (*model.ExecResult, error) { + r, err := query(ctx, s, text, planRows) + if err == nil || !strings.HasPrefix(apperr.From(err).Code, "1792") { + return r, err + } + if _, err := query(ctx, s, "ROLLBACK", 0); err != nil { + return nil, err + } + if _, err := query(ctx, s, "START TRANSACTION READ WRITE", 0); err != nil { + return nil, err + } + r, err = query(ctx, s, text, planRows) + if _, back := query(ctx, s, "ROLLBACK", 0); back != nil { + return nil, back + } + return r, err +} + +// mysqlExplain: MySQL 8.0.16+ prints a tree; MariaDB and older MySQL the +// classic table. +func mysqlExplain(ctx context.Context, s drivers.Session, sql string) (string, error) { + if s.Engine() == model.MySQL { + const prefix = "EXPLAIN FORMAT=TREE " + r, err := mysqlPlan(ctx, s, prefix+sql) + if err == nil { + return lines(r, 0), nil + } + if apperr.From(err).Kind != apperr.Database { + return "", shifted(err, prefix) + } + } + const prefix = "EXPLAIN " + r, err := mysqlPlan(ctx, s, prefix+sql) + if err != nil { + return "", shifted(err, prefix) + } + return textTable(r.Columns, r.Rows), nil +} + +// oracleExplain: EXPLAIN PLAN writes the plan to PLAN_TABLE (a +// session-private temporary table), which a read-only transaction refuses +// (ORA-01456). In that case the read-only transaction, which holds no +// changes, is rolled back, the plan is made and read in a fresh transaction +// that is rolled back too, and the read-only transaction is started again. +// Otherwise the plan rows are deleted once read. +func oracleExplain(ctx context.Context, s drivers.Session, sql string) (string, error) { + id := "LQ_MCP_" + strings.ToUpper(strings.ReplaceAll(uuid.NewString(), "-", "")[:16]) + prefix := fmt.Sprintf("EXPLAIN PLAN SET STATEMENT_ID = '%s' FOR ", id) + plan := prefix + sql + display := fmt.Sprintf("SELECT plan_table_output FROM TABLE(DBMS_XPLAN.DISPLAY(NULL, '%s', 'TYPICAL'))", id) + _, err := query(ctx, s, plan, 0) + if err == nil { + shown, err := query(ctx, s, display, planRows) + _, _ = query(ctx, s, fmt.Sprintf("DELETE FROM plan_table WHERE statement_id = '%s'", id), 0) + if err != nil { + return "", err + } + return lines(shown, 0), nil + } + // Raised directly, or wrapped in ORA-00604 by the recursive insert. + if e := apperr.From(err); e.Code != "ORA-01456" && !strings.Contains(e.Message, "ORA-01456") { + return "", shifted(err, prefix) + } + if _, err := s.EndTransaction(ctx, false); err != nil { + return "", err + } + var shown *model.ExecResult + _, outcome := query(ctx, s, plan, 0) + if outcome == nil { + shown, outcome = query(ctx, s, display, planRows) + } else { + outcome = shifted(outcome, prefix) + } + _, back := s.EndTransaction(ctx, false) + _, readOnly := query(ctx, s, "SET TRANSACTION READ ONLY", 0) + if outcome != nil { + return "", outcome + } + if back != nil { + return "", back + } + if readOnly != nil { + return "", readOnly + } + return lines(shown, 0), nil +} + +// sqlserverExplain: with SHOWPLAN_ALL on, SQL Server compiles the batch and +// returns its plan without running anything. SHOWPLAN_TEXT would put the +// plan in a second result set, which the driver does not return, so the +// StmtText column of SHOWPLAN_ALL (the same text) is used, with the +// estimates. +// +// The setting lasts for the session: if this call is interrupted between ON +// and OFF, later statements are not executed, so the caller must drop the +// session after an interrupted explain. +func sqlserverExplain(ctx context.Context, s drivers.Session, sql string) (string, error) { + if _, err := query(ctx, s, "SET SHOWPLAN_ALL ON", 0); err != nil { + return "", err + } + r, outcome := query(ctx, s, sql, 0) + _, off := query(ctx, s, "SET SHOWPLAN_ALL OFF", 0) + if outcome != nil { + return "", outcome + } + if off != nil { + return "", off + } + at := func(name string) int { + for i, c := range r.Columns { + if equalFoldASCII(c.Name, name) { + return i + } + } + return -1 + } + text, rows, cost, kind := at("StmtText"), at("EstimateRows"), at("TotalSubtreeCost"), at("Type") + if text < 0 { + text = 0 + } + out := make([]string, 0, len(r.Rows)) + for _, row := range r.Rows { + line := strings.TrimRightFunc(cellText(row, text), unicode.IsSpace) + operator := kind >= 0 && cellText(row, kind) == "PLAN_ROW" + if operator && rows >= 0 && cost >= 0 { + line += fmt.Sprintf(" [rows %s, cost %s]", cellText(row, rows), cellText(row, cost)) + } + out = append(out, line) + } + return strings.Join(out, "\n"), nil +} + +// planRow is one EXPLAIN QUERY PLAN row of SQLite. +type planRow struct { + id, parent int64 + detail string +} + +// sqlitePlanTree draws EXPLAIN QUERY PLAN rows (id, parent, detail) like the +// sqlite3 shell does. +func sqlitePlanTree(rows []planRow) string { + var out strings.Builder + out.WriteString("QUERY PLAN") + var walk func(parent int64, prefix string, depth int) + walk = func(parent int64, prefix string, depth int) { + if depth > 64 { + return + } + kids := []planRow{} + for _, r := range rows { + if r.parent == parent && r.id != parent { + kids = append(kids, r) + } + } + for k, r := range kids { + last := k+1 == len(kids) + out.WriteString("\n") + out.WriteString(prefix) + if last { + out.WriteString("`--") + } else { + out.WriteString("|--") + } + out.WriteString(r.detail) + deeper := prefix + "| " + if last { + deeper = prefix + " " + } + walk(r.id, deeper, depth+1) + } + } + walk(0, "", 0) + return out.String() +} + +// textTable writes rows as an aligned text table with a header. +func textTable(columns []model.ColumnInfo, rows []model.Row) string { + show := func(v *string) string { + if v == nil { + return "NULL" + } + return *v + } + widths := make([]int, len(columns)) + for i, c := range columns { + widths[i] = utf8.RuneCountInString(c.Name) + } + for _, row := range rows { + for i, v := range row { + if i < len(widths) { + widths[i] = max(widths[i], utf8.RuneCountInString(show(v))) + } + } + } + line := func(cells []string) string { + parts := []string{} + for i, c := range cells { + if i >= len(widths) { + break + } + pad := widths[i] - utf8.RuneCountInString(c) + parts = append(parts, c+strings.Repeat(" ", max(pad, 0))) + } + return strings.TrimRightFunc(strings.Join(parts, " | "), unicode.IsSpace) + } + names := make([]string, len(columns)) + for i, c := range columns { + names[i] = c.Name + } + out := []string{line(names)} + dashes := make([]string, len(widths)) + for i, w := range widths { + dashes[i] = strings.Repeat("-", w) + } + out = append(out, strings.Join(dashes, "-+-")) + for _, row := range rows { + cells := make([]string, len(row)) + for i, v := range row { + cells[i] = show(v) + } + out = append(out, line(cells)) + } + return strings.Join(out, "\n") +} + +// --------------------------------------------------------------------------- +// Helpers + +func query(ctx context.Context, s drivers.Session, sql string, maxRows int) (*model.ExecResult, error) { + return s.Execute(ctx, model.ExecRequest{SQL: sql, MaxRows: maxRows}) +} + +// cellText is value i of row, "" for NULL or a missing value. +func cellText(row model.Row, i int) string { + if i < len(row) && row[i] != nil { + return *row[i] + } + return "" +} + +// cellPtr is value i of row, nil for NULL or a missing value. +func cellPtr(row model.Row, i int) *string { + if i < len(row) && row[i] != nil { + v := *row[i] + return &v + } + return nil +} + +// lines is column i of every row, one per line. +func lines(r *model.ExecResult, i int) string { + out := make([]string, len(r.Rows)) + for j, row := range r.Rows { + out[j] = cellText(row, i) + } + return strings.Join(out, "\n") +} diff --git a/internal/mcp/catalog_test.go b/internal/mcp/catalog_test.go new file mode 100644 index 0000000..3eed711 --- /dev/null +++ b/internal/mcp/catalog_test.go @@ -0,0 +1,767 @@ +package mcp + +import ( + "context" + "crypto/rand" + "encoding/hex" + "fmt" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/drivers/redis" + "github.com/LowBloat/LowQuery/internal/engines" + "github.com/LowBloat/LowQuery/internal/model" +) + +func ptr(s string) *string { return &s } + +func TestCassandraSearchFiltersAndRanks(t *testing.T) { + k := &cassandraKeyspace{ + tables: []string{"users", "events", "UserLog"}, + views: []string{"users_by_email"}, + types: []string{"user_address", "money"}, + columns: [][3]string{ + {"users", "id", "uuid"}, + {"users", "email", "text"}, + {"users_by_email", "email", "text"}, + {"events", "user_id", "uuid"}, + }, + } + found := cassandraMatches("shop", k, "USER") + rankMatches(found, "user", ptr("other")) + got := []string{} + for _, m := range found { + c := "" + if m.Column != nil { + c = *m.Column + } + got = append(got, m.Table+"/"+m.Kind+"/"+c) + } + want := []string{ + "users/table/", + "UserLog/table/", + "users_by_email/materialized view/", + "user_address/type/", + "events/table/user_id", + } + if !slices.Equal(got, want) { + t.Fatalf("%v", got) + } + if *found[4].ColumnType != "uuid" { + t.Fatal(found[4]) + } + found = cassandraMatches("shop", k, "email") + if len(found) != 3 { + t.Fatalf("%+v", found) + } + if !slices.ContainsFunc(found, func(m objectMatch) bool { + return m.Table == "users_by_email" && m.Kind == "materialized view" + }) { + t.Fatalf("%+v", found) + } + if len(cassandraMatches("shop", k, "zzz")) != 0 { + t.Fatal("zzz") + } +} + +func TestLiteralsPerDialect(t *testing.T) { + cases := []struct { + d litDialect + in string + want string + }{ + {lPostgres, "o'k", "'o''k'"}, + {lPostgres, `a\'b`, `E'a\\''b'`}, + {lOracle, "it's", "'it''s'"}, + {lSqlite, `a\b`, `'a\b'`}, + {lSQLServer, "o'k", "N'o''k'"}, + {lMysql, `a'\é`, "_utf8mb4 X'61275CC3A9'"}, + {lMysql, "", "_utf8mb4 X''"}, + } + for _, c := range cases { + if got, err := literal(c.d, c.in); err != nil || got != c.want { + t.Errorf("%q: %q %v", c.in, got, err) + } + } + for _, d := range []litDialect{lPostgres, lOracle, lMysql, lSQLServer, lSqlite} { + if _, err := literal(d, "a\x00b"); err == nil { + t.Errorf("%d: NUL accepted", d) + } + } +} + +func TestLikeEscaping(t *testing.T) { + if got := likeEscape(lPostgres, "a_b%c!d[e"); got != "a!_b!%c!!d[e" { + t.Error(got) + } + if got := likeEscape(lSQLServer, "a[b]_"); got != "a![b]!_" { + t.Error(got) + } + n, err := newNameTest(lOracle, "x_y") + if err != nil { + t.Fatal(err) + } + if got := n.filter("n"); got != "LOWER(n) LIKE LOWER('%x!_y%') ESCAPE '!'" { + t.Error(got) + } + if !strings.Contains(n.rank("n"), "LOWER(n) = LOWER('x_y')") || !strings.Contains(n.rank("n"), "LIKE LOWER('x!_y%') ESCAPE '!'") { + t.Error(n.rank("n")) + } +} + +func TestPatternsAreNormalized(t *testing.T) { + if got, err := normalizePattern(" %cust* "); err != nil || got != "cust" { + t.Error(got, err) + } + if got, err := normalizePattern("a%b"); err != nil || got != "a%b" { + t.Error(got, err) + } + for _, p := range []string{" %% ", strings.Repeat("x", maxPattern+1), "a\x00"} { + if _, err := normalizePattern(p); err == nil { + t.Errorf("%q accepted", p) + } + } +} + +func TestSearchSQLEmbedsOnlyLiterals(t *testing.T) { + evil := "x'; drop table t; --" + for _, d := range []litDialect{lPostgres, lMysql, lSQLServer} { + tables, columns, err := searchSQL(d, evil, ptr("pub'lic")) + if err != nil { + t.Fatal(err) + } + for _, sql := range []string{tables, columns} { + if strings.Contains(sql, "x'; drop") { + t.Errorf("%d: %s", d, sql) + } + } + } + tables, _, _ := searchSQL(lPostgres, "cust", ptr("public")) + if !strings.Contains(tables, "LIKE LOWER('%cust%') ESCAPE '!'") || !strings.Contains(tables, "CASE WHEN n.nspname::text = 'public' THEN 0") { + t.Error(tables) + } + _, columns, _ := searchSQL(lMysql, "id", nil) + if !strings.Contains(columns, "LOWER(_utf8mb4 X'25696425')") { + t.Error(columns) + } + tables, _, _ = searchSQL(lSQLServer, "a[1]", nil) + if !strings.Contains(tables, "N'%a![1]%'") { + t.Error(tables) + } + + modern, _, _ := oracleSearchSQL("emp", ptr("HR"), true) + if !strings.Contains(modern, "oracle_maintained = 'Y'") || !strings.Contains(modern, "o.owner = 'HR' or") { + t.Error(modern) + } + if !strings.Contains(modern, "o.name not like 'BIN$%'") { + t.Error(modern) + } + _, legacy, _ := oracleSearchSQL("emp", nil, false) + if !strings.Contains(legacy, "'SYSTEM'") || strings.Contains(legacy, "oracle_maintained") || !strings.Contains(legacy, "'APEX!_%' escape '!'") { + t.Error(legacy) + } + + tables, columns, _ = sqliteSearchSQL(`we"ird`, "a'b") + if !strings.Contains(tables, `FROM "we""ird".sqlite_schema m`) { + t.Error(tables) + } + if !strings.Contains(columns, `pragma_table_info(m.name, 'we"ird')`) || !strings.Contains(columns, "'%a''b%'") { + t.Error(columns) + } +} + +func TestFKSQLQuotesNames(t *testing.T) { + sql, _ := fkSQL(lSQLServer, "dbo", "o'rders") + if !strings.Contains(sql, "QUOTENAME(N'dbo') + N'.' + QUOTENAME(N'o''rders')") { + t.Error(sql) + } + sql, _ = fkSQL(lMysql, "db", "t") + if !strings.Contains(sql, "TABLE_SCHEMA = _utf8mb4 X'6462' AND TABLE_NAME = _utf8mb4 X'74'") { + t.Error(sql) + } + sql, _ = fkSQL(lOracle, "HR", "EMP") + if !strings.Contains(sql, "c.owner = 'HR' and c.table_name = 'EMP'") || !strings.Contains(sql, "r.owner = 'HR' and r.table_name = 'EMP'") { + t.Error(sql) + } + sql, _ = fkSQL(lPostgres, "public", `a\b`) + if !strings.Contains(sql, `c.relname = E'a\\b'`) { + t.Error(sql) + } +} + +func resultOf(rows ...[]string) *model.ExecResult { + r := &model.ExecResult{} + for _, row := range rows { + out := model.Row{} + for _, v := range row { + out = append(out, model.Str(v)) + } + r.Rows = append(r.Rows, out) + } + return r +} + +func TestGroupsForeignKeyRows(t *testing.T) { + r := resultOf( + []string{"out", "fk_a", "s", "t", "s", "p", "1", "a1", "id1"}, + []string{"out", "fk_a", "s", "t", "s", "p", "2", "a2", "id2"}, + []string{"out", "fk_b", "s", "t", "x", "q", "1", "b", "id"}, + []string{"in", "fk_c", "s", "child", "s", "t", "1", "t_id", "id"}, + ) + out, in := groupForeignKeys(r) + if len(out) != 2 || !slices.Equal(out[0].Columns, []string{"a1", "a2"}) || !slices.Equal(out[0].RefColumns, []string{"id1", "id2"}) { + t.Fatalf("%+v", out) + } + if *out[1].RefSchema != "x" { + t.Fatalf("%+v", out[1]) + } + if len(in) != 1 || *in[0].Schema != "s" || in[0].Table != "child" || in[0].Key.RefTable != "t" { + t.Fatalf("%+v", in) + } +} + +func TestRanksTablesThenExactThenPrefix(t *testing.T) { + m := func(schema, table string, column *string) objectMatch { + return objectMatch{Schema: ptr(schema), Table: table, Kind: "table", Column: column} + } + found := []objectMatch{ + m("public", "orders", ptr("customer")), + m("public", "old_customer", nil), + m("other", "Customer", nil), + m("public", "customers", nil), + m("public", "customer", nil), + } + rankMatches(found, "customer", ptr("public")) + got := []string{} + for _, f := range found { + got = append(got, *f.Schema+"."+f.Table) + } + want := []string{"public.customer", "other.Customer", "public.customers", "public.old_customer", "public.orders"} + if !slices.Equal(got, want) { + t.Fatal(got) + } +} + +func TestRedisPatterns(t *testing.T) { + if got := redisGlob("a*1"); got != `*[aA]\*1*` { + t.Error(got) + } + if got := redisGlob("[x]?"); got != `*\[[xX]\]\?*` { + t.Error(got) + } + if got := redisQuote("a\"b\\c\n"); got != `"a\"b\\c\x0a"` { + t.Error(got) + } + args, err := redis.SplitArgs("SCAN 0 MATCH " + redisQuote(`a"\x41 b`)) + if err != nil || string(args[3]) != `a"\x41 b` { + t.Error(args, err) + } + if c, ok := nextCursor([]string{"Next cursor: 1234"}); !ok || c != "1234" { + t.Error(c) + } + if c, ok := nextCursor([]string{"Next cursor: 0 (the scan is complete)."}); !ok || c != "0" { + t.Error(c) + } +} + +func TestExplainAcceptsOnlyQueriesAndDML(t *testing.T) { + ok := []struct { + e model.Engine + sql string + }{ + {model.Postgres, "-- c\n select 1"}, + {model.Postgres, "(select 1) union select 2"}, + {model.MySQL, "# c\nselect 1"}, + {model.MySQL, "select ';' from t"}, + {model.MySQL, "select 1 -- ; x"}, + } + for _, c := range ok { + if err := checkExplainable(c.e, c.sql); err != nil { + t.Errorf("%s: %v", c.sql, err) + } + } + refused := []struct { + e model.Engine + sql string + }{ + {model.Postgres, "ANALYZE select 1"}, + {model.Postgres, "explain select 1"}, + {model.Oracle, "drop table t"}, + {model.SQLite, " "}, + {model.MySQL, "/*!ANALYZE*/ select 1"}, + {model.MariaDB, "select /*M!100000 1 */ 2"}, + {model.MySQL, "select 1; drop table t"}, + // Without backslash escapes the string ends at \' and `;` is outside. + {model.MySQL, `select 'a\'; drop table t; -- '`}, + {model.MySQL, "select 1 --; x"}, + } + for _, c := range refused { + if err := checkExplainable(c.e, c.sql); err == nil { + t.Errorf("%s accepted", c.sql) + } + } + err := checkExplainable(model.Postgres, "drop table t") + if err == nil || err.Error() != "Only queries and INSERT, UPDATE, DELETE, MERGE, VALUES, TABLE statements can be explained. Pass the statement itself, without EXPLAIN." { + t.Error(err) + } +} + +func TestPositionsAndTerminators(t *testing.T) { + e := apperr.New(apperr.Invalid, "x") + p := 25 + e.Position = &p + if got := apperr.From(shifted(e, "EXPLAIN (FORMAT TEXT) ")); got.Position == nil || *got.Position != 3 { + t.Error(got.Position) + } + e = apperr.New(apperr.Invalid, "x") + p = 2 + e.Position = &p + if got := apperr.From(shifted(e, "EXPLAIN ")); got.Position != nil { + t.Error(*got.Position) + } + if got := stripTerminator("select 1 ;; \n"); got != "select 1" { + t.Error(got) + } +} + +func TestDrawsSqlitePlansAndTables(t *testing.T) { + rows := []planRow{ + {2, 0, "SCAN a"}, + {5, 0, "SEARCH b USING INDEX i (x=?)"}, + {7, 5, "LIST SUBQUERY 1"}, + {9, 0, "USE TEMP B-TREE FOR ORDER BY"}, + } + if got := sqlitePlanTree(rows); got != "QUERY PLAN\n|--SCAN a\n|--SEARCH b USING INDEX i (x=?)\n| `--LIST SUBQUERY 1\n`--USE TEMP B-TREE FOR ORDER BY" { + t.Error(got) + } + cols := []model.ColumnInfo{{Name: "id"}, {Name: "table"}} + if got := textTable(cols, []model.Row{{model.Str("1"), nil}}); got != "id | table\n---+------\n1 | NULL" { + t.Errorf("%q", got) + } +} + +// ---- SQLite, end to end. + +func mustExec(t *testing.T, s drivers.Session, sql string) *model.ExecResult { + t.Helper() + r, err := execOn(context.Background(), s, sql) + if err != nil { + t.Fatalf("%s: %v", sql, err) + } + return r +} + +func TestSqliteCatalog(t *testing.T) { + ctx := context.Background() + p := sqliteProfile("", "", filepath.Join(t.TempDir(), "catalog.db"), "off") + p.CreateFile = true + s, err := engines.Open(ctx, p, nil) + if err != nil { + t.Fatal(err) + } + defer s.Close() + mustExec(t, s, "CREATE TABLE lq_mcp_customer (id INTEGER PRIMARY KEY, name TEXT)") + mustExec(t, s, `CREATE TABLE "lq mcp order" (id INTEGER PRIMARY KEY, customer_id INTEGER REFERENCES lq_mcp_customer, "it's" TEXT)`) + mustExec(t, s, `CREATE TABLE lq_mcp_line (order_id INTEGER, n INTEGER, FOREIGN KEY (order_id) REFERENCES "lq mcp order" (id))`) + mustExec(t, s, "CREATE VIEW lq_mcp_customer_v AS SELECT * FROM lq_mcp_customer") + mustExec(t, s, "INSERT INTO lq_mcp_customer VALUES (1, 'a')") + + // Tables first (exact, then prefix), then columns. + found, err := search(ctx, s, "LQ_MCP_CUSTOMER", 50) + if err != nil { + t.Fatal(err) + } + if found[0].Table != "lq_mcp_customer" || found[0].Kind != "table" || *found[0].Schema != "main" { + t.Fatalf("%+v", found[0]) + } + if found[1].Table != "lq_mcp_customer_v" || found[1].Kind != "view" { + t.Fatalf("%+v", found[1]) + } + found, _ = search(ctx, s, "customer", 50) + if found[0].Column != nil { + t.Fatalf("%+v", found[0]) + } + i := slices.IndexFunc(found, func(m objectMatch) bool { return m.Column != nil && *m.Column == "customer_id" }) + if i < 0 || found[i].Table != "lq mcp order" || *found[i].ColumnType != "INTEGER" { + t.Fatalf("%+v", found) + } + if found, _ := search(ctx, s, "customer", 1); len(found) != 1 { + t.Fatal(found) + } + // `_` is literal: "q m" in "lq mcp order" does not match "q_m". + found, _ = search(ctx, s, "q_m", 50) + if slices.ContainsFunc(found, func(m objectMatch) bool { return m.Table == "lq mcp order" }) || + !slices.ContainsFunc(found, func(m objectMatch) bool { return m.Table == "lq_mcp_line" }) { + t.Fatalf("%+v", found) + } + // Quotes are data. + found, _ = search(ctx, s, "it's", 50) + if found[0].Column == nil || *found[0].Column != "it's" { + t.Fatalf("%+v", found) + } + if _, err := search(ctx, s, "%", 50); err == nil { + t.Fatal("% accepted") + } + + // Foreign keys: implicit target columns resolve to the primary key. + out, in, err := foreignKeys(ctx, s, nil, "lq mcp order") + if err != nil { + t.Fatal(err) + } + if len(out) != 1 || !slices.Equal(out[0].Columns, []string{"customer_id"}) || out[0].RefTable != "lq_mcp_customer" || !slices.Equal(out[0].RefColumns, []string{"id"}) { + t.Fatalf("%+v", out) + } + if len(in) != 1 || in[0].Table != "lq_mcp_line" || !slices.Equal(in[0].Key.Columns, []string{"order_id"}) || !slices.Equal(in[0].Key.RefColumns, []string{"id"}) { + t.Fatalf("%+v", in) + } + out, in, err = foreignKeys(ctx, s, ptr("main"), "lq_mcp_customer") + if err != nil || len(out) != 0 || in[0].Table != "lq mcp order" || !slices.Equal(in[0].Key.RefColumns, []string{"id"}) { + t.Fatalf("%+v %+v %v", out, in, err) + } + + // Explain: a tree, nothing runs, only queries and DML. + plan, err := explainPlan(ctx, s, "SELECT * FROM lq_mcp_customer WHERE id = 1;") + if err != nil || !strings.HasPrefix(plan, "QUERY PLAN\n`--SEARCH") { + t.Fatalf("%s %v", plan, err) + } + if _, err := explainPlan(ctx, s, "DELETE FROM lq_mcp_customer"); err != nil { + t.Fatal(err) + } + if r := mustExec(t, s, "SELECT count(*) FROM lq_mcp_customer"); cellText(r.Rows[0], 0) != "1" { + t.Fatal("explain ran the delete") + } + if _, err := explainPlan(ctx, s, "DROP TABLE lq_mcp_customer"); err == nil { + t.Fatal("drop explained") + } + if _, err := explainPlan(ctx, s, "SELECT nope FROM lq_mcp_customer"); err == nil || !strings.Contains(err.Error(), "nope") { + t.Fatal(err) + } + + // Read-only session, as the MCP server opens it. + mustExec(t, s, "PRAGMA query_only = ON") + if found, err := search(ctx, s, "order", 10); err != nil || len(found) < 2 { + t.Fatal(found, err) + } + if _, _, err := foreignKeys(ctx, s, nil, "lq_mcp_line"); err != nil { + t.Fatal(err) + } + if plan, err := explainPlan(ctx, s, "INSERT INTO lq_mcp_customer VALUES (2, 'b')"); err != nil || !strings.HasPrefix(plan, "QUERY PLAN") { + t.Fatal(plan, err) + } +} + +// ---- Against real servers, with the variables of the driver tests; each +// test skips when its server is not configured. + +// targetOf returns the profile and password of one engine's test server, +// or skips the test. +func targetOf(t *testing.T, engine string) (model.ConnectionProfile, *string) { + t.Helper() + p := model.DefaultProfile() + p.Name = "test" + var pw string + switch engine { + case "postgres": + p.Engine = model.Postgres + p.Host = env("LQ_PG_HOST") + p.Port = port("LQ_PG_PORT", 5432) + p.User = envOr("LQ_PG_USER", "postgres") + p.Database = envOr("LQ_PG_DB", "postgres") + p.SslMode = model.SslPrefer + pw = env("LQ_PG_PASSWORD") + case "oracle": + p.Engine = model.Oracle + p.Host = env("LQ_ORA_HOST") + p.Port = port("LQ_ORA_PORT", 1521) + p.User = env("LQ_ORA_USER") + p.Database = envOr("LQ_ORA_SERVICE", "FREEPDB1") + p.OracleConnectType = model.OracleService + pw = env("LQ_ORA_PASSWORD") + if p.User == "" { + p.Host = "" + } + case "mysql": + p.Engine = model.MySQL + if env("LQ_MYSQL_ENGINE") == "mariadb" { + p.Engine = model.MariaDB + } + p.Host = env("LQ_MYSQL_HOST") + p.Port = port("LQ_MYSQL_PORT", 3306) + p.User = envOr("LQ_MYSQL_USER", "root") + p.Database = envOr("LQ_MYSQL_DB", "lowquery") + p.SslMode = model.SslPrefer + pw = env("LQ_MYSQL_PASSWORD") + case "sqlserver": + p.Engine = model.SQLServer + p.Host = env("LQ_MSSQL_HOST") + p.Port = port("LQ_MSSQL_PORT", 1433) + p.User = envOr("LQ_MSSQL_USER", "sa") + p.Database = envOr("LQ_MSSQL_DB", "master") + p.SslMode = model.SslPrefer + pw = env("LQ_MSSQL_PASSWORD") + // SQL Server always signs in with a password, empty or not. + return skipWithout(t, p, &pw) + case "redis": + p.Engine = model.Redis + p.Host = env("LQ_REDIS_HOST") + p.Port = port("LQ_REDIS_PORT", 6379) + p.Database = "0" + p.SslMode = model.SslDisable + pw = env("LQ_REDIS_PASSWORD") + case "cassandra": + p.Engine = model.Cassandra + p.Host = env("LQ_CASSANDRA_HOST") + p.Port = port("LQ_CASSANDRA_PORT", 9042) + p.User = env("LQ_CASSANDRA_USER") + p.Datacenter = env("LQ_CASSANDRA_DC") + p.SslMode = model.SslDisable + pw = env("LQ_CASSANDRA_PASSWORD") + } + if pw == "" { + return skipWithout(t, p, nil) + } + return skipWithout(t, p, &pw) +} + +func skipWithout(t *testing.T, p model.ConnectionProfile, pw *string) (model.ConnectionProfile, *string) { + t.Helper() + if p.Host == "" { + t.Skipf("no %s test server configured", p.Engine) + } + return p, pw +} + +func openTarget(t *testing.T, engine string) drivers.Session { + t.Helper() + p, pw := targetOf(t, engine) + s, err := engines.Open(context.Background(), p, pw) + if err != nil { + t.Fatalf("connection: %v", err) + } + t.Cleanup(func() { _ = s.Close() }) + return s +} + +// checkCatalog runs the shared checks: parent and child exist, +// child.parent_id references parent.id. +func checkCatalog(t *testing.T, s drivers.Session, prefix, parent, child, querySQL string) { + t.Helper() + ctx := context.Background() + found, err := search(ctx, s, prefix, 50) + if err != nil { + t.Fatal(err) + } + for _, table := range []string{parent, child} { + if !slices.ContainsFunc(found, func(m objectMatch) bool { return m.Table == table && m.Column == nil }) { + t.Fatalf("%s: %+v", table, found) + } + } + found, err = search(ctx, s, "PARENT_ID", 50) + if err != nil { + t.Fatal(err) + } + i := slices.IndexFunc(found, func(m objectMatch) bool { return m.Table == child }) + if i < 0 || !equalFoldASCII(*found[i].Column, "parent_id") || found[i].ColumnType == nil { + t.Fatalf("%+v", found) + } + if found[0].Column == nil || !equalFoldASCII(*found[0].Column, "parent_id") { + t.Fatalf("%+v", found[0]) + } + if _, err := search(ctx, s, "x'; --", 5); err != nil { + t.Fatal(err) + } + + out, in, err := foreignKeys(ctx, s, nil, child) + if err != nil { + t.Fatal(err) + } + if len(out) != 1 || out[0].RefTable != parent || !equalFoldASCII(out[0].Columns[0], "parent_id") || + !equalFoldASCII(out[0].RefColumns[0], "id") || out[0].Name == nil || len(in) != 0 { + t.Fatalf("%+v %+v", out, in) + } + out, in, err = foreignKeys(ctx, s, nil, parent) + if err != nil || len(out) != 0 || len(in) != 1 || in[0].Table != child { + t.Fatalf("%+v %+v %v", out, in, err) + } + + plan, err := explainPlan(ctx, s, querySQL) + if err != nil || strings.TrimSpace(plan) == "" { + t.Fatalf("%q %v", plan, err) + } +} + +// runTag is a short tag that keeps the names of one test run apart. +func runTag() string { + b := make([]byte, 3) + _, _ = rand.Read(b) + return hex.EncodeToString(b) +} + +func TestPostgresCatalog(t *testing.T) { + s := openTarget(t, "postgres") + ctx := context.Background() + tag := "lq_mcp_" + runTag() + parent, child := tag+"_parent", tag+" Child" + cleanup := func() { _, _ = execOn(ctx, s, fmt.Sprintf(`DROP TABLE IF EXISTS "%s", %s`, child, parent)) } + cleanup() + t.Cleanup(cleanup) + mustExec(t, s, fmt.Sprintf("CREATE TABLE %s (id int PRIMARY KEY)", parent)) + mustExec(t, s, fmt.Sprintf(`CREATE TABLE "%s" (id int PRIMARY KEY, parent_id int CONSTRAINT %s_fk REFERENCES %s (id))`, child, tag, parent)) + mustExec(t, s, fmt.Sprintf("INSERT INTO %s VALUES (1)", parent)) + checkCatalog(t, s, tag, parent, child, fmt.Sprintf(`SELECT * FROM "%s"`, child)) + + mustExec(t, s, "SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY") + plan, err := explainPlan(ctx, s, "DELETE FROM "+parent) + if err != nil || !strings.Contains(plan, "Delete on "+parent) { + t.Fatal(plan, err) + } + if _, err := search(ctx, s, tag, 5); err != nil { + t.Fatal(err) + } + mustExec(t, s, "SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE") + if r := mustExec(t, s, "SELECT count(*) FROM "+parent); cellText(r.Rows[0], 0) != "1" { + t.Fatal("explain ran the delete") + } + _, err = explainPlan(ctx, s, "SELECT nope FROM "+parent) + if e := apperr.From(err); err == nil || e.Position == nil || *e.Position != 7 { + t.Fatalf("%v", err) + } +} + +func TestOracleCatalog(t *testing.T) { + s := openTarget(t, "oracle") + ctx := context.Background() + tag := "lq_mcp_" + runTag() + parent, child := strings.ToUpper(tag+"_parent"), tag+" Child" + cleanup := func() { + _, _ = execOn(ctx, s, fmt.Sprintf(`drop table "%s" purge`, child)) + _, _ = execOn(ctx, s, fmt.Sprintf("drop table %s purge", parent)) + } + cleanup() + t.Cleanup(cleanup) + mustExec(t, s, fmt.Sprintf("create table %s (id number primary key)", parent)) + mustExec(t, s, fmt.Sprintf(`create table "%s" (id number primary key, parent_id number constraint %s_fk references %s (id))`, child, tag, parent)) + mustExec(t, s, fmt.Sprintf("insert into %s values (1)", parent)) + mustExec(t, s, "commit") + checkCatalog(t, s, tag, parent, child, fmt.Sprintf(`select * from "%s"`, child)) + + // As the MCP server runs reads: manual commit, read-only transaction. + if _, err := s.SetAutocommit(ctx, false); err != nil { + t.Fatal(err) + } + mustExec(t, s, "set transaction read only") + plan, err := explainPlan(ctx, s, "delete from "+parent) + if err != nil || !strings.Contains(plan, "DELETE") { + t.Fatal(plan, err) + } + _, err = execOn(ctx, s, fmt.Sprintf("insert into %s values (2)", parent)) + if apperr.From(err).Code != "ORA-01456" { + t.Fatalf("%v", err) + } + if _, err := s.EndTransaction(ctx, false); err != nil { + t.Fatal(err) + } + if _, err := s.SetAutocommit(ctx, true); err != nil { + t.Fatal(err) + } + if r := mustExec(t, s, "select count(*) from plan_table where statement_id like 'LQ_MCP_%'"); cellText(r.Rows[0], 0) != "0" { + t.Fatal("plan rows left behind") + } + if r := mustExec(t, s, "select count(*) from "+parent); cellText(r.Rows[0], 0) != "1" { + t.Fatal("explain ran the delete") + } +} + +func TestMySQLCatalog(t *testing.T) { + s := openTarget(t, "mysql") + ctx := context.Background() + tag := "lq_mcp_" + runTag() + parent, child := tag+"_parent", tag+" Child" + cleanup := func() { _, _ = execOn(ctx, s, fmt.Sprintf("DROP TABLE IF EXISTS `%s`, %s", child, parent)) } + cleanup() + t.Cleanup(cleanup) + mustExec(t, s, fmt.Sprintf("CREATE TABLE %s (id int PRIMARY KEY) ENGINE=InnoDB", parent)) + mustExec(t, s, fmt.Sprintf("CREATE TABLE `%s` (id int PRIMARY KEY, parent_id int, CONSTRAINT %s_fk FOREIGN KEY (parent_id) REFERENCES %s (id)) ENGINE=InnoDB", child, tag, parent)) + mustExec(t, s, fmt.Sprintf("INSERT INTO %s VALUES (1)", parent)) + checkCatalog(t, s, tag, parent, child, fmt.Sprintf("SELECT * FROM `%s`", child)) + + mustExec(t, s, "SET SESSION TRANSACTION READ ONLY") + if _, err := explainPlan(ctx, s, "DELETE FROM "+parent); err != nil { + t.Fatal(err) + } + // Backslashes and quotes in the pattern stay data in both modes. + if _, err := search(ctx, s, `a\'b`, 5); err != nil { + t.Fatal(err) + } + mustExec(t, s, "SET SESSION sql_mode = CONCAT_WS(',', NULLIF(@@sql_mode, ''), 'NO_BACKSLASH_ESCAPES')") + if _, err := search(ctx, s, `a\'b`, 5); err != nil { + t.Fatal(err) + } + mustExec(t, s, "SET SESSION TRANSACTION READ WRITE") + if r := mustExec(t, s, "SELECT count(*) FROM "+parent); cellText(r.Rows[0], 0) != "1" { + t.Fatal("explain ran the delete") + } +} + +func TestSQLServerCatalog(t *testing.T) { + s := openTarget(t, "sqlserver") + ctx := context.Background() + tag := "lq_mcp_" + runTag() + parent, child := tag+"_parent", tag+" Child" + cleanup := func() { _, _ = execOn(ctx, s, fmt.Sprintf("DROP TABLE IF EXISTS [%s], %s", child, parent)) } + cleanup() + t.Cleanup(cleanup) + mustExec(t, s, fmt.Sprintf("CREATE TABLE %s (id int PRIMARY KEY)", parent)) + mustExec(t, s, fmt.Sprintf("CREATE TABLE [%s] (id int PRIMARY KEY, parent_id int CONSTRAINT %s_fk REFERENCES %s (id))", child, tag, parent)) + mustExec(t, s, fmt.Sprintf("INSERT INTO %s VALUES (1)", parent)) + checkCatalog(t, s, tag, parent, child, fmt.Sprintf("SELECT * FROM [%s]", child)) + + // Nothing runs under SHOWPLAN, and the session is back to normal. + plan, err := explainPlan(ctx, s, "DELETE FROM "+parent) + if err != nil || !strings.Contains(plan, "Delete") { + t.Fatal(plan, err) + } + if _, err := s.SetAutocommit(ctx, false); err != nil { + t.Fatal(err) + } + if _, err := explainPlan(ctx, s, "SELECT * FROM "+parent); err != nil { + t.Fatal(err) + } + if _, err := s.EndTransaction(ctx, false); err != nil { + t.Fatal(err) + } + if _, err := s.SetAutocommit(ctx, true); err != nil { + t.Fatal(err) + } + if r := mustExec(t, s, "SELECT count(*) FROM "+parent); cellText(r.Rows[0], 0) != "1" { + t.Fatal("explain ran the delete") + } +} + +func TestRedisSearch(t *testing.T) { + s := openTarget(t, "redis") + ctx := context.Background() + tag := "lq_mcp_" + runTag() + user, star := tag+":User:1", tag+":*star" + t.Cleanup(func() { _, _ = execOn(ctx, s, fmt.Sprintf(`DEL %s "%s"`, user, star)) }) + mustExec(t, s, fmt.Sprintf("SET %s a", user)) + mustExec(t, s, fmt.Sprintf(`SET "%s" b`, star)) + found, err := search(ctx, s, strings.ToUpper(tag)+":user", 10) + if err != nil || !slices.ContainsFunc(found, func(m objectMatch) bool { return m.Table == user }) { + t.Fatalf("%+v %v", found, err) + } + found, err = search(ctx, s, tag[len(tag)-6:]+":*st", 10) + if err != nil || len(found) != 1 || found[0].Kind != "key" { + t.Fatalf("%+v %v", found, err) + } + if out, _, err := foreignKeys(ctx, s, nil, "x"); err != nil || len(out) != 0 { + t.Fatal(out, err) + } + if _, err := explainPlan(ctx, s, "GET x"); err == nil { + t.Fatal("explained") + } +} diff --git a/internal/mcp/e2e_test.go b/internal/mcp/e2e_test.go new file mode 100644 index 0000000..c7871c6 --- /dev/null +++ b/internal/mcp/e2e_test.go @@ -0,0 +1,1184 @@ +package mcp + +// The MCP server against real servers, one test per engine, through the +// in-memory client. They run only with the variables of the driver +// integration tests and skip without them: +// +// - PostgreSQL: LQ_PG_HOST, LQ_PG_PORT, LQ_PG_USER, LQ_PG_PASSWORD, LQ_PG_DB +// - Oracle: LQ_ORA_HOST, LQ_ORA_PORT, LQ_ORA_SERVICE, LQ_ORA_USER, LQ_ORA_PASSWORD +// - MySQL and MariaDB: LQ_MYSQL_HOST, LQ_MYSQL_PORT, LQ_MYSQL_USER, +// LQ_MYSQL_PASSWORD, LQ_MYSQL_DB, LQ_MYSQL_ENGINE +// - SQL Server: LQ_MSSQL_HOST, LQ_MSSQL_PORT, LQ_MSSQL_USER, LQ_MSSQL_PASSWORD, LQ_MSSQL_DB +// - Redis: LQ_REDIS_HOST, LQ_REDIS_PORT, LQ_REDIS_PASSWORD +// - Cassandra: LQ_CASSANDRA_HOST, LQ_CASSANDRA_PORT (9042), LQ_CASSANDRA_USER, +// LQ_CASSANDRA_PASSWORD, LQ_CASSANDRA_DC +// +// Each test writes a connections.json with a read, an off and a write +// profile for the same server, creates objects named lq_mcp_e2e__* +// through the write connection and drops them at the end, also when a check +// fails (Cassandra: the keyspace lq_mcp_e2e_). The SQL below is written +// with the bare lq_mcp_e2e prefix; the harness adds the run tag. + +import ( + "context" + "fmt" + "slices" + "strconv" + "strings" + "testing" + "time" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/engines" + "github.com/LowBloat/LowQuery/internal/model" +) + +const ( + // normalLimit is the time limit of the main client. + normalLimit = 30 * time.Second + // shortLimit is the time limit of the second client, for slow calls. + shortLimit = 3 * time.Second + readOnlyMsg = "read-only for AI agents" + e2eParent = "lq_mcp_e2e_parent" + // e2eChild is the child table's name, mixed case with a space. + e2eChild = "lq_mcp_e2e Child" + e2eUpdate = "UPDATE lq_mcp_e2e_parent SET name = 'uno' WHERE id = 1" +) + +// e2e is two clients on one connections.json: c with the normal time +// limit, short with shortLimit. +type e2e struct { + t *testing.T + dir string + c, short *testClient + server *server + prefix string + ro, rw string + roName, rwName, offName string +} + +// startE2e connects to the engine's test server (or skips), drops leftovers +// of cleanup now and again when the test ends, and starts the clients. +func startE2e(t *testing.T, engine, tag string, cleanup []string) *e2e { + t.Helper() + target, pw := targetOf(t, engine) + e := &e2e{t: t, prefix: "lq_mcp_e2e_" + runTag()} + runAll := func() { + ctx := context.Background() + s, err := engines.Open(ctx, target, pw) + if err != nil { + t.Errorf("connect for cleanup: %v", err) + return + } + defer s.Close() + for _, sql := range cleanup { + _, _ = execOn(ctx, s, e.n(sql)) + } + } + runAll() + // Registered first, so it runs after the servers have stopped. + t.Cleanup(runAll) + + e.dir = t.TempDir() + run := runTag() + profile := func(suffix string, access model.AiAccess) model.ConnectionProfile { + p := target + p.ID = fmt.Sprintf("e2e-%s-%s-%s", tag, suffix, run) + p.Name = fmt.Sprintf("E2E %s %s", tag, suffix) + p.AiAccess = access + return p + } + ro, off, rw := profile("read", accessRead), profile("off", "off"), profile("write", accessWrite) + for _, p := range []model.ConnectionProfile{ro, off, rw} { + setTestPassword(p.ID, pw) + } + writeProfiles(t, e.dir, ro, off, rw) + e.c, e.server = startClient(t, e.dir, normalLimit) + e.short, _ = startClient(t, e.dir, shortLimit) + e.c.initialize("2025-11-25") + e.short.initialize("2025-11-25") + e.ro, e.rw = ro.ID, rw.ID + e.roName, e.rwName, e.offName = ro.Name, rw.Name, off.Name + return e +} + +// n adds the run tag to the object names in s. +func (e *e2e) n(s string) string { return strings.ReplaceAll(s, "lq_mcp_e2e", e.prefix) } + +func (e *e2e) named(args map[string]any) map[string]any { + out := map[string]any{} + for k, v := range args { + if s, ok := v.(string); ok { + v = e.n(s) + } + out[k] = v + } + return out +} + +func (e *e2e) ok(tool string, args map[string]any) map[string]any { + e.t.Helper() + args = e.named(args) + r := e.c.call(tool, args) + if isErr(r) { + e.t.Fatalf("%s %s: %s", tool, jsonText(args), textOf(r)) + } + return r +} + +// refused returns the text of a refused call. +func (e *e2e) refused(tool string, args map[string]any) string { + e.t.Helper() + args = e.named(args) + r := e.c.call(tool, args) + if !isErr(r) { + e.t.Fatalf("%s %s was not refused: %s", tool, jsonText(args), textOf(r)) + } + return textOf(r) +} + +func (e *e2e) query(connection, sql string) [][]*string { + e.t.Helper() + return rowsOf(e.ok("query", map[string]any{"connection": connection, "sql": sql})) +} + +func (e *e2e) read(sql string) [][]*string { + e.t.Helper() + return e.query(e.ro, sql) +} + +// write runs execute on the write connection; the structured result. +func (e *e2e) write(sql string) map[string]any { + e.t.Helper() + return structuredOf(e.ok("execute", map[string]any{"connection": e.rw, "sql": sql})) +} + +// value is one value read through the write connection. +func (e *e2e) value(sql string) *string { + e.t.Helper() + rows := e.query(e.rw, sql) + if len(rows) == 0 || len(rows[0]) == 0 { + return nil + } + return rows[0][0] +} + +// onRead runs op on the agent's session of the read connection, as tools do. +func (e *e2e) onRead(kind callKind, op func(ctx context.Context, s drivers.Session) error) error { + e.t.Helper() + all, err := e.server.agentProfiles() + if err != nil { + e.t.Fatal(err) + } + i := slices.IndexFunc(all, func(p model.ConnectionProfile) bool { return p.ID == e.ro }) + return e.server.run(all[i], kind, newCancel(), func(ctx context.Context, s drivers.Session) error { + return op(ctx, s) + }) +} + +// checkConnections: read and write are listed, off is not and cannot be +// used. +func (e *e2e) checkConnections() { + e.t.Helper() + list := e.ok("list_connections", map[string]any{}) + conns := arr(structuredOf(list)["connections"]) + names := []string{} + for _, c := range conns { + names = append(names, mapOf(c)["name"].(string)) + } + if !slices.Equal(names, []string{e.roName, e.rwName}) { + e.t.Fatal(names) + } + if mapOf(conns[0])["access"] != "read" || mapOf(conns[1])["access"] != "write" { + e.t.Fatal(conns) + } + if strings.Contains(textOf(list), e.offName) { + e.t.Fatal(textOf(list)) + } + if m := e.refused("list_schemas", map[string]any{"connection": e.offName}); !strings.Contains(m, "Unknown connection") { + e.t.Fatal(m) + } +} + +// checkTimeLimit runs a call on the short client that goes past its limit, +// then a quick one on the same connection. +func (e *e2e) checkTimeLimit(connection, tool, slow, quick string) { + e.t.Helper() + started := time.Now() + r := e.short.call(tool, e.named(map[string]any{"connection": connection, "sql": slow})) + if !isErr(r) || !strings.Contains(textOf(r), "longer than 3 s") { + e.t.Fatalf("%s: %s", slow, textOf(r)) + } + if time.Since(started) >= 20*time.Second { + e.t.Fatalf("%s took %s", slow, time.Since(started)) + } + r = e.short.call("query", e.named(map[string]any{"connection": connection, "sql": quick})) + if isErr(r) { + e.t.Fatalf("after the time limit: %s", textOf(r)) + } +} + +func (e *e2e) log() []AuditEntry { + e.t.Helper() + log, err := ReadRecent(e.dir, 10_000) + if err != nil { + e.t.Fatal(err) + } + for _, entry := range log { + if entry.Client != "test-client 1.0" { + e.t.Fatalf("%+v", entry) + } + } + return log +} + +func is(p *string, s string) bool { return p != nil && *p == s } + +func contains(p *string, s string) bool { return p != nil && strings.Contains(*p, s) } + +// hasEntry fails the test when no entry of log matches. +func hasEntry(t *testing.T, log []AuditEntry, what string, match func(AuditEntry) bool) { + t.Helper() + if !slices.ContainsFunc(log, match) { + t.Fatalf("no log entry for %s: %s", what, jsonText(log)) + } +} + +// checkLog checks the entries every test leaves in the activity log. +func (e *e2e) checkLog(update string) { + e.t.Helper() + log := e.log() + ro := func(a AuditEntry) bool { return is(a.ConnectionID, e.ro) && is(a.ConnectionName, e.roName) } + rw := func(a AuditEntry) bool { return is(a.ConnectionID, e.rw) && is(a.ConnectionName, e.rwName) } + hasEntry(e.t, log, "list_connections", func(a AuditEntry) bool { + return a.Tool == "list_connections" && a.OK && a.ConnectionID == nil + }) + hasEntry(e.t, log, "search_objects", func(a AuditEntry) bool { return a.Tool == "search_objects" && a.OK && ro(a) }) + hasEntry(e.t, log, "a read", func(a AuditEntry) bool { return a.Tool == "query" && a.OK && ro(a) && a.Rows != nil }) + hasEntry(e.t, log, "the update", func(a AuditEntry) bool { + return a.Tool == "execute" && a.OK && rw(a) && a.Rows != nil && *a.Rows == 1 && is(a.Detail, e.n(update)) + }) + hasEntry(e.t, log, "a refused change", func(a AuditEntry) bool { + return a.Tool == "query" && !a.OK && ro(a) && contains(a.Error, readOnlyMsg) + }) + hasEntry(e.t, log, "execute on the read connection", func(a AuditEntry) bool { return a.Tool == "execute" && !a.OK && ro(a) }) + hasEntry(e.t, log, "the time limit", func(a AuditEntry) bool { + return !a.OK && a.ConnectionID != nil && contains(a.Error, "longer than") + }) + hasEntry(e.t, log, "the off connection", func(a AuditEntry) bool { + return !a.OK && a.ConnectionID == nil && a.Tool == "list_schemas" + }) +} + +func eqFold(v any, s string) bool { + text, ok := v.(string) + return ok && equalFoldASCII(text, s) +} + +func args(kv ...any) map[string]any { + out := map[string]any{} + for i := 0; i+1 < len(kv); i += 2 { + out[kv[i].(string)] = kv[i+1] + } + return out +} + +// --------------------------------------------------------------------------- +// SQL engines + +// sqlSpec is what differs between SQL engines in the shared checks. +type sqlSpec struct { + tag string + // child is the child table as written in SQL. + child string + // setup creates the parent and child tables and fills them: parents 1 + // one, 2 two, 3 three; children 10→1 'a', 11→1 NULL, 12→2 'c'. + setup []string + // cleanup drops everything the test may create. + cleanup []string + // refusedReads are refused by the read check on this engine only. + refusedReads []string + // txControl is transaction control, refused by execute. + txControl []string + // quick is a read that returns one row. + quick string + // deletePlan is part of the plan of DELETE FROM lq_mcp_e2e_parent WHERE + // id = 3, if any. + deletePlan string +} + +// sqlCommon runs the checks from the connection list to the read check +// refusals, on fresh tables. +func sqlCommon(e *e2e, spec *sqlSpec) { + t := e.t + t.Helper() + ro, rw := e.ro, e.rw + parent, child := e.n(e2eParent), e.n(e2eChild) + e.checkConnections() + + // Setup through the write connection. + for _, stmt := range spec.setup { + r := e.write(stmt) + if strings.HasPrefix(strings.ToLower(strings.TrimSpace(stmt)), "insert") && r["rowsAffected"] != float64(3) { + t.Fatalf("%s: %v", stmt, r) + } + } + + // Catalog. + d := e.ok("describe_table", args("connection", ro, "table", e2eChild)) + s := structuredOf(d) + if s["table"] != child { + t.Fatal(jsonText(s)) + } + cols := arr(s["columns"]) + names := []string{} + for _, c := range cols { + names = append(names, lowerASCII(mapOf(c)["name"].(string))) + } + if !slices.Equal(names, []string{"id", "parent_id", "note"}) || + mapOf(cols[0])["primaryKey"] != true || mapOf(cols[1])["primaryKey"] != false || + mapOf(cols[1])["nullable"] != false || mapOf(cols[2])["nullable"] != true { + t.Fatal(jsonText(s)) + } + fks := arr(s["foreignKeys"]) + if len(fks) != 1 { + t.Fatal(jsonText(s)) + } + fk := mapOf(fks[0]) + if !eqFold(fk["name"], e.n("lq_mcp_e2e_fk")) || !eqFold(fk["refTable"], parent) || + !eqFold(arr(fk["columns"])[0], "parent_id") || !eqFold(arr(fk["refColumns"])[0], "id") { + t.Fatal(jsonText(s)) + } + if !strings.Contains(textOf(d), "PK") { + t.Fatal(textOf(d)) + } + + // Parent by its unquoted name in another case: the catalog finds it. + d = e.ok("describe_table", args("connection", ro, "table", strings.ToUpper(parent))) + s = structuredOf(d) + if !eqFold(s["table"], parent) || + !slices.ContainsFunc(arr(s["referencedBy"]), func(f any) bool { return mapOf(f)["table"] == child }) { + t.Fatal(jsonText(s)) + } + if m := e.refused("describe_table", args("connection", ro, "table", "lq_mcp_e2e_missing")); !strings.Contains(m, "not found") { + t.Fatal(m) + } + + found := e.ok("search_objects", args("connection", ro, "pattern", "lq_mcp_e2e")) + matches := arr(structuredOf(found)["matches"]) + for _, table := range []string{parent, child} { + if !slices.ContainsFunc(matches, func(m any) bool { + return eqFold(mapOf(m)["table"], table) && mapOf(m)["column"] == nil + }) { + t.Fatalf("%s: %s", table, jsonText(matches)) + } + } + found = e.ok("search_objects", args("connection", ro, "pattern", "parent_id", "limit", 200)) + matches = arr(structuredOf(found)["matches"]) + if !slices.ContainsFunc(matches, func(m any) bool { + return mapOf(m)["table"] == child && eqFold(mapOf(m)["column"], "parent_id") + }) { + t.Fatal(jsonText(matches)) + } + + schemas := e.ok("list_schemas", args("connection", ro)) + current, ok := structuredOf(schemas)["current"].(string) + if !ok || !slices.ContainsFunc(arr(structuredOf(schemas)["schemas"]), func(s any) bool { return eqFold(s, current) }) { + t.Fatalf("%s: %s", current, textOf(schemas)) + } + tables := e.ok("list_tables", args("connection", ro)) + s = structuredOf(tables) + if s["schema"] != current { + t.Fatal(jsonText(s)) + } + for _, table := range []string{parent, child} { + if !slices.ContainsFunc(arr(s["tables"]), func(o any) bool { + return eqFold(mapOf(o)["name"], table) && mapOf(o)["kind"] == "table" + }) { + t.Fatalf("%s: %s", table, jsonText(s)) + } + } + tables = e.ok("list_tables", args("connection", ro, "schema", current)) + if len(arr(structuredOf(tables)["tables"])) < 2 { + t.Fatal(textOf(tables)) + } + + // Plans, without running the statement. + plan := e.ok("explain", args("connection", ro, "sql", "SELECT * FROM "+spec.child+" WHERE parent_id = 1")) + if strings.TrimSpace(textOf(plan)) == "" { + t.Fatal("empty plan") + } + plan = e.ok("explain", args("connection", ro, "sql", "DELETE FROM lq_mcp_e2e_parent WHERE id = 3")) + if strings.TrimSpace(textOf(plan)) == "" { + t.Fatal("empty plan") + } + if spec.deletePlan != "" && !strings.Contains(textOf(plan), e.n(spec.deletePlan)) { + t.Fatal(textOf(plan)) + } + if m := e.refused("explain", args("connection", ro, "sql", "EXPLAIN SELECT 1")); !strings.Contains(m, "Pass the statement itself") { + t.Fatal(m) + } + + // Queries on the read connection. + const parents = "[1, one] [2, two] [3, three]" + q := e.ok("query", args("connection", ro, "sql", "SELECT id, name FROM lq_mcp_e2e_parent ORDER BY id;")) + if showRows(rowsOf(q)) != parents || structuredOf(q)["rowCount"] != float64(3) || structuredOf(q)["truncated"] != false { + t.Fatal(jsonText(q)) + } + if !strings.Contains(textOf(q), "| 2 | two |") { + t.Fatal(textOf(q)) + } + q = e.ok("query", args("connection", ro, "sql", "SELECT id, name FROM lq_mcp_e2e_parent ORDER BY id", "max_rows", 2)) + if showRows(rowsOf(q)) != "[1, one] [2, two]" || structuredOf(q)["rowCount"] != float64(2) || structuredOf(q)["truncated"] != true { + t.Fatal(jsonText(q)) + } + if !strings.Contains(textOf(q), "more rows exist") { + t.Fatal(textOf(q)) + } + joined := e.read("SELECT c.id, p.name, c.note FROM " + spec.child + " c JOIN lq_mcp_e2e_parent p ON p.id = c.parent_id ORDER BY c.id") + if got := showRows(joined); got != "[10, one, a] [11, one, ] [12, two, c]" { + t.Fatal(got) + } + if m := e.refused("query", args("connection", ro, "sql", "SELECT nope FROM lq_mcp_e2e_parent")); !strings.Contains(strings.ToLower(m), "nope") { + t.Fatal(m) + } + + // Read-only, check level: refused before reaching the server. + common := []string{ + "INSERT INTO lq_mcp_e2e_parent (id, name) VALUES (9, 'x')", + "UPDATE lq_mcp_e2e_parent SET name = 'x'", + "DELETE FROM lq_mcp_e2e_parent", + "TRUNCATE TABLE lq_mcp_e2e_parent", + "DROP TABLE lq_mcp_e2e_parent", + "CREATE TABLE lq_mcp_e2e_x (id int)", + "ALTER TABLE lq_mcp_e2e_parent ADD extra int", + "WITH x AS (SELECT 1 AS n) DELETE FROM lq_mcp_e2e_parent", + } + for _, stmt := range append(common, spec.refusedReads...) { + if m := e.refused("query", args("connection", ro, "sql", stmt)); !strings.Contains(m, readOnlyMsg) { + t.Fatalf("%s: %s", stmt, m) + } + } + if m := e.refused("query", args("connection", ro, "sql", "SELECT 1 FROM lq_mcp_e2e_parent; DELETE FROM lq_mcp_e2e_parent")); !strings.Contains(m, "one statement per call") { + t.Fatal(m) + } + for _, stmt := range []string{ + "DELETE FROM lq_mcp_e2e_parent", + "DROP TABLE lq_mcp_e2e_parent", + "SELECT 1 FROM lq_mcp_e2e_parent", + } { + if m := e.refused("execute", args("connection", ro, "sql", stmt)); !strings.Contains(m, readOnlyMsg) { + t.Fatalf("%s: %s", stmt, m) + } + } + // query on the write connection is still read-only. + if m := e.refused("query", args("connection", rw, "sql", "DELETE FROM lq_mcp_e2e_parent")); !strings.Contains(m, "use execute") { + t.Fatal(m) + } + checkUnchanged(e, spec.child, "one", "two", "three") +} + +// checkUnchanged: the tables hold what setup wrote, with these parent +// names, as the write connection sees them. +func checkUnchanged(e *e2e, child string, names ...string) { + e.t.Helper() + parents := e.query(e.rw, "SELECT id, name FROM lq_mcp_e2e_parent ORDER BY id") + want := []string{} + for i, n := range names { + want = append(want, "["+strconv.Itoa(i+1)+", "+n+"]") + } + if got := showRows(parents); got != strings.Join(want, " ") { + e.t.Fatal(got) + } + if n := e.value("SELECT count(*) FROM " + child); !is(n, "3") { + e.t.Fatal(n) + } +} + +// sqlWrites: the update commits and the read connection sees it; +// transaction control is refused. +func sqlWrites(e *e2e, spec *sqlSpec) { + t := e.t + t.Helper() + if r := e.write(e2eUpdate); r["rowsAffected"] != float64(1) { + t.Fatal(jsonText(r)) + } + if got := showRows(e.read("SELECT name FROM lq_mcp_e2e_parent WHERE id = 1")); got != "[uno]" { + t.Fatal(got) + } + for _, stmt := range spec.txControl { + if m := e.refused("execute", args("connection", e.rw, "sql", stmt)); !strings.Contains(m, "Transaction control") { + t.Fatalf("%s: %s", stmt, m) + } + } + m := e.refused("execute", args("connection", e.rw, "sql", + "UPDATE lq_mcp_e2e_parent SET name = 'a' WHERE id = 2; UPDATE lq_mcp_e2e_parent SET name = 'b' WHERE id = 3")) + if !strings.Contains(m, "one statement per call") { + t.Fatal(m) + } + checkUnchanged(e, spec.child, "uno", "two", "three") +} + +// sqlEngine runs the checks of one SQL engine: engine holds the +// engine-level read-only checks, tail the transaction and time-limit checks. +func sqlEngine(t *testing.T, target string, spec *sqlSpec, engine, tail func(e *e2e)) { + e := startE2e(t, target, spec.tag, spec.cleanup) + sqlCommon(e, spec) + engine(e) + checkUnchanged(e, spec.child, "one", "two", "three") + sqlWrites(e, spec) + tail(e) + checkUnchanged(e, spec.child, "uno", "two", "three") + e.checkLog(e2eUpdate) +} + +// --------------------------------------------------------------------------- +// PostgreSQL + +var pgSpec = sqlSpec{ + tag: "pg", + child: `"lq_mcp_e2e Child"`, + setup: []string{ + "CREATE TABLE lq_mcp_e2e_parent (id int PRIMARY KEY, name text NOT NULL)", + `CREATE TABLE "lq_mcp_e2e Child" (id int PRIMARY KEY, ` + + "parent_id int NOT NULL CONSTRAINT lq_mcp_e2e_fk REFERENCES lq_mcp_e2e_parent (id), note text)", + "INSERT INTO lq_mcp_e2e_parent VALUES (1, 'one'), (2, 'two'), (3, 'three')", + `INSERT INTO "lq_mcp_e2e Child" VALUES (10, 1, 'a'), (11, 1, NULL), (12, 2, 'c')`, + // Writes, but reads like a plain function call. + "CREATE FUNCTION lq_mcp_e2e_touch() RETURNS int LANGUAGE plpgsql AS $$ " + + "BEGIN UPDATE lq_mcp_e2e_parent SET name = 'touched' WHERE id = 1; RETURN 1; END $$", + }, + cleanup: []string{ + "DROP FUNCTION IF EXISTS lq_mcp_e2e_touch()", + `DROP TABLE IF EXISTS "lq_mcp_e2e Child"`, + "DROP TABLE IF EXISTS lq_mcp_e2e_parent", + }, + refusedReads: []string{ + "SELECT setval('lq_mcp_e2e_seq', 5)", + "SELECT nextval('lq_mcp_e2e_seq')", + "SELECT set_config('default_transaction_read_only', 'off', false)", + "EXPLAIN ANALYZE DELETE FROM lq_mcp_e2e_parent", + "SELECT * INTO lq_mcp_e2e_copy FROM lq_mcp_e2e_parent", + "COPY lq_mcp_e2e_parent TO STDOUT", + "CALL lq_mcp_e2e_proc()", + }, + txControl: []string{"BEGIN", "START TRANSACTION", "COMMIT", "ROLLBACK", "SAVEPOINT x", "END"}, + quick: "SELECT 1", + deletePlan: "Delete on lq_mcp_e2e_parent", +} + +func TestMCPPostgresServer(t *testing.T) { + sqlEngine(t, "postgres", &pgSpec, func(e *e2e) { + ro := e.ro + const objects = "SELECT count(*) FROM pg_largeobject_metadata" + largeObjects := e.value(objects) + // The read check lets a user function through; the read-only + // transaction refuses the write inside it. + if m := e.refused("query", args("connection", ro, "sql", "SELECT lq_mcp_e2e_touch()")); !strings.Contains(m, "read-only transaction") { + t.Fatal(m) + } + // Large objects are refused before they reach the server. + if m := e.refused("query", args("connection", ro, "sql", "SELECT lo_creat(-1)")); !strings.Contains(m, "not allowed") { + t.Fatal(m) + } + if got := e.value(objects); jsonText(got) != jsonText(largeObjects) { + t.Fatal(got) + } + + // The agent's session itself refuses writes. + err := e.onRead(kindRead, func(ctx context.Context, s drivers.Session) error { + _, err := execOn(ctx, s, e.n("UPDATE lq_mcp_e2e_parent SET name = 'x' WHERE id = 1")) + return err + }) + if err == nil || !strings.Contains(apperr.From(err).Message, "read-only transaction") { + t.Fatal(err) + } + // A call that turns its own transaction read-write (SET is not a + // read, so agents cannot) still has its work rolled back. + var affected *uint64 + err = e.onRead(kindRead, func(ctx context.Context, s drivers.Session) error { + if _, err := execOn(ctx, s, "SET TRANSACTION READ WRITE"); err != nil { + return err + } + r, err := execOn(ctx, s, e.n("UPDATE lq_mcp_e2e_parent SET name = 'x' WHERE id = 3")) + if r != nil { + affected = r.RowsAffected + } + return err + }) + if err != nil || affected == nil || *affected != 1 { + t.Fatal(affected, err) + } + }, func(e *e2e) { + e.checkTimeLimit(e.ro, "query", "SELECT pg_sleep(30)", pgSpec.quick) + }) +} + +// --------------------------------------------------------------------------- +// MySQL and MariaDB + +var mysqlSpec = sqlSpec{ + tag: "mysql", + child: "`lq_mcp_e2e Child`", + setup: []string{ + "CREATE TABLE lq_mcp_e2e_parent (id int PRIMARY KEY, name varchar(50) NOT NULL) ENGINE=InnoDB", + "CREATE TABLE `lq_mcp_e2e Child` (id int PRIMARY KEY, parent_id int NOT NULL, note varchar(50), " + + "CONSTRAINT lq_mcp_e2e_fk FOREIGN KEY (parent_id) REFERENCES lq_mcp_e2e_parent (id)) ENGINE=InnoDB", + "INSERT INTO lq_mcp_e2e_parent VALUES (1, 'one'), (2, 'two'), (3, 'three')", + "INSERT INTO `lq_mcp_e2e Child` VALUES (10, 1, 'a'), (11, 1, NULL), (12, 2, 'c')", + // Writes, but reads like a plain function call. + "CREATE FUNCTION lq_mcp_e2e_touch() RETURNS int DETERMINISTIC MODIFIES SQL DATA " + + "BEGIN UPDATE lq_mcp_e2e_parent SET name = 'touched' WHERE id = 1; RETURN 1; END", + // Leaves a transaction open when called. + "CREATE PROCEDURE lq_mcp_e2e_open() " + + "BEGIN START TRANSACTION; UPDATE lq_mcp_e2e_parent SET name = 'open' WHERE id = 2; END", + }, + cleanup: []string{ + "DROP FUNCTION IF EXISTS lq_mcp_e2e_touch", + "DROP PROCEDURE IF EXISTS lq_mcp_e2e_open", + "DROP TABLE IF EXISTS `lq_mcp_e2e Child`, lq_mcp_e2e_parent", + }, + refusedReads: []string{ + "REPLACE INTO lq_mcp_e2e_parent VALUES (9, 'x')", + "SELECT * FROM lq_mcp_e2e_parent INTO OUTFILE '/tmp/lq_mcp_e2e'", + "SELECT name INTO @x FROM lq_mcp_e2e_parent LIMIT 1", + "SET @x = 1", + "CALL lq_mcp_e2e_open()", + "DO SLEEP(1)", + "EXPLAIN ANALYZE SELECT * FROM lq_mcp_e2e_parent", + "LOCK TABLES lq_mcp_e2e_parent READ", + }, + txControl: []string{ + "START TRANSACTION", + "BEGIN", + "BEGIN WORK", + "COMMIT", + "ROLLBACK", + "SAVEPOINT x", + "SET autocommit = 0", + "SET @@session.autocommit = 0", + "LOCK TABLES lq_mcp_e2e_parent WRITE", + "XA START 'lq_mcp_e2e'", + }, + quick: "SELECT 1", + // Older MySQL trees do not show single-table DELETE. +} + +func TestMCPMySQLServer(t *testing.T) { + sqlEngine(t, "mysql", &mysqlSpec, func(e *e2e) { + readOnlyTx := func(m string) bool { return strings.Contains(strings.ToLower(m), "read only transaction") } + // The read check lets the call through; the READ ONLY transaction + // refuses the UPDATE inside. + touch := args("connection", e.ro, "sql", "SELECT lq_mcp_e2e_touch()") + if m := e.refused("query", touch); !readOnlyTx(m) { + t.Fatal(m) + } + // The agent's session itself refuses writes. + insert := e.n("INSERT INTO lq_mcp_e2e_parent VALUES (99, 'x')") + err := e.onRead(kindRead, func(ctx context.Context, s drivers.Session) error { + _, err := execOn(ctx, s, insert) + return err + }) + if err == nil || !readOnlyTx(apperr.From(err).Message) { + t.Fatal(err) + } + // A read-write session default does not reach the transaction each + // call starts. + err = e.onRead(kindRead, func(ctx context.Context, s drivers.Session) error { + if _, err := execOn(ctx, s, "SET SESSION TRANSACTION READ WRITE"); err != nil { + return err + } + _, err := execOn(ctx, s, insert) + return err + }) + if err == nil { + t.Fatal("the insert ran") + } + if m := e.refused("query", touch); !readOnlyTx(m) { + t.Fatal(m) + } + _ = e.onRead(kindRead, func(ctx context.Context, s drivers.Session) error { + _, err := execOn(ctx, s, "SET SESSION TRANSACTION READ ONLY") + return err + }) + }, func(e *e2e) { + // A procedure that opens a transaction: rolled back and refused. + if m := e.refused("execute", args("connection", e.rw, "sql", "CALL lq_mcp_e2e_open()")); !strings.Contains(m, "left a transaction open") { + t.Fatal(m) + } + e.checkTimeLimit(e.ro, "query", "SELECT SLEEP(30)", mysqlSpec.quick) + }) +} + +// --------------------------------------------------------------------------- +// SQL Server + +var mssqlSpec = sqlSpec{ + tag: "mssql", + child: "[lq_mcp_e2e Child]", + setup: []string{ + "CREATE TABLE lq_mcp_e2e_parent (id int PRIMARY KEY, name nvarchar(50) NOT NULL)", + "CREATE TABLE [lq_mcp_e2e Child] (id int PRIMARY KEY, parent_id int NOT NULL " + + "CONSTRAINT lq_mcp_e2e_fk REFERENCES lq_mcp_e2e_parent (id), note nvarchar(50) NULL)", + "INSERT INTO lq_mcp_e2e_parent VALUES (1, N'one'), (2, N'two'), (3, N'three')", + "INSERT INTO [lq_mcp_e2e Child] VALUES (10, 1, N'a'), (11, 1, NULL), (12, 2, N'c')", + }, + cleanup: []string{ + "DROP TABLE IF EXISTS [lq_mcp_e2e Child]", + "DROP TABLE IF EXISTS lq_mcp_e2e_parent", + "DROP TABLE IF EXISTS lq_mcp_e2e_tmp", + }, + refusedReads: []string{ + "SELECT 1 DELETE FROM lq_mcp_e2e_parent", + "SELECT 1 WAITFOR DELAY '00:00:01'", + "EXEC sp_who", + "SELECT * INTO lq_mcp_e2e_copy FROM lq_mcp_e2e_parent", + "DECLARE @x int", + "SET NOCOUNT ON", + "SELECT * FROM OPENROWSET('SQLNCLI', 'x', 'SELECT 1')", + "MERGE lq_mcp_e2e_parent AS t USING (SELECT 1 AS id) AS s ON t.id = s.id WHEN MATCHED THEN DELETE;", + }, + txControl: []string{ + "BEGIN TRAN", + "BEGIN TRANSACTION", + "COMMIT", + "ROLLBACK", + "SAVE TRAN x", + "SET IMPLICIT_TRANSACTIONS ON", + }, + quick: "SELECT 1", + deletePlan: "Delete", +} + +func TestMCPSQLServerServer(t *testing.T) { + sqlEngine(t, "sqlserver", &mssqlSpec, func(e *e2e) { + // No read the check accepts writes here, so check the session: + // every call of a read connection runs in a transaction that is + // rolled back, DDL included. + inTx := false + err := e.onRead(kindRead, func(ctx context.Context, s drivers.Session) error { + if _, err := execOn(ctx, s, e.n("INSERT INTO lq_mcp_e2e_parent VALUES (99, N'x')")); err != nil { + return err + } + if _, err := execOn(ctx, s, e.n("CREATE TABLE lq_mcp_e2e_tmp (id int)")); err != nil { + return err + } + inTx = s.TxState().InTransaction + return nil + }) + if err != nil || !inTx { + t.Fatal(inTx, err) + } + if n := e.value("SELECT count(*) FROM lq_mcp_e2e_parent WHERE id = 99"); !is(n, "0") { + t.Fatal(n) + } + if n := e.value("SELECT count(*) FROM sys.tables WHERE name = 'lq_mcp_e2e_tmp'"); !is(n, "0") { + t.Fatal(n) + } + // The read connection keeps working after that. + if got := showRows(e.read("SELECT count(*) FROM lq_mcp_e2e_parent")); got != "[3]" { + t.Fatal(got) + } + }, func(e *e2e) { + // A batch that opens a transaction without BEGIN TRAN first: rolled + // back and refused. + m := e.refused("execute", args("connection", e.rw, "sql", + "BEGIN TRY BEGIN TRANSACTION UPDATE lq_mcp_e2e_parent SET name = N'open' WHERE id = 2 END TRY BEGIN CATCH END CATCH")) + if !strings.Contains(m, "left a transaction open") { + t.Fatal(m) + } + // WAITFOR is not a read: the write connection waits. + e.checkTimeLimit(e.rw, "execute", "WAITFOR DELAY '00:00:20'", mssqlSpec.quick) + }) +} + +// --------------------------------------------------------------------------- +// Oracle + +var oracleSpec = sqlSpec{ + tag: "ora", + child: `"lq_mcp_e2e Child"`, + setup: []string{ + "create table lq_mcp_e2e_parent (id number primary key, name varchar2(50) not null)", + `create table "lq_mcp_e2e Child" (id number primary key, parent_id number not null ` + + "constraint lq_mcp_e2e_fk references lq_mcp_e2e_parent (id), note varchar2(50))", + "insert into lq_mcp_e2e_parent select 1, 'one' from dual union all " + + "select 2, 'two' from dual union all select 3, 'three' from dual", + `insert into "lq_mcp_e2e Child" select 10, 1, 'a' from dual union all ` + + "select 11, 1, null from dual union all select 12, 2, 'c' from dual", + }, + cleanup: []string{ + `drop table "lq_mcp_e2e Child" purge`, + "drop table lq_mcp_e2e_parent purge", + }, + refusedReads: []string{ + "BEGIN NULL; END;", + "MERGE INTO lq_mcp_e2e_parent t USING dual ON (t.id = 1) WHEN MATCHED THEN UPDATE SET t.name = 'x'", + "SELECT lq_mcp_e2e_seq.nextval FROM dual", + "LOCK TABLE lq_mcp_e2e_parent IN EXCLUSIVE MODE", + "CALL dbms_session.sleep(1)", + "ALTER SESSION SET current_schema = sys", + }, + txControl: []string{"COMMIT", "ROLLBACK", "SAVEPOINT x", "ROLLBACK TO SAVEPOINT x"}, + quick: "SELECT 1 FROM dual", + deletePlan: "DELETE", +} + +func TestMCPOracleServer(t *testing.T) { + sqlEngine(t, "oracle", &oracleSpec, func(e *e2e) { + // FOR UPDATE passes the read check (it only locks); a READ ONLY + // transaction refuses it. + m := e.refused("query", args("connection", e.ro, "sql", "SELECT id FROM lq_mcp_e2e_parent WHERE id = 1 FOR UPDATE")) + if !strings.Contains(m, "ORA-") { + t.Fatal(m) + } + // The agent's session itself refuses writes. + insert := e.n("INSERT INTO lq_mcp_e2e_parent VALUES (99, 'x')") + err := e.onRead(kindRead, func(ctx context.Context, s drivers.Session) error { + _, err := execOn(ctx, s, insert) + return err + }) + if err == nil || apperr.From(err).Code != "ORA-01456" { + t.Fatal(err) + } + // explain skips SET TRANSACTION READ ONLY (EXPLAIN PLAN writes + // PLAN_TABLE): what such a call writes is rolled back. + inTx := false + err = e.onRead(kindExplain, func(ctx context.Context, s drivers.Session) error { + if _, err := execOn(ctx, s, insert); err != nil { + return err + } + inTx = s.TxState().InTransaction + return nil + }) + if err != nil || !inTx { + t.Fatal(inTx, err) + } + if n := e.value("SELECT count(*) FROM lq_mcp_e2e_parent WHERE id = 99"); !is(n, "0") { + t.Fatal(n) + } + }, func(e *e2e) { + // No sleep can be called from a read, and the driver may not + // interrupt a call: the session is dropped and the next call opens + // another. + e.checkTimeLimit(e.rw, "execute", "BEGIN DBMS_SESSION.SLEEP(8); END;", oracleSpec.quick) + }) +} + +// --------------------------------------------------------------------------- +// Redis + +// cells returns the values of a Redis reply, row by row. +func cells(result map[string]any) []string { + out := []string{} + for _, row := range rowsOf(result) { + for _, v := range row { + if v != nil { + out = append(out, *v) + } + } + } + return out +} + +func TestMCPRedisServer(t *testing.T) { + e := startE2e(t, "redis", "redis", []string{"DEL lq_mcp_e2e:str lq_mcp_e2e:hash lq_mcp_e2e:list lq_mcp_e2e:none"}) + ro, rw := e.ro, e.rw + e.checkConnections() + + e.write("SET lq_mcp_e2e:str hello") + e.write("HSET lq_mcp_e2e:hash f1 v1 f2 v2") + e.write("RPUSH lq_mcp_e2e:list a b c") + + // Keys and databases. + found := e.ok("search_objects", args("connection", ro, "pattern", "lq_mcp_e2e:")) + matches := arr(structuredOf(found)["matches"]) + for _, key := range []string{"lq_mcp_e2e:str", "lq_mcp_e2e:hash", "lq_mcp_e2e:list"} { + if !slices.ContainsFunc(matches, func(m any) bool { return mapOf(m)["table"] == e.n(key) && mapOf(m)["kind"] == "key" }) { + t.Fatalf("%s: %s", key, jsonText(matches)) + } + } + schemas := e.ok("list_schemas", args("connection", ro)) + if structuredOf(schemas)["current"] != "db0" { + t.Fatal(textOf(schemas)) + } + tables := e.ok("list_tables", args("connection", ro)) + objects := arr(structuredOf(tables)["tables"]) + for _, k := range [][2]string{{"lq_mcp_e2e:str", "string"}, {"lq_mcp_e2e:hash", "hash"}, {"lq_mcp_e2e:list", "list"}} { + if !slices.ContainsFunc(objects, func(o any) bool { return mapOf(o)["name"] == e.n(k[0]) && mapOf(o)["kind"] == k[1] }) { + t.Fatalf("%s: %s", k[0], jsonText(objects)) + } + } + if m := e.refused("describe_table", args("connection", ro, "table", "lq_mcp_e2e:str")); !strings.Contains(m, "no columns") { + t.Fatal(m) + } + if m := e.refused("explain", args("connection", ro, "sql", "GET lq_mcp_e2e:str")); !strings.Contains(m, "no execution plans") { + t.Fatal(m) + } + + // Reads. + get := func(key string) map[string]any { return args("connection", ro, "sql", "GET "+key) } + if c := cells(e.ok("query", get("lq_mcp_e2e:str"))); !slices.Equal(c, []string{"hello"}) { + t.Fatal(c) + } + c := cells(e.ok("query", args("connection", ro, "sql", "HGETALL lq_mcp_e2e:hash"))) + if !slices.Contains(c, "f1") || !slices.Contains(c, "v2") { + t.Fatal(c) + } + r := e.ok("query", args("connection", ro, "sql", "LRANGE lq_mcp_e2e:list 0 -1", "max_rows", 2)) + // Lists come with their index. + if c := cells(r); !slices.Equal(c, []string{"1", "a", "2", "b"}) || structuredOf(r)["truncated"] != true { + t.Fatal(c, jsonText(r)) + } + if c := cells(e.ok("query", args("connection", ro, "sql", "SCAN 0 MATCH lq_mcp_e2e:* COUNT 1000"))); len(c) == 0 { + t.Fatal("empty scan") + } + + // Read-only: the read connection only takes read commands. + for _, cmd := range []string{ + "SET lq_mcp_e2e:str x", + "DEL lq_mcp_e2e:str", + "HSET lq_mcp_e2e:hash f1 x", + "EXPIRE lq_mcp_e2e:str 1", + "RPOP lq_mcp_e2e:list", + "FLUSHDB", + `EVAL "return 1" 0`, + "CONFIG SET maxmemory 1", + "BLPOP lq_mcp_e2e:list 1", + "MULTI", + } { + if m := e.refused("query", args("connection", ro, "sql", cmd)); !strings.Contains(m, readOnlyMsg) { + t.Fatalf("%s: %s", cmd, m) + } + } + if m := e.refused("execute", args("connection", ro, "sql", "SET lq_mcp_e2e:str x")); !strings.Contains(m, readOnlyMsg) { + t.Fatal(m) + } + if m := e.refused("query", args("connection", ro, "sql", "KEYS lq_mcp_e2e:*")); !strings.Contains(m, "SCAN 0 MATCH") { + t.Fatal(m) + } + if c := cells(e.ok("query", get("lq_mcp_e2e:str"))); !slices.Equal(c, []string{"hello"}) { + t.Fatal(c) + } + if c := cells(e.ok("query", args("connection", ro, "sql", "TTL lq_mcp_e2e:str"))); !slices.Equal(c, []string{"-1"}) { + t.Fatal(c) + } + if c := cells(e.ok("query", args("connection", ro, "sql", "LLEN lq_mcp_e2e:list"))); !slices.Equal(c, []string{"3"}) { + t.Fatal(c) + } + + // Writes on the write connection; session commands stay refused. + e.write("SET lq_mcp_e2e:str world") + if c := cells(e.ok("query", get("lq_mcp_e2e:str"))); !slices.Equal(c, []string{"world"}) { + t.Fatal(c) + } + for _, cmd := range []string{"MULTI", "SELECT 1", "CLIENT KILL TYPE normal"} { + if m := e.refused("execute", args("connection", rw, "sql", cmd)); !strings.Contains(m, "not available to agents") { + t.Fatalf("%s: %s", cmd, m) + } + } + if m := e.refused("query", args("connection", rw, "sql", "DEL lq_mcp_e2e:str")); !strings.Contains(m, "use execute") { + t.Fatal(m) + } + + // A blocking command past the time limit is unblocked. + e.checkTimeLimit(rw, "execute", "BLPOP lq_mcp_e2e:none 20", "GET lq_mcp_e2e:str") + if c := cells(e.ok("query", get("lq_mcp_e2e:str"))); !slices.Equal(c, []string{"world"}) { + t.Fatal(c) + } + + // Activity log. + log := e.log() + on := func(a AuditEntry, id string) bool { return is(a.ConnectionID, id) } + hasEntry(t, log, "list_connections", func(a AuditEntry) bool { return a.Tool == "list_connections" && a.OK }) + hasEntry(t, log, "search_objects", func(a AuditEntry) bool { + return a.Tool == "search_objects" && a.OK && on(a, ro) && a.Rows != nil && *a.Rows >= 3 + }) + hasEntry(t, log, "the write", func(a AuditEntry) bool { + return a.Tool == "execute" && a.OK && on(a, rw) && is(a.Detail, e.n("SET lq_mcp_e2e:str world")) + }) + hasEntry(t, log, "KEYS", func(a AuditEntry) bool { + return a.Tool == "query" && !a.OK && on(a, ro) && is(a.Detail, e.n("KEYS lq_mcp_e2e:*")) && contains(a.Error, "SCAN") + }) + hasEntry(t, log, "the time limit", func(a AuditEntry) bool { + return a.Tool == "execute" && !a.OK && on(a, rw) && contains(a.Error, "longer than") + }) + hasEntry(t, log, "the off connection", func(a AuditEntry) bool { + return !a.OK && a.Tool == "list_schemas" && a.ConnectionID == nil + }) +} + +// --------------------------------------------------------------------------- +// Cassandra + +func TestMCPCassandraServer(t *testing.T) { + const ks = "lq_mcp_e2e" + e := startE2e(t, "cassandra", "cassandra", []string{"DROP KEYSPACE IF EXISTS " + ks}) + ro, rw := e.ro, e.rw + keyspace := e.n(ks) + e.checkConnections() + list := e.ok("list_connections", args()) + conns := arr(structuredOf(list)["connections"]) + if mapOf(conns[0])["engine"] != "Cassandra" || !strings.Contains(mapOf(conns[0])["dialect"].(string), "ALLOW FILTERING") { + t.Fatal(jsonText(conns)) + } + + // The write connection creates a keyspace, a type and a table. Names are + // keyspace-qualified: no call may change the session keyspace. + e.write("CREATE KEYSPACE " + ks + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}") + e.write("CREATE TYPE " + ks + ".addr (street text, zip int)") + e.write("CREATE TABLE " + ks + ".items (id int, seq int, name text, tags set, " + + "home frozen, PRIMARY KEY (id, seq))") + insert := "INSERT INTO " + ks + ".items (id, seq, name, tags) VALUES (1, 1, 'uno', {'a', 'b'})" + e.write(insert) + // A batch is one statement, semicolons and all. + e.write("BEGIN BATCH " + + "INSERT INTO " + ks + ".items (id, seq, name) VALUES (1, 2, 'it''s; two'); " + + "INSERT INTO " + ks + ".items (id, seq, name) VALUES (2, 1, 'tres'); " + + "APPLY BATCH;") + e.write("UPDATE " + ks + ".items SET home = {street: 'Main', zip: 12345} WHERE id = 1 AND seq = 1") + + // Reads on the read connection. + if got := showRows(e.read("SELECT seq, name, tags FROM " + ks + ".items WHERE id = 1")); got != "[1, uno, {'a', 'b'}] [2, it's; two, ]" { + t.Fatal(got) + } + if got := showRows(e.read("SELECT home FROM " + ks + ".items WHERE id = 1 AND seq = 1;")); got != "[{street: 'Main', zip: 12345}]" { + t.Fatal(got) + } + if got := showRows(e.read("SELECT name FROM " + ks + ".items WHERE name = 'tres' ALLOW FILTERING")); got != "[tres]" { + t.Fatal(got) + } + r := e.ok("query", args("connection", ro, "max_rows", 1, "sql", "SELECT seq FROM "+ks+".items WHERE id = 1 -- ; INSERT\n")) + if len(rowsOf(r)) != 1 || structuredOf(r)["truncated"] != true { + t.Fatal(jsonText(r)) + } + + // Read-only: SELECT and LIST only, whatever the statement hides. + for _, sql := range []string{ + "INSERT INTO " + ks + ".items (id, seq) VALUES (9, 9)", + "UPDATE " + ks + ".items SET name = 'x' WHERE id = 1 AND seq = 1", + "DELETE FROM " + ks + ".items WHERE id = 1", + "TRUNCATE " + ks + ".items", + "DROP TABLE " + ks + ".items", + "ALTER TABLE " + ks + ".items ADD extra int", + "CREATE TABLE " + ks + ".other (k int PRIMARY KEY)", + "BEGIN BATCH INSERT INTO " + ks + ".items (id, seq) VALUES (9, 9); APPLY BATCH", + "USE " + ks, + "GRANT SELECT ON ALL KEYSPACES TO nobody", + "SELECT * FROM " + ks + ".items; DELETE FROM " + ks + ".items WHERE id = 1", + "SELECT * FROM " + ks + ".items WHERE id = 1 /* ; */ ; TRUNCATE x", + } { + if m := e.refused("query", args("connection", ro, "sql", sql)); !strings.Contains(m, readOnlyMsg) && !strings.Contains(m, "one statement") { + t.Fatalf("%s: %s", sql, m) + } + } + if m := e.refused("query", args("connection", ro, "sql", "DESCRIBE KEYSPACES")); !strings.Contains(m, "cqlsh") { + t.Fatal(m) + } + if m := e.refused("execute", args("connection", ro, "sql", insert)); !strings.Contains(m, readOnlyMsg) { + t.Fatal(m) + } + // None of it changed anything. + if n := e.value("SELECT count(*) FROM " + ks + ".items"); !is(n, "3") { + t.Fatal(n) + } + + // The write connection refuses transaction control and USE, and sends + // reads to query. + for _, sql := range []string{"BEGIN TRANSACTION", "COMMIT TRANSACTION", "COMMIT", "USE " + ks, insert + "; " + insert} { + e.refused("execute", args("connection", rw, "sql", sql)) + } + if m := e.refused("query", args("connection", rw, "sql", "DELETE FROM "+ks+".items WHERE id = 2")); !strings.Contains(m, "use execute") { + t.Fatal(m) + } + + // Schema tools. + schemas := e.ok("list_schemas", args("connection", ro)) + if names := arr(structuredOf(schemas)["schemas"]); !slices.Contains(names, any(keyspace)) { + t.Fatal(jsonText(names)) + } + tables := e.ok("list_tables", args("connection", ro, "schema", ks)) + objects := arr(structuredOf(tables)["tables"]) + for _, k := range [][2]string{{"items", "table"}, {"addr", "type"}} { + if !slices.ContainsFunc(objects, func(o any) bool { return mapOf(o)["name"] == k[0] && mapOf(o)["kind"] == k[1] }) { + t.Fatalf("%s: %s", k[0], jsonText(objects)) + } + } + d := e.ok("describe_table", args("connection", ro, "table", "items", "schema", ks)) + cols := arr(structuredOf(d)["columns"]) + role := func(name string) string { + i := slices.IndexFunc(cols, func(c any) bool { return mapOf(c)["name"] == name }) + if i < 0 { + return "missing" + } + c := mapOf(cols[i]) + return fmt.Sprintf("%v %v %v", c["keyRole"], c["primaryKey"], c["type"]) + } + for name, want := range map[string]string{ + "id": "partition true int", + "seq": "clustering true int", + "name": "regular false text", + } { + if got := role(name); got != want { + t.Fatalf("%s: %s: %s", name, got, jsonText(cols)) + } + } + if !strings.HasSuffix(role("tags"), " set") { + t.Fatal(jsonText(cols)) + } + if fks, ok := structuredOf(d)["foreignKeys"].([]any); !ok || len(fks) != 0 { + t.Fatal(jsonText(structuredOf(d))) + } + // keyspace.table works as the table argument. + e.ok("describe_table", args("connection", ro, "table", ks+".items")) + if m := e.refused("describe_table", args("connection", ro, "table", "nope", "schema", ks)); !strings.Contains(m, "not found") { + t.Fatal(m) + } + + search := func(pattern string) []any { + return arr(structuredOf(e.ok("search_objects", args("connection", ro, "pattern", pattern)))["matches"]) + } + if matches := search("ITEM"); !slices.ContainsFunc(matches, func(m any) bool { + x := mapOf(m) + return x["table"] == "items" && x["schema"] == keyspace && x["kind"] == "table" && x["column"] == nil + }) { + t.Fatal(jsonText(matches)) + } + if matches := search("tags"); !slices.ContainsFunc(matches, func(m any) bool { + x := mapOf(m) + return x["table"] == "items" && x["column"] == "tags" && x["columnType"] == "set" + }) { + t.Fatal(jsonText(matches)) + } + if matches := search("addr"); !slices.ContainsFunc(matches, func(m any) bool { + return mapOf(m)["table"] == "addr" && mapOf(m)["kind"] == "type" + }) { + t.Fatal(jsonText(matches)) + } + if m := e.refused("explain", args("connection", ro, "sql", "SELECT * FROM "+ks+".items")); !strings.Contains(m, "no EXPLAIN") { + t.Fatal(m) + } + + // Writes through the write connection are visible to reads. + e.write("DELETE FROM " + ks + ".items WHERE id = 2 AND seq = 1") + if n := e.value("SELECT count(*) FROM " + ks + ".items"); !is(n, "2") { + t.Fatal(n) + } + + // Activity log. + log := e.log() + on := func(a AuditEntry, id string) bool { return is(a.ConnectionID, id) } + hasEntry(t, log, "list_connections", func(a AuditEntry) bool { return a.Tool == "list_connections" && a.OK }) + hasEntry(t, log, "search_objects", func(a AuditEntry) bool { return a.Tool == "search_objects" && a.OK && on(a, ro) }) + hasEntry(t, log, "the insert", func(a AuditEntry) bool { + return a.Tool == "execute" && a.OK && on(a, rw) && is(a.Detail, e.n(insert)) + }) + hasEntry(t, log, "a refused change", func(a AuditEntry) bool { + return a.Tool == "query" && !a.OK && on(a, ro) && contains(a.Error, readOnlyMsg) + }) + hasEntry(t, log, "execute on the read connection", func(a AuditEntry) bool { return a.Tool == "execute" && !a.OK && on(a, ro) }) + hasEntry(t, log, "the off connection", func(a AuditEntry) bool { + return !a.OK && a.Tool == "list_schemas" && a.ConnectionID == nil + }) +} diff --git a/internal/mcp/format.go b/internal/mcp/format.go new file mode 100644 index 0000000..e1c60c6 --- /dev/null +++ b/internal/mcp/format.go @@ -0,0 +1,185 @@ +package mcp + +// Text for agents: compact result tables, value and size caps, and error +// messages with the engine's code and a position hint. + +import ( + "fmt" + "strings" + "unicode/utf8" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" +) + +// valueCap is the longest value shown, in characters. +const valueCap = 1_000 + +// textCap is the rough size of one text result, in bytes. +const textCap = 60_000 + +// cutValue cuts a value to valueCap characters, saying how long it was. +func cutValue(v string) string { + total := utf8.RuneCountInString(v) + if total <= valueCap { + return v + } + return fmt.Sprintf("%s… (%d chars)", firstChars(v, valueCap), total) +} + +// firstChars returns the first n characters of s. +func firstChars(s string, n int) string { + i := 0 + for pos := range s { + if i == n { + return s[:pos] + } + i++ + } + return s +} + +var cellEscaper = strings.NewReplacer( + `\`, `\\`, + "|", `\|`, + "\r", `\r`, + "\n", `\n`, + "\t", `\t`, +) + +// cell is a value as one table cell: on one line and without bare `|`. +func cell(v *string) string { + if v == nil { + return "NULL" + } + return cellEscaper.Replace(cutValue(*v)) +} + +func tableLine(cells []string) string { + var b strings.Builder + b.WriteString("|") + for _, c := range cells { + b.WriteString(" ") + b.WriteString(c) + b.WriteString(" |") + } + b.WriteString("\n") + return b.String() +} + +// table is a Markdown table of rows within budget bytes. Returns the text +// and the rows it holds (values already cut). +func table(columns []model.ColumnInfo, rows []model.Row, budget int) (string, [][]*string) { + head := make([]string, len(columns)) + sep := make([]string, len(columns)) + for i, c := range columns { + name := c.Name + head[i] = cell(&name) + sep[i] = "---" + } + var text strings.Builder + text.WriteString(tableLine(head)) + text.WriteString(tableLine(sep)) + kept := [][]*string{} + for _, row := range rows { + cells := make([]string, len(row)) + for i, v := range row { + cells[i] = cell(v) + } + r := tableLine(cells) + if text.Len()+len(r) > budget && len(kept) > 0 { + break + } + text.WriteString(r) + values := make([]*string, len(row)) + for i, v := range row { + if v != nil { + c := cutValue(*v) + values[i] = &c + } + } + kept = append(kept, values) + } + return text.String(), kept +} + +// plural is "1 row" / "3 rows". +func plural(n int, word string) string { + if n == 1 { + return "1 " + word + } + for _, e := range []string{"s", "x", "ch", "sh"} { + if strings.HasSuffix(word, e) { + return fmt.Sprintf("%d %ses", n, word) + } + } + return fmt.Sprintf("%d %ss", n, word) +} + +// lineCol is the line and column (1-based) of a character offset. +func lineCol(sql string, pos int) (int, int) { + line, col := 1, 1 + i := 0 + for _, c := range sql { + if i == pos { + break + } + i++ + if c == '\n' { + line++ + col = 1 + } else { + col++ + } + } + return line, col +} + +// errorText is the error as an agent should read it: engine code and +// message, then detail, hint and where in the SQL it happened. sql is nil +// when the error is not about a statement. +func errorText(err error, sql *string) string { + e := apperr.From(err) + var out string + switch { + case e.Code != "": + out = fmt.Sprintf("Error %s: %s", e.Code, e.Message) + case e.Kind == apperr.Database: + out = "Database error: " + e.Message + case e.Kind == apperr.Connection: + out = "Connection error: " + e.Message + case e.Kind == apperr.Cancelled: + out = "Cancelled: " + e.Message + default: + out = e.Message + } + if e.Detail != "" { + out += "\nDetail: " + e.Detail + } + if e.Hint != "" { + out += "\nHint: " + e.Hint + } + if e.Position != nil && *e.Position >= 0 && sql != nil { + pos := *e.Position + line, col := lineCol(*sql, pos) + near := []rune{} + i := 0 + for _, c := range *sql { + if i >= pos+40 { + break + } + if i >= pos { + if c == '\n' { + c = ' ' + } + near = append(near, c) + } + i++ + } + out += fmt.Sprintf("\nAt line %d, column %d", line, col) + if n := string(near); strings.TrimSpace(n) != "" { + out += ", near: " + strings.TrimRightFunc(n, isUnicodeSpace) + } + } + return out +} diff --git a/internal/mcp/format_test.go b/internal/mcp/format_test.go new file mode 100644 index 0000000..b60bf73 --- /dev/null +++ b/internal/mcp/format_test.go @@ -0,0 +1,165 @@ +package mcp + +import ( + "fmt" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/model" +) + +func col(name string) model.ColumnInfo { + return model.ColumnInfo{Name: name, TypeName: "text", Kind: model.KindText} +} + +func TestValuesAreCutWithTheirLength(t *testing.T) { + if cutValue("abc") != "abc" { + t.Fatal(cutValue("abc")) + } + long := strings.Repeat("é", 1500) + cut := cutValue(long) + if !strings.HasPrefix(cut, strings.Repeat("é", 1000)) || !strings.HasSuffix(cut, "… (1500 chars)") { + t.Fatalf("%q", cut[len(cut)-30:]) + } + if strings.HasPrefix(cut, strings.Repeat("é", 1001)) { + t.Fatal("kept too much") + } +} + +func TestTableIsOneLinePerRow(t *testing.T) { + rows := []model.Row{ + {model.Str("1"), model.Str("a|b\nc")}, + {model.Str("2"), nil}, + } + text, kept := table([]model.ColumnInfo{col("id"), col("name")}, rows, textCap) + if want := "| id | name |\n| --- | --- |\n| 1 | a\\|b\\nc |\n| 2 | NULL |\n"; text != want { + t.Fatalf("%q", text) + } + if len(kept) != 2 { + t.Fatal(kept) + } +} + +func TestTableStopsAtTheBudget(t *testing.T) { + rows := []model.Row{} + for i := range 1000 { + rows = append(rows, model.Row{model.Str(fmt.Sprintf("%0100d", i))}) + } + text, kept := table([]model.ColumnInfo{col("v")}, rows, 5_000) + if len(text) > 5_000 { + t.Fatal(len(text)) + } + if len(kept) >= 1000 || len(kept) == 0 { + t.Fatal(len(kept)) + } + if n := strings.Count(text, "\n"); n != len(kept)+2 { + t.Fatal(n) + } +} + +func TestErrorsShowCodeAndPosition(t *testing.T) { + e := apperr.New(apperr.Database, `syntax error at or near "frm"`) + e.Code = "42601" + pos := 16 + e.Position = &pos + sql := "select *\n from frm users" + if got := errorText(e, &sql); got != "Error 42601: syntax error at or near \"frm\"\nAt line 2, column 8, near: frm users" { + t.Fatalf("%q", got) + } + e = apperr.New(apperr.Cancelled, "The client cancelled the call.") + e.Detail = "d" + e.Hint = "h" + if got := errorText(e, nil); got != "Cancelled: The client cancelled the call.\nDetail: d\nHint: h" { + t.Fatalf("%q", got) + } + if got := errorText(apperr.New(apperr.Connection, "gone"), nil); got != "Connection error: gone" { + t.Fatalf("%q", got) + } + if got := errorText(apperr.New(apperr.Invalid, "bad"), nil); got != "bad" { + t.Fatalf("%q", got) + } +} + +func TestPlural(t *testing.T) { + cases := map[string]string{ + plural(1, "row"): "1 row", + plural(3, "row"): "3 rows", + plural(0, "match"): "0 matches", + plural(2, "schema"): "2 schemas", + plural(2, "more object"): "2 more objects", + } + for got, want := range cases { + if got != want { + t.Errorf("%s != %s", got, want) + } + } +} + +func TestAppendsReadsAndClears(t *testing.T) { + dir := filepath.Join(t.TempDir(), "nested") + entry := func(i uint64) AuditEntry { + rows := i + return AuditEntry{ + At: fmt.Sprintf("2026-10-20T10:00:0%dZ", i), + Client: "test 1.0", + Tool: "query", + ConnectionID: model.Str("c1"), + ConnectionName: model.Str("Local"), + Detail: model.Str(fmt.Sprintf("select %d", i)), + OK: true, + Rows: &rows, + ElapsedMs: 3, + } + } + for i := range uint64(3) { + appendAudit(dir, entry(i)) + } + got, err := ReadRecent(dir, 2) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, []AuditEntry{entry(2), entry(1)}) { + t.Fatalf("%+v", got) + } + // The JSON is the AiActivity type of the app. + data, _ := os.ReadFile(LogPath(dir)) + first := strings.SplitN(string(data), "\n", 2)[0] + want := `{"at":"2026-10-20T10:00:00Z","client":"test 1.0","tool":"query","connectionId":"c1","connectionName":"Local","detail":"select 0","ok":true,"rows":0,"error":null,"elapsedMs":3}` + if first != want { + t.Fatalf("%s", first) + } + if err := ClearActivity(dir); err != nil { + t.Fatal(err) + } + if got, err := ReadRecent(dir, 10); err != nil || len(got) != 0 { + t.Fatalf("%v %v", got, err) + } + if err := ClearActivity(dir); err != nil { + t.Fatal(err) + } +} + +func TestAuditLogIsTrimmed(t *testing.T) { + dir := t.TempDir() + path := LogPath(dir) + line := strings.Repeat("x", 1023) + "\n" + if err := os.WriteFile(path, []byte(strings.Repeat(line, auditMaxBytes/1024+10)), 0o644); err != nil { + t.Fatal(err) + } + appendAudit(dir, AuditEntry{At: "now", Client: "c", Tool: "query", OK: true}) + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if info.Size() > auditMaxBytes/2+10_000 { + t.Fatalf("not trimmed: %d", info.Size()) + } + got, _ := ReadRecent(dir, 5) + if len(got) != 1 || got[0].At != "now" { + t.Fatalf("%+v", got) + } +} diff --git a/internal/mcp/guard.go b/internal/mcp/guard.go new file mode 100644 index 0000000..d4ee0fb --- /dev/null +++ b/internal/mcp/guard.go @@ -0,0 +1,1065 @@ +package mcp + +// Statement checks for agents: one statement per call, read-only +// classification and the Redis command lists. +// +// The lexer only needs to know where strings, quoted names and comments +// start and end in each dialect, so a `;` or a keyword inside them is not +// mistaken for SQL. Whenever the dialect leaves room for doubt (MySQL with +// or without backslash escapes, an unterminated string) the text is refused +// instead of guessed. + +import ( + "bytes" + "errors" + "fmt" + "slices" + "strings" + "unicode" + "unicode/utf8" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers/oracle" + "github.com/LowBloat/LowQuery/internal/drivers/redis" + "github.com/LowBloat/LowQuery/internal/model" +) + +type sqlDialect int + +const ( + dPostgres sqlDialect = iota + dOracle + dMysql + dSQLServer + dSqlite + dCassandra +) + +func dialectOf(engine model.Engine) sqlDialect { + switch engine { + case model.Postgres: + return dPostgres + case model.Oracle: + return dOracle + case model.MySQL, model.MariaDB: + return dMysql + case model.SQLServer: + return dSQLServer + case model.Cassandra: + return dCassandra + } + // SQLite; Redis never reaches the SQL lexer. + return dSqlite +} + +type tokKind int + +const ( + // tWord is a keyword or unquoted name, uppercased. + tWord tokKind = iota + // tQuoted is a string literal or quoted name. + tQuoted + tNumber + tPunct + tSemi + // tSlash is a line holding only `/` (SQL*Plus), Oracle only. + tSlash +) + +type tok struct { + kind tokKind + word string + punct byte +} + +func punct(c byte) tok { return tok{kind: tPunct, punct: c} } + +type token struct { + tok tok + end int +} + +// checked is one statement, ready to send. +type checked struct { + // The statement without the trailing `;` or `/` line (PL/SQL and + // routine bodies keep their final `;`). + sql string + // Tokens of the statement, once per way the dialect may read it. + views [][]tok +} + +func (c *checked) firstWord() string { + if len(c.views) == 0 { + return "" + } + return firstWord(c.views[0]) +} + +// firstWord is the first word, skipping opening parentheses; "" when the +// statement starts with something else. +func firstWord(toks []tok) string { + for _, t := range toks { + if t == punct('(') { + continue + } + if t.kind == tWord { + return t.word + } + return "" + } + return "" +} + +func words(toks []tok) []string { + out := []string{} + for _, t := range toks { + if t.kind == tWord { + out = append(out, t.word) + } + } + return out +} + +// --------------------------------------------------------------------------- +// Character classes (ASCII rules, as Rust's u8 methods) + +func isASCIISpace(c byte) bool { + return c == ' ' || c == '\t' || c == '\n' || c == '\x0c' || c == '\r' +} + +func isASCIIAlpha(c byte) bool { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') } +func isASCIIDigit(c byte) bool { return c >= '0' && c <= '9' } +func isASCIIAlnum(c byte) bool { return isASCIIAlpha(c) || isASCIIDigit(c) } +func isASCIIControl(c byte) bool { + return c < 0x20 || c == 0x7f +} + +func isUnicodeSpace(r rune) bool { return unicode.IsSpace(r) } + +// upperASCII uppercases ASCII letters only. +func upperASCII(s string) string { + b := []byte(s) + for i, c := range b { + if c >= 'a' && c <= 'z' { + b[i] = c - 'a' + 'A' + } + } + return string(b) +} + +func lowerASCII(s string) string { + b := []byte(s) + for i, c := range b { + if c >= 'A' && c <= 'Z' { + b[i] = c - 'A' + 'a' + } + } + return string(b) +} + +func equalFoldASCII(a, b string) bool { + return len(a) == len(b) && lowerASCII(a) == lowerASCII(b) +} + +// --------------------------------------------------------------------------- +// Lexer + +func isWordStart(c byte) bool { + return isASCIIAlpha(c) || c == '_' || c >= 0x80 +} + +func isWordChar(c byte, d sqlDialect) bool { + return isASCIIAlnum(c) || + c == '_' || + c >= 0x80 || + (c == '$' && d != dSqlite && d != dCassandra) || + (c == '#' && (d == dOracle || d == dSQLServer)) +} + +const unterminated = "The text has an unterminated string, quoted name or comment." + +var errUnterminated = errors.New(unterminated) + +// skipQuoted skips a quoted run opened by b[i] == q. The quote doubled +// stands for itself; with backslash, `\` escapes the next character. +func skipQuoted(b []byte, i int, q byte, backslash bool) (int, error) { + j := i + 1 + for j < len(b) { + switch { + case backslash && b[j] == '\\': + j += 2 + case b[j] == q: + if j+1 < len(b) && b[j+1] == q { + j += 2 + } else { + return j + 1, nil + } + default: + j++ + } + } + return 0, errUnterminated +} + +// skipQQuote skips Oracle q'[...]': i is at the opening `'`. +func skipQQuote(b []byte, i int) (int, error) { + if i+1 >= len(b) { + return 0, errUnterminated + } + open := b[i+1] + var close byte + switch { + case open == '[': + close = ']' + case open == '{': + close = '}' + case open == '<': + close = '>' + case open == '(': + close = ')' + case isASCIISpace(open): + return 0, errors.New("Invalid q'' quote delimiter.") + default: + close = open + } + for j := i + 2; j+1 < len(b); j++ { + if b[j] == close && b[j+1] == '\'' { + return j + 2, nil + } + } + return 0, errUnterminated +} + +// skipDollarQuote skips PostgreSQL $tag$...$tag$: ok is false when the `$` +// does not open one. +func skipDollarQuote(b []byte, i int) (end int, ok bool, err error) { + j := i + 1 + if j >= len(b) || b[j] != '$' { + if !(j < len(b) && isWordStart(b[j])) { + return 0, false, nil + } + for j < len(b) && (isASCIIAlnum(b[j]) || b[j] == '_' || b[j] >= 0x80) { + j++ + } + if j >= len(b) || b[j] != '$' { + return 0, false, nil + } + } + tag := b[i : j+1] + body := j + 1 + p := bytes.Index(b[body:], tag) + if p < 0 { + return 0, false, errUnterminated + } + return body + p + len(tag), true, nil +} + +// skipDoubleDollar skips CQL $$...$$: i is at the first `$`, the next one is +// known to be `$`. +func skipDoubleDollar(b []byte, i int) (int, error) { + p := bytes.Index(b[i+2:], []byte("$$")) + if p < 0 { + return 0, errUnterminated + } + return i + 2 + p + 2, nil +} + +func skipBlockComment(b []byte, i int, nested bool) (int, error) { + depth := 1 + j := i + 2 + for j+1 < len(b) { + switch { + case b[j] == '*' && b[j+1] == '/': + depth-- + j += 2 + if depth == 0 { + return j, nil + } + case nested && b[j] == '/' && b[j+1] == '*': + depth++ + j += 2 + default: + j++ + } + } + return 0, errUnterminated +} + +// unicodeSpace is the length of the non-ASCII whitespace character at i, or +// 0 when there is none. +func unicodeSpace(sql string, i int) int { + if sql[i] < 0x80 { + return 0 + } + r, n := utf8.DecodeRuneInString(sql[i:]) + if r != utf8.RuneError && unicode.IsSpace(r) { + return n + } + return 0 +} + +func lineEnd(b []byte, i int) int { + if p := bytes.IndexByte(b[i:], '\n'); p >= 0 { + return i + p + } + return len(b) +} + +func allASCIISpace(b []byte) bool { + for _, c := range b { + if !isASCIISpace(c) { + return false + } + } + return true +} + +// slashAlone reports a `/` alone on its line (spaces aside). +func slashAlone(b []byte, i int) bool { + start := bytes.LastIndexByte(b[:i], '\n') + 1 + end := lineEnd(b, i) + return allASCIISpace(b[start:i]) && allASCIISpace(b[i+1:end]) +} + +func lex(sql string, d sqlDialect, backslash bool) ([]token, error) { + b := []byte(sql) + out := []token{} + push := func(t tok, end int) { out = append(out, token{t, end}) } + i := 0 + for i < len(b) { + c := b[i] + var next byte + hasNext := i+1 < len(b) + if hasNext { + next = b[i+1] + } + switch { + case isASCIISpace(c): + i++ + case unicodeSpace(sql, i) > 0: + // T-SQL reads U+00A0 and friends as spaces. + i += unicodeSpace(sql, i) + case c == '-' && hasNext && next == '-': + // MySQL needs a space (or control character) after `--`: `1--1` + // is arithmetic there. + comment := d != dMysql || i+2 >= len(b) || isASCIISpace(b[i+2]) || isASCIIControl(b[i+2]) + if comment { + i = lineEnd(b, i) + } else { + push(punct(c), i+1) + i++ + } + case (c == '#' && d == dMysql) || (c == '/' && hasNext && next == '/' && d == dCassandra): + i = lineEnd(b, i) + case c == '/' && hasNext && next == '*': + if d == dMysql && ((i+2 < len(b) && b[i+2] == '!') || + (i+3 < len(b) && b[i+2] == 'M' && b[i+3] == '!')) { + return nil, errors.New("MySQL executable comments (/*! ... */) are not accepted; write the SQL plainly.") + } + var err error + if i, err = skipBlockComment(b, i, d == dPostgres || d == dSQLServer); err != nil { + return nil, err + } + case c == '/' && d == dOracle && slashAlone(b, i): + push(tok{kind: tSlash}, i+1) + i++ + case c == '\'': + var err error + if i, err = skipQuoted(b, i, '\'', backslash); err != nil { + return nil, err + } + push(tok{kind: tQuoted}, i) + case c == '"': + var err error + if i, err = skipQuoted(b, i, '"', backslash && d == dMysql); err != nil { + return nil, err + } + push(tok{kind: tQuoted}, i) + case c == '`' && (d == dMysql || d == dSqlite): + var err error + if i, err = skipQuoted(b, i, '`', false); err != nil { + return nil, err + } + push(tok{kind: tQuoted}, i) + case c == '[' && (d == dSQLServer || d == dSqlite): + // `]]` stands for `]` inside the name. + j := i + 1 + bracket: + for { + switch { + case j >= len(b): + return nil, errUnterminated + case b[j] == ']' && j+1 < len(b) && b[j+1] == ']': + j += 2 + case b[j] == ']': + break bracket + default: + j++ + } + } + i = j + 1 + push(tok{kind: tQuoted}, i) + case c == '$' && d == dCassandra: + if hasNext && next == '$' { + var err error + if i, err = skipDoubleDollar(b, i); err != nil { + return nil, err + } + push(tok{kind: tQuoted}, i) + } else { + i++ + push(punct(c), i) + } + case c == '$' && d == dPostgres: + end, ok, err := skipDollarQuote(b, i) + if err != nil { + return nil, err + } + if ok { + i = end + push(tok{kind: tQuoted}, i) + } else { + i++ + push(punct(c), i) + } + case c == ';': + i++ + push(tok{kind: tSemi}, i) + case isASCIIDigit(c): + // Letters right after a number start a new word, as PostgreSQL + // before 15 reads `1into`. + for i < len(b) && (isASCIIDigit(b[i]) || b[i] == '.') { + i++ + } + push(tok{kind: tNumber}, i) + case isWordStart(c): + start := i + for i < len(b) { + if b[i] >= 0x80 { + if unicodeSpace(sql, i) > 0 { + break + } + _, n := utf8.DecodeRuneInString(sql[i:]) + i += n + } else if isWordChar(b[i], d) { + i++ + } else { + break + } + } + word := sql[start:i] + if i < len(b) && b[i] == '\'' { + upper := upperASCII(word) + if d == dPostgres && upper == "E" { + var err error + if i, err = skipQuoted(b, i, '\'', true); err != nil { + return nil, err + } + push(tok{kind: tQuoted}, i) + continue + } + if d == dOracle && (upper == "Q" || upper == "NQ") { + var err error + if i, err = skipQQuote(b, i); err != nil { + return nil, err + } + push(tok{kind: tQuoted}, i) + continue + } + } + push(tok{kind: tWord, word: upperASCII(word)}, i) + default: + i++ + push(punct(c), i) + } + } + return out, nil +} + +// isRoutine reports CREATE PROCEDURE, FUNCTION, TRIGGER... whose body may +// hold `;`. +func isRoutine(toks []token) bool { + head := []string{} + for n, t := range toks { + if t.tok == punct('(') || n >= 16 { + break + } + if t.tok.kind == tWord { + head = append(head, t.tok.word) + } + } + if len(head) == 0 || (head[0] != "CREATE" && head[0] != "ALTER") { + return false + } + for _, w := range head[1:] { + switch w { + case "PROCEDURE", "PROC", "FUNCTION", "TRIGGER", "EVENT", "PACKAGE": + return true + } + } + return false +} + +// isCQLBatchOpen reports a CQL BEGIN [UNLOGGED|COUNTER] BATCH whose APPLY +// BATCH has not come yet: the `;` between its statements do not end it. +func isCQLBatchOpen(group []token) bool { + w := []string{} + for _, t := range group { + if t.tok.kind == tWord { + w = append(w, t.tok.word) + } + } + at := func(i int) string { + if i < len(w) { + return w[i] + } + return "" + } + opens := at(0) == "BEGIN" && (at(1) == "BATCH" || + ((at(1) == "UNLOGGED" || at(1) == "COUNTER") && at(2) == "BATCH")) + if !opens { + return false + } + prev := "" + for _, word := range w { + if prev == "APPLY" && word == "BATCH" { + return false + } + prev = word + } + return true +} + +// splitOne splits toks and keeps the only statement, with the byte offset +// where it ends. +func splitOne(toks []token, sql string, d sqlDialect) ([]tok, int, error) { + // CQL function bodies are $$...$$ strings, so only batches span `;`. + var block bool + switch d { + case dOracle: + block = oracle.IsPLSQL(sql) + case dCassandra: + block = false + default: + block = isRoutine(toks) + } + groups := [][]token{{}} + for _, t := range toks { + last := groups[len(groups)-1] + inBatch := d == dCassandra && t.tok.kind == tSemi && isCQLBatchOpen(last) + separator := t.tok.kind == tSlash || (t.tok.kind == tSemi && !block && !inBatch) + if separator { + groups = append(groups, []token{}) + } else { + groups[len(groups)-1] = append(last, t) + } + } + kept := [][]token{} + for _, g := range groups { + if len(g) > 0 { + kept = append(kept, g) + } + } + switch len(kept) { + case 0: + return nil, 0, errors.New("Nothing to run.") + case 1: + g := kept[0] + out := make([]tok, len(g)) + for i, t := range g { + out[i] = t.tok + } + return out, g[len(g)-1].end, nil + default: + return nil, 0, fmt.Errorf("Send one statement per call; this text has %d statements.", len(kept)) + } +} + +// oneStatement checks that sql is exactly one statement for engine. +func oneStatement(sql string, engine model.Engine) (*checked, error) { + d := dialectOf(engine) + // MySQL reads \' as an escape unless NO_BACKSLASH_ESCAPES is set: the + // text must be one statement both ways. + modes := []bool{false} + if d == dMysql { + modes = []bool{true, false} + } + views := [][]tok{} + cut := 0 + for _, backslash := range modes { + lexed, err := lex(sql, d, backslash) + if err != nil { + return nil, err + } + toks, end, err := splitOne(lexed, sql, d) + if err != nil { + return nil, err + } + cut = max(cut, end) + views = append(views, toks) + } + return &checked{sql: strings.TrimSpace(sql[:cut]), views: views}, nil +} + +// --------------------------------------------------------------------------- +// Read-only classifier + +// writeWords change data or run other statements and are refused anywhere +// in a read statement (data-changing CTEs, T-SQL batches without `;`, +// functions with side effects). +var writeWords = []string{ + "INSERT", + "UPDATE", + "DELETE", + "MERGE", + "UPSERT", + "TRUNCATE", + "DROP", + "ALTER", + "CREATE", + "GRANT", + "REVOKE", + "INTO", + // PostgreSQL functions that act outside the transaction or change state. + "SET_CONFIG", + "NEXTVAL", + "SETVAL", + "PG_TERMINATE_BACKEND", + "PG_CANCEL_BACKEND", + "PG_RELOAD_CONF", + "PG_ROTATE_LOGFILE", + "PG_SWITCH_WAL", + "PG_CREATE_RESTORE_POINT", + "PG_PROMOTE", + "PG_LOGICAL_EMIT_MESSAGE", + "PG_FILE_WRITE", + "PG_FILE_RENAME", + "PG_FILE_UNLINK", + "LO_IMPORT", + "LO_EXPORT", + "LO_UNLINK", + "LO_CREATE", + "LO_CREAT", + "LO_FROM_BYTEA", + "LO_PUT", + "DBLINK", + "DBLINK_EXEC", + "DBLINK_CONNECT", + // Session-level locks outlive the rolled-back transaction. + "PG_ADVISORY_LOCK", + "PG_ADVISORY_LOCK_SHARED", + "PG_TRY_ADVISORY_LOCK", + "PG_TRY_ADVISORY_LOCK_SHARED", + "GET_LOCK", + // SQLite + "LOAD_EXTENSION", +} + +// tsqlWords: T-SQL runs every statement of a batch, `;` or not. +var tsqlWords = []string{ + "EXEC", + "EXECUTE", + "BEGIN", + "COMMIT", + "ROLLBACK", + "SAVE", + "DECLARE", + "SET", + "USE", + "DBCC", + "KILL", + "SHUTDOWN", + "BACKUP", + "RESTORE", + "BULK", + "DENY", + "WAITFOR", + "RECONFIGURE", + "CHECKPOINT", + "REVERT", + "SETUSER", + "OPENQUERY", + "OPENROWSET", + "OPENDATASOURCE", +} + +// readPragmas only report. +var readPragmas = []string{ + "APPLICATION_ID", + "AUTO_VACUUM", + "AUTOMATIC_INDEX", + "BUSY_TIMEOUT", + "CACHE_SIZE", + "CACHE_SPILL", + "CELL_SIZE_CHECK", + "COLLATION_LIST", + "COMPILE_OPTIONS", + "DATA_VERSION", + "DATABASE_LIST", + "DEFER_FOREIGN_KEYS", + "ENCODING", + "FOREIGN_KEYS", + "FREELIST_COUNT", + "FUNCTION_LIST", + "JOURNAL_MODE", + "JOURNAL_SIZE_LIMIT", + "LEGACY_ALTER_TABLE", + "LOCKING_MODE", + "MAX_PAGE_COUNT", + "MMAP_SIZE", + "MODULE_LIST", + "PAGE_COUNT", + "PAGE_SIZE", + "PRAGMA_LIST", + "QUERY_ONLY", + "RECURSIVE_TRIGGERS", + "SCHEMA_VERSION", + "SECURE_DELETE", + "SYNCHRONOUS", + "TEMP_STORE", + "TRUSTED_SCHEMA", + "USER_VERSION", + "WAL_AUTOCHECKPOINT", +} + +// argPragmas take a table or index name and only report. +var argPragmas = []string{ + "TABLE_INFO", + "TABLE_XINFO", + "TABLE_LIST", + "INDEX_LIST", + "INDEX_INFO", + "INDEX_XINFO", + "FOREIGN_KEY_LIST", + "FOREIGN_KEY_CHECK", + "INTEGRITY_CHECK", + "QUICK_CHECK", +} + +func checkPragma(toks []tok) error { + if slices.Contains(toks, punct('=')) { + return errors.New("PRAGMA with = changes a setting.") + } + // PRAGMA [schema.]name [(argument)] + rest := toks[1:] + if len(rest) > 1 && rest[1] == punct('.') { + rest = rest[2:] + } + if len(rest) == 0 || rest[0].kind != tWord { + return errors.New("Name the PRAGMA to read.") + } + name := rest[0].word + hasArg := len(rest) > 1 + if slices.Contains(argPragmas, name) || (!hasArg && slices.Contains(readPragmas, name)) { + return nil + } + return fmt.Errorf("PRAGMA %s is not one of the PRAGMAs that only read.", name) +} + +// checkCQLView: CQL reads are SELECT and LIST only. LIST (ROLES, USERS, +// PERMISSIONS) only reports, so its permission names (CREATE, ALTER, +// DROP...) are not scanned. +func checkCQLView(first string, toks []tok) error { + switch first { + case "LIST": + return nil + case "SELECT": + for _, w := range words(toks) { + if slices.Contains(writeWords, w) { + return fmt.Errorf("%s is not allowed in a read statement.", w) + } + } + return nil + case "DESCRIBE", "DESC": + return errors.New("DESCRIBE is a cqlsh command, not CQL; use the schema, table and search tools instead.") + case "WITH", "EXPLAIN": + return fmt.Errorf("%s does not exist in CQL; send a SELECT.", first) + } + return fmt.Errorf("%s is not a read statement; CQL reads are SELECT and LIST.", first) +} + +func checkView(toks []tok, engine model.Engine) error { + first := firstWord(toks) + if first == "" { + return errors.New("The statement must start with a keyword such as SELECT.") + } + if engine == model.Cassandra { + return checkCQLView(first, toks) + } + allowed := false + switch first { + case "SELECT", "WITH", "SHOW", "DESCRIBE", "DESC", "EXPLAIN", "VALUES", "TABLE": + allowed = true + case "PRAGMA": + allowed = engine == model.SQLite + } + if !allowed { + return fmt.Errorf("%s is not a read statement.", first) + } + ws := words(toks) + if (first == "EXPLAIN" || first == "DESCRIBE" || first == "DESC") && + (engine == model.Postgres || engine == model.MySQL || engine == model.MariaDB) && + (slices.Contains(ws, "ANALYZE") || slices.Contains(ws, "ANALYSE")) { + return errors.New("EXPLAIN ANALYZE runs the statement; use the explain tool for the plan.") + } + if first == "PRAGMA" { + return checkPragma(toks) + } + prev, prev2 := "", "" + for _, w := range ws { + // NEXT VALUE FOR (SQL Server, MariaDB) advances a sequence, which no + // rollback undoes. + if w == "FOR" && prev == "VALUE" && prev2 == "NEXT" { + return errors.New("NEXT VALUE FOR is not allowed in a read statement.") + } + // SELECT ... FOR UPDATE / FOR NO KEY UPDATE only lock, and the lock + // ends with the rolled-back transaction. + locking := w == "UPDATE" && (prev == "FOR" || prev == "KEY") + refused := slices.Contains(writeWords, w) || + (engine == model.SQLServer && slices.Contains(tsqlWords, w)) + if refused && !locking { + return fmt.Errorf("%s is not allowed in a read statement.", w) + } + prev2 = prev + prev = w + } + return nil +} + +// checkRead accepts SELECT, WITH, SHOW, DESCRIBE, EXPLAIN (without +// ANALYZE), VALUES, TABLE and reading PRAGMAs (CQL: SELECT and LIST); the +// error says why the text is not a read. +func checkRead(stmt *checked, engine model.Engine) error { + for _, v := range stmt.views { + if err := checkView(v, engine); err != nil { + return err + } + } + return nil +} + +// checkWrite checks execute statements: no transaction control, since each +// call commits on its own. +func checkWrite(stmt *checked, engine model.Engine) error { + const message = "Transaction control is not available to agents: each execute call commits on its own." + for _, toks := range stmt.views { + ws := words(toks) + first, second := "", "" + if len(ws) > 0 { + first = ws[0] + } + if len(ws) > 1 { + second = ws[1] + } + control := false + switch { + // BEGIN [UNLOGGED|COUNTER] BATCH is one statement, not a + // transaction; Accord (Cassandra 5.1+) uses BEGIN TRANSACTION. + case first == "BEGIN" && engine == model.Cassandra: + control = second == "TRANSACTION" || second == "TRAN" + // CQL has no savepoints; USE would change the session's keyspace for + // later calls. + case first == "USE" && engine == model.Cassandra: + return errors.New("USE changes the session keyspace; qualify names as keyspace.table instead.") + case first == "BEGIN": + switch engine { + case model.Oracle: + control = false + case model.SQLServer: + control = second == "TRAN" || second == "TRANSACTION" || second == "DISTRIBUTED" + default: + control = true + } + case first == "START": + control = second == "TRANSACTION" + case first == "COMMIT" || first == "ROLLBACK" || first == "SAVEPOINT" || + first == "RELEASE" || first == "ABORT" || first == "XA": + control = true + case first == "END": + control = engine == model.Postgres || engine == model.SQLite + case first == "SAVE": + control = engine == model.SQLServer + case first == "LOCK": + control = engine == model.MySQL || engine == model.MariaDB + case first == "SET": + control = slices.Contains(ws, "AUTOCOMMIT") || slices.Contains(ws, "IMPLICIT_TRANSACTIONS") + } + if control { + return errors.New(message) + } + } + return nil +} + +// checkExplain: explain takes the statement itself; the engine's EXPLAIN is +// added. +func checkExplain(stmt *checked) error { + switch stmt.firstWord() { + case "EXPLAIN", "DESCRIBE", "DESC", "ANALYZE", "ANALYSE": + return errors.New("Pass the statement itself; explain adds EXPLAIN and never runs it.") + } + return nil +} + +// --------------------------------------------------------------------------- +// Redis + +// redisBlocked are commands agents never send: they change the session for +// later calls or take over the connection. +var redisBlocked = []string{ + "MULTI", + "EXEC", + "DISCARD", + "WATCH", + "UNWATCH", + "SELECT", + "SWAPDB", + "AUTH", + "HELLO", + "QUIT", + "RESET", + "CLIENT", + "MONITOR", + "SUBSCRIBE", + "PSUBSCRIBE", + "SSUBSCRIBE", + "UNSUBSCRIBE", + "PUNSUBSCRIBE", + "SUNSUBSCRIBE", + "SYNC", + "PSYNC", + "SHUTDOWN", + "DEBUG", + "REPLICAOF", + "SLAVEOF", + "FAILOVER", +} + +// redisRead are commands that only read. +var redisRead = []string{ + "GET", + "MGET", + "STRLEN", + "GETRANGE", + "SUBSTR", + "LCS", + "GETBIT", + "BITCOUNT", + "BITPOS", + "BITFIELD_RO", + "EXISTS", + "TYPE", + "TTL", + "PTTL", + "EXPIRETIME", + "PEXPIRETIME", + "RANDOMKEY", + "SCAN", + "HSCAN", + "SSCAN", + "ZSCAN", + "HGET", + "HMGET", + "HGETALL", + "HKEYS", + "HVALS", + "HLEN", + "HEXISTS", + "HSTRLEN", + "HRANDFIELD", + "LRANGE", + "LLEN", + "LINDEX", + "LPOS", + "SMEMBERS", + "SISMEMBER", + "SMISMEMBER", + "SCARD", + "SRANDMEMBER", + "SINTER", + "SINTERCARD", + "SUNION", + "SDIFF", + "ZRANGE", + "ZRANGEBYSCORE", + "ZRANGEBYLEX", + "ZREVRANGE", + "ZREVRANGEBYSCORE", + "ZREVRANGEBYLEX", + "ZSCORE", + "ZMSCORE", + "ZCARD", + "ZCOUNT", + "ZLEXCOUNT", + "ZRANK", + "ZREVRANK", + "ZRANDMEMBER", + "ZINTER", + "ZINTERCARD", + "ZUNION", + "ZDIFF", + "XRANGE", + "XREVRANGE", + "XLEN", + "XPENDING", + "PFCOUNT", + "GEOPOS", + "GEODIST", + "GEOHASH", + "GEOSEARCH", + "GEORADIUS_RO", + "GEORADIUSBYMEMBER_RO", + "SORT_RO", + "INFO", + "DBSIZE", + "LASTSAVE", + "PING", + "ECHO", + "TIME", +} + +// redisReadSub are read commands with a subcommand. +var redisReadSub = map[string][]string{ + "MEMORY": {"USAGE", "STATS", "DOCTOR"}, + "OBJECT": {"ENCODING", "FREQ", "IDLETIME", "REFCOUNT"}, + "XINFO": {"STREAM", "GROUPS", "CONSUMERS"}, +} + +// checkRedis checks one redis-cli command; write lifts the read allowlist. +func checkRedis(text string, write bool) error { + text = strings.TrimSpace(text) + if strings.ContainsAny(text, "\n\r") { + return errors.New(`Send one Redis command per call, on one line (write \n inside double quotes).`) + } + args, err := redis.SplitArgs(text) + if err != nil { + return errors.New(apperr.From(err).Message) + } + if len(args) == 0 { + return errors.New("Enter a Redis command.") + } + name := upperASCII(strings.ToValidUTF8(string(args[0]), "�")) + if slices.Contains(redisBlocked, name) { + return fmt.Errorf("%s is not available to agents.", name) + } + if write { + return nil + } + if name == "KEYS" { + return errors.New("KEYS blocks the server while it walks every key; use SCAN 0 MATCH pattern COUNT 100.") + } + if slices.Contains(redisRead, name) { + return nil + } + if subs, ok := redisReadSub[name]; ok { + sub := "" + if len(args) > 1 { + sub = upperASCII(strings.ToValidUTF8(string(args[1]), "�")) + } + if slices.Contains(subs, sub) { + return nil + } + return fmt.Errorf("%s %s is not a read command.", name, sub) + } + return fmt.Errorf("%s is not a read command.", name) +} diff --git a/internal/mcp/guard_test.go b/internal/mcp/guard_test.go new file mode 100644 index 0000000..87fe28e --- /dev/null +++ b/internal/mcp/guard_test.go @@ -0,0 +1,441 @@ +package mcp + +import ( + "strings" + "testing" + + "github.com/LowBloat/LowQuery/internal/model" +) + +func one(sql string, engine model.Engine) (string, error) { + c, err := oneStatement(sql, engine) + if err != nil { + return "", err + } + return c.sql, nil +} + +func read(sql string, engine model.Engine) error { + c, err := oneStatement(sql, engine) + if err != nil { + return err + } + return checkRead(c, engine) +} + +func mustOne(t *testing.T, sql string, engine model.Engine) *checked { + t.Helper() + c, err := oneStatement(sql, engine) + if err != nil { + t.Fatalf("%s: %v", sql, err) + } + return c +} + +func TestSingleStatementWithTrailingTerminators(t *testing.T) { + cases := []struct { + sql string + engine model.Engine + want string + }{ + {"select 1;", model.Postgres, "select 1"}, + {"select 1 ; ; -- done", model.Postgres, "select 1"}, + {"select 1\n/\n", model.Oracle, "select 1"}, + {"select 1;\n/", model.Oracle, "select 1"}, + } + for _, c := range cases { + if got, err := one(c.sql, c.engine); err != nil || got != c.want { + t.Errorf("%q: %q %v", c.sql, got, err) + } + } + if _, err := one(" -- nothing\n ; ", model.SQLite); err == nil { + t.Error("empty text accepted") + } +} + +func TestMultipleStatementsAreRefused(t *testing.T) { + for _, engine := range []model.Engine{model.Postgres, model.Oracle, model.MySQL, model.SQLServer, model.SQLite} { + for _, sql := range []string{"select 1; select 2", "select 1;delete from t"} { + if _, err := one(sql, engine); err == nil { + t.Errorf("%s: %s", engine, sql) + } + } + } + if _, err := one("select 1\n/\nselect 2", model.Oracle); err == nil { + t.Error("oracle slash") + } + _, err := one("select 1; select 2", model.Postgres) + if err == nil || err.Error() != "Send one statement per call; this text has 2 statements." { + t.Errorf("message: %v", err) + } +} + +func TestSemicolonsInsideQuotesAndComments(t *testing.T) { + cases := []struct { + engine model.Engine + sql string + }{ + {model.Postgres, "select 'a;b', \"c;d\" -- ;\n from t /* ; /* ; */ ; */"}, + {model.Postgres, "select $$a;b$$, $fn$ x; $$ ; $fn$"}, + {model.Postgres, `select E'it\'s; here'`}, + {model.Postgres, "select 'it''s; here'"}, + {model.Postgres, "select $1::int"}, + {model.Oracle, "select q'[a ; it's]' from dual"}, + {model.Oracle, "select nq'{;}' from dual"}, + {model.MySQL, "select `a;b`, 'x;y' # ;\n from t"}, + {model.MySQL, "select 'it''s;'"}, + {model.SQLServer, "select [a;]]b] from t"}, + {model.SQLServer, "select 1 /* /* ; */ ; */"}, + {model.SQLite, "select [a;b], `c;d`, \"e;f\" from t"}, + } + for _, c := range cases { + if _, err := one(c.sql, c.engine); err != nil { + t.Errorf("%s: %s: %v", c.engine, c.sql, err) + } + } +} + +func TestDialectSpecificTraps(t *testing.T) { + refused := []struct { + sql string + engine model.Engine + }{ + // Non-nested comments end at the first */ in MySQL, Oracle and SQLite. + {"select 1 /* /* */ ; delete from t */", model.MySQL}, + {"select 1 /* /* */ ; delete from t */", model.SQLite}, + // MySQL `--` needs a space. + {"select 1--1; delete from t", model.MySQL}, + // Backslash escapes: one statement only if it is one either way. + {`select 'a\'; delete from t; -- '`, model.MySQL}, + {"select 1 /*! ; delete from t */", model.MySQL}, + // Unterminated text is refused, not guessed. + {"select 'abc", model.Postgres}, + {"select $x$ abc", model.Postgres}, + {"select 1 /* open", model.SQLServer}, + } + for _, c := range refused { + if _, err := one(c.sql, c.engine); err == nil { + t.Errorf("%s: %s", c.engine, c.sql) + } + } + _, err := one("select 'abc", model.Postgres) + if err == nil || err.Error() != unterminated { + t.Errorf("unterminated: %v", err) + } +} + +func TestRoutineBodiesAreOneStatement(t *testing.T) { + plsql := "begin\n update t set a = 1;\n commit;\nend;\n/" + if got, err := one(plsql, model.Oracle); err != nil || got != "begin\n update t set a = 1;\n commit;\nend;" { + t.Errorf("plsql: %q %v", got, err) + } + if _, err := one("begin null; end;\n/\nselect 1 from dual", model.Oracle); err == nil { + t.Error("plsql then select") + } + if _, err := one("CREATE PROCEDURE p() BEGIN SELECT 1; SELECT 2; END", model.MySQL); err != nil { + t.Error(err) + } + if _, err := one("CREATE TRIGGER tr AFTER INSERT ON t BEGIN UPDATE u SET n = n + 1; END;", model.SQLite); err != nil { + t.Error(err) + } +} + +func TestClassifierAcceptsReads(t *testing.T) { + cases := []struct { + sql string + engine model.Engine + }{ + {"SELECT * FROM t", model.Postgres}, + {"(select 1) union (select 2)", model.Postgres}, + {"with x as (select 1) select * from x", model.SQLServer}, + {"select * from t for update", model.Oracle}, + {"select * from t for no key update", model.Postgres}, + {"show tables", model.MySQL}, + {"explain select 1", model.MySQL}, + {"values (1), (2)", model.SQLite}, + {"select 'insert into t'", model.Postgres}, + {"select last_update, \"delete\" from t", model.Postgres}, + {"pragma table_info('t')", model.SQLite}, + {"PRAGMA main.user_version", model.SQLite}, + } + for _, c := range cases { + if err := read(c.sql, c.engine); err != nil { + t.Errorf("%s: %s: %v", c.engine, c.sql, err) + } + } +} + +func TestClassifierRefusesWrites(t *testing.T) { + cases := []struct { + engine model.Engine + sql string + }{ + {model.Postgres, "delete from t"}, + {model.Postgres, "with d as (delete from t returning *) select * from d"}, + {model.Postgres, "select * into t2 from t"}, + {model.Postgres, "select 1into t2"}, + {model.Postgres, "explain analyze delete from t"}, + {model.Postgres, "explain (analyze, costs off) select 1"}, + {model.Postgres, "select set_config('default_transaction_read_only', 'off', false)"}, + {model.Postgres, "select nextval('s')"}, + {model.Postgres, "copy t to stdout"}, + {model.Postgres, "call p()"}, + {model.MySQL, "select * from t into outfile '/tmp/x'"}, + {model.MySQL, "explain analyze select 1"}, + {model.MySQL, "replace into t values (1)"}, + {model.SQLServer, "select 1 delete from t"}, + {model.SQLServer, "select 1 exec sp_who"}, + {model.SQLServer, "with c as (select * from t) update c set a = 1"}, + {model.SQLServer, "select * from openquery(srv, 'delete x')"}, + {model.SQLServer, "select 1 delete from t"}, + {model.Oracle, "begin null; end;"}, + {model.Oracle, "merge into t using u on (1 = 1) when matched then update set a = 1"}, + {model.SQLite, "pragma user_version = 5"}, + {model.SQLite, "pragma query_only(0)"}, + {model.SQLite, "pragma writable_schema"}, + {model.SQLite, "attach 'x.db' as x"}, + {model.SQLite, "with x as (select 1) insert into t select * from x"}, + } + for _, c := range cases { + if err := read(c.sql, c.engine); err == nil { + t.Errorf("%s: %s", c.engine, c.sql) + } + } + if err := read("delete from t", model.Postgres); err == nil || err.Error() != "DELETE is not a read statement." { + t.Errorf("message: %v", err) + } +} + +func TestWriteCheckRefusesTransactionControl(t *testing.T) { + write := func(sql string, engine model.Engine) error { + return checkWrite(mustOne(t, sql, engine), engine) + } + if err := write("update t set a = 1", model.Postgres); err != nil { + t.Error(err) + } + if err := write("begin update t set a = 1; end;", model.Oracle); err != nil { + t.Error(err) + } + for _, c := range []struct { + sql string + engine model.Engine + }{ + {"begin", model.Postgres}, + {"start transaction", model.MySQL}, + {"commit", model.Oracle}, + {"begin tran", model.SQLServer}, + {"set autocommit = 0", model.MySQL}, + {"set implicit_transactions on", model.SQLServer}, + } { + if err := write(c.sql, c.engine); err == nil { + t.Errorf("%s: %s", c.engine, c.sql) + } + } +} + +func TestCQLStatementsAndBatches(t *testing.T) { + cql := func(sql string) (string, error) { return one(sql, model.Cassandra) } + if got, err := cql("select * from ks.t;"); err != nil || got != "select * from ks.t" { + t.Errorf("%q %v", got, err) + } + for _, sql := range []string{ + "select 1 from t; select 2 from t", + "select 1 from t; delete from t where k = 1;", + " -- nothing\n // nothing\n ; ", + } { + if _, err := cql(sql); err == nil { + t.Errorf("%s", sql) + } + } + batch := "BEGIN BATCH\n INSERT INTO ks.t (k) VALUES (1);\n INSERT INTO ks.t (k) VALUES (2);\nAPPLY BATCH;" + if got, err := cql(batch); err != nil || !strings.HasSuffix(got, "APPLY BATCH") { + t.Errorf("batch: %q %v", got, err) + } + for _, head := range []string{"begin unlogged batch", "BEGIN COUNTER BATCH"} { + sql := head + " update t set c = c + 1 where k = 1; apply batch" + if _, err := cql(sql); err != nil { + t.Errorf("%s: %v", sql, err) + } + } + // Whatever follows APPLY BATCH is a second statement. + for _, sql := range []string{batch + " select 1 from t", batch + " delete from t where k = 1;"} { + if _, err := cql(sql); err == nil { + t.Errorf("%s", sql) + } + } + // Other BEGIN statements still split at `;`. + if _, err := cql("begin; select 1 from t"); err == nil { + t.Error("begin; select") + } +} + +func TestCQLLexerHidesSemicolonsAndKeywords(t *testing.T) { + for _, sql := range []string{ + "select 'a;b', \"c;d\" from t -- ;\n where k = 1", + "select 'it''s; here' from t // ; delete from t\n", + "select \"we\"\"ird;\" from t /* ; /* */", + "create function f(a int) returns null on null input returns int language java as $$ return a; $$", + "select $$a;b$$ from t", + } { + if _, err := one(sql, model.Cassandra); err != nil { + t.Errorf("%s: %v", sql, err) + } + } + // Block comments do not nest, `\` does not escape in strings. + for _, sql := range []string{ + "select 1 /* /* */ ; delete from t */", + `select 'a\'; delete from t; -- '`, + "select 'abc", + "select $$ abc", + "select 1 /* open", + } { + if _, err := one(sql, model.Cassandra); err == nil { + t.Errorf("%s", sql) + } + } + // A comment hides a write word from the classifier too. + if err := read("select a from t -- delete\n", model.Cassandra); err != nil { + t.Error(err) + } +} + +func TestCQLClassifier(t *testing.T) { + cql := func(sql string) error { return read(sql, model.Cassandra) } + for _, sql := range []string{ + "SELECT * FROM ks.t WHERE k = 1 LIMIT 10", + "select * from ks.t where c > 1 allow filtering", + "select \"insert\", 'delete from t' from t", + "select writetime(v), ttl(v) from t", + "LIST ROLES", + "list all permissions of alice", + "LIST USERS", + } { + if err := cql(sql); err != nil { + t.Errorf("%s: %v", sql, err) + } + } + if err := cql("describe keyspaces"); err == nil || !strings.Contains(err.Error(), "cqlsh") { + t.Errorf("describe: %v", err) + } + for _, sql := range []string{ + "desc table ks.t", + "insert into t (k) values (1)", + "update t set v = 1 where k = 1", + "delete from t where k = 1", + "begin batch insert into t (k) values (1); apply batch", + "create table t (k int primary key)", + "alter table t add c int", + "drop table t", + "truncate t", + "grant select on t to bob", + "revoke select on t from bob", + "use ks", + "with x as (select 1) select * from x", + "explain select * from t", + "select * from t where k = 1 delete from t", + "select * into t2 from t", + } { + if err := cql(sql); err == nil { + t.Errorf("%s", sql) + } + } +} + +func TestCQLWriteCheck(t *testing.T) { + write := func(sql string) error { + return checkWrite(mustOne(t, sql, model.Cassandra), model.Cassandra) + } + for _, sql := range []string{ + "insert into ks.t (k) values (1)", + "create table ks.t (k int primary key)", + "begin batch insert into t (k) values (1); apply batch", + "BEGIN UNLOGGED BATCH delete from t where k = 1; APPLY BATCH", + "BEGIN COUNTER BATCH update t set c = c + 1; APPLY BATCH", + } { + if err := write(sql); err != nil { + t.Errorf("%s: %v", sql, err) + } + } + for _, sql := range []string{ + "begin transaction", + "commit transaction", + "start transaction", + "commit", + "rollback", + "use ks", + } { + if err := write(sql); err == nil { + t.Errorf("%s", sql) + } + } +} + +func TestExplainTakesTheStatement(t *testing.T) { + if err := checkExplain(mustOne(t, "explain select 1", model.Postgres)); err == nil { + t.Error("explain explain") + } + if err := checkExplain(mustOne(t, "update t set a = 1", model.Postgres)); err != nil { + t.Error(err) + } +} + +func TestRedisAllowlist(t *testing.T) { + for _, cmd := range []string{ + "GET key", + "hgetall \"user:1\"", + "SCAN 0 MATCH user:* COUNT 100", + "MEMORY USAGE key", + "OBJECT ENCODING key", + } { + if err := checkRedis(cmd, false); err != nil { + t.Errorf("%s: %v", cmd, err) + } + } + for _, cmd := range []string{ + "set key 1", + "DEL key", + "MEMORY PURGE", + "CONFIG GET *", + "GET a\nDEL a", + "", + } { + if err := checkRedis(cmd, false); err == nil { + t.Errorf("%q", cmd) + } + } + if err := checkRedis("KEYS *", false); err == nil || !strings.Contains(err.Error(), "SCAN") { + t.Errorf("keys: %v", err) + } + // Write access lifts the allowlist but not the session commands. + if err := checkRedis("SET key 1", true); err != nil { + t.Error(err) + } + for _, cmd := range []string{"MULTI", "select 2"} { + if err := checkRedis(cmd, true); err == nil { + t.Errorf("%s", cmd) + } + } + if err := checkRedis(`GET "open`, false); err == nil || err.Error() != "Unbalanced quotes in the command." { + t.Errorf("quotes: %v", err) + } +} + +func TestRefusesEffectsThatOutliveARollback(t *testing.T) { + for _, c := range []struct { + engine model.Engine + sql string + }{ + {model.SQLServer, "SELECT NEXT VALUE FOR dbo.seq"}, + {model.MariaDB, "select next value for s"}, + {model.MySQL, "SELECT GET_LOCK('x', 1)"}, + {model.Postgres, "select pg_advisory_lock(1)"}, + {model.Postgres, "select lo_creat(-1)"}, + } { + if err := checkRead(mustOne(t, c.sql, c.engine), c.engine); err == nil { + t.Errorf("%s", c.sql) + } + } + if err := checkRead(mustOne(t, "select pg_advisory_xact_lock(1)", model.Postgres), model.Postgres); err != nil { + t.Error(err) + } +} diff --git a/internal/mcp/helpers_test.go b/internal/mcp/helpers_test.go new file mode 100644 index 0000000..9c52d99 --- /dev/null +++ b/internal/mcp/helpers_test.go @@ -0,0 +1,286 @@ +package mcp + +import ( + "bufio" + "context" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/engines" + "github.com/LowBloat/LowQuery/internal/model" +) + +// testClient talks to a server over in-memory pipes, as an MCP client does +// over stdio. +type testClient struct { + t *testing.T + in *io.PipeWriter + lines chan string + nextID int +} + +// startClient serves dir with the time limit; the server stops (and closes +// its sessions) when the test ends. +func startClient(t *testing.T, dir string, timeout time.Duration) (*testClient, *server) { + t.Helper() + s := newServer(dir, timeout) + inR, inW := io.Pipe() + outR, outW := io.Pipe() + done := make(chan struct{}) + go func() { + s.serve(context.Background(), inR, outW) + _ = outW.Close() + close(done) + }() + lines := make(chan string, 100_000) + go func() { + r := bufio.NewReader(outR) + for { + l, err := r.ReadString('\n') + if l != "" { + lines <- l + } + if err != nil { + close(lines) + return + } + } + }() + c := &testClient{t: t, in: inW, lines: lines, nextID: 1} + t.Cleanup(func() { + _ = inW.Close() + select { + case <-done: + case <-time.After(60 * time.Second): + t.Errorf("the server did not stop") + } + }) + return c, s +} + +func (c *testClient) sendRaw(line string) { + c.t.Helper() + if _, err := io.WriteString(c.in, line+"\n"); err != nil { + c.t.Fatalf("write: %v", err) + } +} + +func (c *testClient) recv() map[string]any { + c.t.Helper() + select { + case line, ok := <-c.lines: + if !ok { + c.t.Fatal("the server closed its output") + } + if !strings.HasSuffix(line, "\n") || strings.Contains(strings.TrimSuffix(line, "\n"), "\n") { + c.t.Fatalf("not one line: %q", line) + } + var m map[string]any + if err := json.Unmarshal([]byte(line), &m); err != nil { + c.t.Fatalf("reply is not JSON: %v: %s", err, line) + } + return m + case <-time.After(60 * time.Second): + c.t.Fatal("no reply") + } + return nil +} + +func (c *testClient) request(method string, params any) map[string]any { + c.t.Helper() + id := c.nextID + c.nextID++ + msg, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params}) + c.sendRaw(string(msg)) + reply := c.recv() + if reply["id"] != float64(id) { + c.t.Fatalf("reply to %v instead of %d: %v", reply["id"], id, reply) + } + return reply +} + +func (c *testClient) initialize(version string) map[string]any { + c.t.Helper() + r := c.request("initialize", map[string]any{ + "protocolVersion": version, + "capabilities": map[string]any{}, + "clientInfo": map[string]any{"name": "test-client", "version": "1.0"}, + }) + c.sendRaw(`{"jsonrpc":"2.0","method":"notifications/initialized"}`) + return r +} + +func (c *testClient) call(tool string, args map[string]any) map[string]any { + c.t.Helper() + r := c.request("tools/call", map[string]any{"name": tool, "arguments": args}) + result, ok := r["result"].(map[string]any) + if !ok { + c.t.Fatalf("%s: no result: %v", tool, r) + } + return result +} + +// --------------------------------------------------------------------------- +// Reading results + +func textOf(result map[string]any) string { + content, _ := result["content"].([]any) + if len(content) == 0 { + return "" + } + first, _ := content[0].(map[string]any) + s, _ := first["text"].(string) + return s +} + +func isErr(result map[string]any) bool { return result["isError"] == true } + +func structuredOf(result map[string]any) map[string]any { + s, _ := result["structuredContent"].(map[string]any) + return s +} + +func arr(v any) []any { + a, _ := v.([]any) + return a +} + +func mapOf(v any) map[string]any { + m, _ := v.(map[string]any) + return m +} + +// rowsOf returns the rows of a result as text, nil for NULL. +func rowsOf(result map[string]any) [][]*string { + out := [][]*string{} + for _, r := range arr(structuredOf(result)["rows"]) { + row := []*string{} + for _, v := range arr(r) { + if s, ok := v.(string); ok { + row = append(row, &s) + } else { + row = append(row, nil) + } + } + out = append(out, row) + } + return out +} + +// showRows writes rows with NULL as , for comparisons. +func showRows(rows [][]*string) string { + parts := []string{} + for _, row := range rows { + cells := []string{} + for _, v := range row { + if v == nil { + cells = append(cells, "") + } else { + cells = append(cells, *v) + } + } + parts = append(parts, "["+strings.Join(cells, ", ")+"]") + } + return strings.Join(parts, " ") +} + +func jsonText(v any) string { + b, _ := json.Marshal(v) + return string(b) +} + +// --------------------------------------------------------------------------- +// Databases + +func env(name string) string { return os.Getenv(name) } + +func envOr(name, fallback string) string { + if v := os.Getenv(name); v != "" { + return v + } + return fallback +} + +func port(name string, fallback uint16) uint16 { + var p uint16 + if _, err := fmt.Sscan(os.Getenv(name), &p); err == nil && p != 0 { + return p + } + return fallback +} + +func execOn(ctx context.Context, s drivers.Session, sql string) (*model.ExecResult, error) { + return s.Execute(ctx, model.ExecRequest{SQL: sql}) +} + +// sqliteProfile is a profile for the SQLite file at path. +func sqliteProfile(id, name, path string, access model.AiAccess) model.ConnectionProfile { + p := model.DefaultProfile() + p.ID = id + p.Name = name + p.Engine = model.SQLite + p.Database = path + p.AiAccess = access + return p +} + +// makeDB creates the teams/users test database at path. +func makeDB(t *testing.T, path string) { + t.Helper() + p := sqliteProfile("", "", path, "off") + p.CreateFile = true + ctx := context.Background() + s, err := engines.Open(ctx, p, nil) + if err != nil { + t.Fatal(err) + } + defer s.Close() + for _, sql := range []string{ + "CREATE TABLE teams (id INTEGER PRIMARY KEY, name TEXT NOT NULL)", + "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, team_id INTEGER REFERENCES teams(id), bio TEXT)", + "INSERT INTO teams VALUES (1, 'core')", + "INSERT INTO users VALUES (1, 'Ann', 1, NULL), (2, 'Bob', 1, 'line1\nline2'), (3, 'Cid', NULL, NULL)", + } { + if _, err := execOn(ctx, s, sql); err != nil { + t.Fatalf("%s: %v", sql, err) + } + } +} + +// scalarOf reads one value from the SQLite file at path, on a session of +// its own. +func scalarOf(t *testing.T, path, sql string) string { + t.Helper() + ctx := context.Background() + s, err := engines.Open(ctx, sqliteProfile("", "", path, "off"), nil) + if err != nil { + t.Fatal(err) + } + defer s.Close() + r, err := execOn(ctx, s, sql) + if err != nil { + t.Fatalf("%s: %v", sql, err) + } + return cellText(r.Rows[0], 0) +} + +func writeProfiles(t *testing.T, dir string, profiles ...model.ConnectionProfile) { + t.Helper() + data, err := json.Marshal(profiles) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "connections.json"), data, 0o644); err != nil { + t.Fatal(err) + } +} + +type apperrError = apperr.Error diff --git a/internal/mcp/json.go b/internal/mcp/json.go new file mode 100644 index 0000000..7102cc4 --- /dev/null +++ b/internal/mcp/json.go @@ -0,0 +1,87 @@ +package mcp + +import ( + "bytes" + "encoding/json" +) + +// field is one member of an obj. +type field struct { + K string + V any +} + +// obj is a JSON object that keeps its keys in the order they were added, so +// tool definitions and results read in a natural order. +type obj []field + +func (o obj) MarshalJSON() ([]byte, error) { + var buf bytes.Buffer + buf.WriteByte('{') + for i, f := range o { + if i > 0 { + buf.WriteByte(',') + } + k, err := marshal(f.K) + if err != nil { + return nil, err + } + buf.Write(k) + buf.WriteByte(':') + v, err := marshal(f.V) + if err != nil { + return nil, err + } + buf.Write(v) + } + buf.WriteByte('}') + return buf.Bytes(), nil +} + +// set replaces the value of k, or adds k at the end. +func (o *obj) set(k string, v any) { + for i := range *o { + if (*o)[i].K == k { + (*o)[i].V = v + return + } + } + *o = append(*o, field{k, v}) +} + +// get returns the value of k. +func (o obj) get(k string) (any, bool) { + for _, f := range o { + if f.K == k { + return f.V, true + } + } + return nil, false +} + +// without returns o without the given keys. +func (o obj) without(keys ...string) obj { + out := make(obj, 0, len(o)) +outer: + for _, f := range o { + for _, k := range keys { + if f.K == k { + continue outer + } + } + out = append(out, f) + } + return out +} + +// marshal is json.Marshal without HTML escaping (<, > and & stay as they +// are, as in SQL text). +func marshal(v any) ([]byte, error) { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + if err := enc.Encode(v); err != nil { + return nil, err + } + return bytes.TrimSuffix(buf.Bytes(), []byte("\n")), nil +} diff --git a/internal/mcp/server.go b/internal/mcp/server.go new file mode 100644 index 0000000..0c76e90 --- /dev/null +++ b/internal/mcp/server.go @@ -0,0 +1,911 @@ +package mcp + +// MCP over stdio: JSON-RPC 2.0, one message per line. Tool calls run +// concurrently, serialized per connection, each on the connection's own +// agent session (separate from the app's) under a time limit. + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + "unicode/utf8" + + "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" +) + +// protocolVersions are the supported revisions, newest first. +var protocolVersions = []string{"2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"} + +const ( + defaultTimeout = 30 * time.Second + // grace is the time a cancelled call gets to stop before its session is + // dropped. + grace = 5 * time.Second +) + +const ( + accessRead model.AiAccess = "read" + accessWrite model.AiAccess = "write" +) + +const instructions = "LowQuery gives you the database connections the user opened to AI agents. " + + "Start with list_connections to see each connection's engine, access (read or write) and SQL dialect. " + + "Find tables with search_objects (or list_schemas and list_tables), and read describe_table before " + + "writing SQL so you use the real column names, keys and foreign keys. Write SQL in the connection's own " + + "dialect (FETCH FIRST n ROWS ONLY on Oracle, TOP (n) on SQL Server, LIMIT n elsewhere) and send one " + + "statement per call. Keep result sets small: select only the columns you need and filter or aggregate in " + + "SQL. Use explain to check the plan of a heavy query before running it. Use execute only when the user " + + "asked for a change; read-only connections refuse changes." + +// Run is the entry point of `lowquery mcp`: serves stdin/stdout until stdin +// closes. configDir holds connections.json and the activity log; version is +// the app version reported in serverInfo. +func Run(configDir, version string) { + Serve(context.Background(), configDir, version, os.Stdin, os.Stdout) +} + +// Serve serves JSON-RPC lines from r, answering on w, until r closes or ctx +// is done, then waits for the calls still running (a done ctx cancels them) +// and closes the agent sessions. The time limit of each call comes from +// LOWQUERY_MCP_TIMEOUT (seconds, default 30). +func Serve(ctx context.Context, configDir, version string, r io.Reader, w io.Writer) { + s := newServer(configDir, timeoutFromEnv()) + s.appVersion = version + s.serve(ctx, r, w) +} + +func timeoutFromEnv() time.Duration { + v, err := strconv.ParseUint(strings.TrimSpace(os.Getenv("LOWQUERY_MCP_TIMEOUT")), 10, 64) + if err != nil || v == 0 { + return defaultTimeout + } + return time.Duration(v) * time.Second +} + +// callCancel is a cancel request for one tool call (notifications/cancelled). +type callCancel struct { + flag atomic.Bool + once sync.Once + done chan struct{} +} + +func newCancel() *callCancel { return &callCancel{done: make(chan struct{})} } + +func (c *callCancel) cancel() { + c.flag.Store(true) + c.once.Do(func() { close(c.done) }) +} + +func (c *callCancel) isCancelled() bool { return c.flag.Load() } + +// callKind is how a call uses the session. +type callKind int + +const ( + // kindRead: reads, inside a read-only transaction rolled back afterwards + // on read-only connections. + kindRead callKind = iota + // kindExplain is like kindRead, but Oracle skips SET TRANSACTION READ + // ONLY: EXPLAIN PLAN writes PLAN_TABLE (and is rolled back). + kindExplain + // kindWrite is execute on a write connection: autocommit, no transaction + // left open. + kindWrite +) + +// slot holds the agent session of one connection. +type slot struct { + mu sync.Mutex + session drivers.Session + // The profile the session was opened with. + fingerprint string +} + +// reply is what a tool returns. +type reply struct { + text string + structured any + isError bool + // Rows returned or affected, for the activity log. + rows *uint64 +} + +func okReply(text string, structured any) *reply { + return &reply{text: text, structured: structured} +} + +func errReply(text string) *reply { + return &reply{text: text, isError: true} +} + +func (r *reply) withRows(n int) *reply { + v := uint64(n) + r.rows = &v + return r +} + +func (r *reply) result(structured bool) obj { + out := obj{{"content", []obj{{{"type", "text"}, {"text", r.text}}}}} + if structured && r.structured != nil { + out.set("structuredContent", r.structured) + } + if r.isError { + out.set("isError", true) + } + return out +} + +// callInfo says what a call is about, for the activity log. +type callInfo struct { + connectionID *string + connectionName *string + detail *string +} + +// server is one MCP session over one pair of streams. +type server struct { + configDir string + appVersion string + timeout time.Duration + + mu sync.Mutex + // clientInfo of initialize, as "name version". + client string + version string + slots map[string]*slot + inflight map[string]*callCancel + + out *outbox + calls sync.WaitGroup +} + +func newServer(configDir string, timeout time.Duration) *server { + return &server{ + configDir: configDir, + appVersion: "dev", + timeout: timeout, + client: "unknown", + version: protocolVersions[0], + slots: map[string]*slot{}, + inflight: map[string]*callCancel{}, + } +} + +// outbox writes messages in order from a goroutine of its own, so a slow +// reader on the other side never blocks the reading of requests. +type outbox struct { + mu sync.Mutex + cond *sync.Cond + queue [][]byte + closed bool + done chan struct{} +} + +func newOutbox(w io.Writer) *outbox { + o := &outbox{done: make(chan struct{})} + o.cond = sync.NewCond(&o.mu) + go func() { + defer close(o.done) + failed := false + for { + o.mu.Lock() + for len(o.queue) == 0 && !o.closed { + o.cond.Wait() + } + if len(o.queue) == 0 { + o.mu.Unlock() + return + } + line := o.queue[0] + o.queue = o.queue[1:] + o.mu.Unlock() + if failed { + continue + } + if _, err := w.Write(line); err != nil { + fmt.Fprintln(os.Stderr, "lowquery mcp: stdout closed") + failed = true + } + } + }() + return o +} + +func (o *outbox) send(message any) { + line, err := marshal(message) + if err != nil { + return + } + line = append(line, '\n') + o.mu.Lock() + if !o.closed { + o.queue = append(o.queue, line) + o.cond.Signal() + } + o.mu.Unlock() +} + +// close lets the writer finish the queue and waits for it. +func (o *outbox) close() { + o.mu.Lock() + o.closed = true + o.cond.Signal() + o.mu.Unlock() + <-o.done +} + +func response(id any, result any) obj { + return obj{{"jsonrpc", "2.0"}, {"id", id}, {"result", result}} +} + +func errorResponse(id any, code int, message string) obj { + return obj{{"jsonrpc", "2.0"}, {"id", id}, {"error", obj{{"code", code}, {"message", message}}}} +} + +// serve reads lines from r until it closes or ctx is done, then waits for +// the calls still running. +func (s *server) serve(ctx context.Context, r io.Reader, w io.Writer) { + s.out = newOutbox(w) + lines := make(chan []byte) + go func() { + defer close(lines) + reader := bufio.NewReader(r) + for { + line, err := reader.ReadBytes('\n') + if len(line) > 0 { + select { + case lines <- line: + case <-ctx.Done(): + return + } + } + if err != nil { + if !errors.Is(err, io.EOF) { + fmt.Fprintf(os.Stderr, "lowquery mcp: reading stdin failed: %v\n", err) + } + return + } + } + }() +read: + for { + select { + case line, ok := <-lines: + if !ok { + break read + } + switch { + case !utf8.Valid(line): + s.out.send(errorResponse(nil, -32700, "Parse error: the message is not UTF-8.")) + case strings.TrimSpace(string(line)) == "": + default: + s.handle(ctx, strings.TrimSpace(string(line))) + } + case <-ctx.Done(): + s.mu.Lock() + for _, c := range s.inflight { + c.cancel() + } + s.mu.Unlock() + break read + } + } + s.calls.Wait() + s.out.close() + s.closeSessions() +} + +// closeSessions closes every agent session. +func (s *server) closeSessions() { + s.mu.Lock() + slots := s.slots + s.slots = map[string]*slot{} + s.mu.Unlock() + for _, sl := range slots { + sl.mu.Lock() + if sl.session != nil { + _ = sl.session.Close() + sl.session = nil + } + sl.mu.Unlock() + } +} + +// negotiated is the protocol revision in use. +func (s *server) negotiated() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.version +} + +func (s *server) handle(ctx context.Context, text string) { + dec := json.NewDecoder(strings.NewReader(text)) + dec.UseNumber() + var message any + if err := dec.Decode(&message); err != nil { + s.out.send(errorResponse(nil, -32700, "Parse error: "+err.Error())) + return + } + if dec.More() { + s.out.send(errorResponse(nil, -32700, "Parse error: trailing characters after the message.")) + return + } + m, isObject := message.(map[string]any) + if !isObject { + why := "Invalid request: expected a JSON object." + if _, isArray := message.([]any); isArray { + why = "Invalid request: batches are not supported; send one message per line." + } + s.out.send(errorResponse(nil, -32600, why)) + return + } + id, hasID := m["id"] + if id == nil { + hasID = false + } + method, hasMethod := m["method"].(string) + if !hasMethod { + // Responses to server requests: this server sends none. + _, isResult := m["result"] + _, isError := m["error"] + if !isResult && !isError && hasID { + s.out.send(errorResponse(id, -32600, "Invalid request: method is missing.")) + } + return + } + params := m["params"] + if !hasID { + s.notification(method, params) + return + } + switch id.(type) { + case string, json.Number: + default: + s.out.send(errorResponse(nil, -32600, "Invalid request: id must be a string or a number.")) + return + } + if v, _ := m["jsonrpc"].(string); v != "2.0" { + s.out.send(errorResponse(id, -32600, `Invalid request: jsonrpc must be "2.0".`)) + return + } + p, isParams := params.(map[string]any) + if params != nil && !isParams { + s.out.send(errorResponse(id, -32602, "Invalid params: params must be an object.")) + return + } + switch method { + case "initialize": + s.out.send(s.initialize(id, p)) + case "ping": + s.out.send(response(id, obj{})) + case "tools/list": + s.out.send(response(id, toolList(s.negotiated()))) + case "tools/call": + s.startCall(ctx, id, p) + default: + s.out.send(errorResponse(id, -32601, "Method not found: "+method)) + } +} + +// requestKey is the key of a request id in the inflight table: its JSON +// text, so 7 and "7" stay apart. +func requestKey(id any) string { + b, _ := marshal(id) + return string(b) +} + +func (s *server) notification(method string, params any) { + if method == "notifications/cancelled" { + p, _ := params.(map[string]any) + if request, ok := p["requestId"]; ok && request != nil { + s.mu.Lock() + c := s.inflight[requestKey(request)] + s.mu.Unlock() + if c != nil { + c.cancel() + } + } + } + // notifications/initialized and the rest need nothing. +} + +func (s *server) initialize(id any, params map[string]any) obj { + requested, ok := params["protocolVersion"].(string) + if !ok { + return errorResponse(id, -32602, "Invalid params: protocolVersion is required.") + } + version := protocolVersions[0] + for _, v := range protocolVersions { + if v == requested { + version = v + } + } + info, _ := params["clientInfo"].(map[string]any) + fieldOf := func(k string) string { + v, _ := info[k].(string) + return strings.TrimSpace(v) + } + client := strings.TrimSpace(fieldOf("name") + " " + fieldOf("version")) + s.mu.Lock() + s.version = version + if client != "" { + s.client = client + } + s.mu.Unlock() + return response(id, obj{ + {"protocolVersion", version}, + {"capabilities", obj{{"tools", obj{{"listChanged", false}}}}}, + {"serverInfo", obj{ + {"name", "lowquery"}, + {"title", "LowQuery"}, + {"version", s.appVersion}, + }}, + {"instructions", instructions}, + }) +} + +func (s *server) startCall(ctx context.Context, id any, params map[string]any) { + name, ok := params["name"].(string) + if !ok { + s.out.send(errorResponse(id, -32602, "Invalid params: name is required.")) + return + } + args := map[string]any{} + switch a := params["arguments"].(type) { + case nil: + case map[string]any: + args = a + default: + s.out.send(errorResponse(id, -32602, "Invalid params: arguments must be an object.")) + return + } + if !toolExists(name) { + s.log(name, &callInfo{}, errReply("Unknown tool."), 0) + s.out.send(errorResponse(id, -32602, "Unknown tool: "+name)) + return + } + key := requestKey(id) + c := newCancel() + s.mu.Lock() + s.inflight[key] = c + s.mu.Unlock() + if ctx.Err() != nil { + c.cancel() + } + s.calls.Add(1) + go func() { + defer s.calls.Done() + result := s.call(name, args, c) + s.mu.Lock() + if s.inflight[key] == c { + delete(s.inflight, key) + } + s.mu.Unlock() + // A cancelled request gets no response. + if !c.isCancelled() { + s.out.send(response(id, result)) + } + }() +} + +func (s *server) call(name string, args map[string]any, c *callCancel) obj { + started := time.Now() + info := &callInfo{} + r := runTool(s, name, args, c, info) + s.log(name, info, r, uint64(time.Since(started).Milliseconds())) + return r.result(s.negotiated() >= "2025-06-18") +} + +// capChars cuts s to n characters, marking the cut with an ellipsis. +func capChars(s string, n int) string { + if utf8.RuneCountInString(s) <= n { + return s + } + return firstChars(s, n) + "…" +} + +func (s *server) log(tool string, info *callInfo, r *reply, elapsedMs uint64) { + s.mu.Lock() + client := s.client + s.mu.Unlock() + entry := AuditEntry{ + At: time.Now().UTC().Format("2006-01-02T15:04:05.000Z"), + Client: client, + Tool: tool, + ConnectionID: info.connectionID, + ConnectionName: info.connectionName, + OK: !r.isError, + Rows: r.rows, + ElapsedMs: elapsedMs, + } + if info.detail != nil { + entry.Detail = model.Str(capChars(*info.detail, 4000)) + } + if r.isError { + entry.Error = model.Str(capChars(r.text, 2000)) + } + appendAudit(s.configDir, entry) +} + +// agentProfiles returns the profiles open to agents, read again on every +// call. +func (s *server) agentProfiles() ([]model.ConnectionProfile, error) { + fail := func(err error) error { + return fmt.Errorf("Could not read the LowQuery connections: %s", apperr.From(err).Error()) + } + store, err := profiles.NewStore(s.configDir) + if err != nil { + return nil, fail(err) + } + all, err := store.List() + if err != nil { + return nil, fail(err) + } + out := []model.ConnectionProfile{} + for _, p := range all { + if p.AiAccess == accessRead || p.AiAccess == accessWrite { + out = append(out, p) + } + } + return out, nil +} + +func (s *server) slot(id string) *slot { + s.mu.Lock() + defer s.mu.Unlock() + sl, ok := s.slots[id] + if !ok { + sl = &slot{} + s.slots[id] = sl + } + return sl +} + +func (s *server) limitError(timedOut bool) error { + if timedOut { + return apperr.Newf(apperr.Cancelled, + "The call took longer than %d s and was cancelled. Narrow the query, or ask the user to raise LOWQUERY_MCP_TIMEOUT.", + int64(s.timeout/time.Second)) + } + return apperr.New(apperr.Cancelled, "The client cancelled the call.") +} + +// withGrace runs fn with grace to finish; an error when it fails or does not +// finish in time. +func withGrace(fn func(ctx context.Context) error) error { + ctx, cancel := context.WithTimeout(context.Background(), grace) + defer cancel() + done := make(chan error, 1) + go func() { done <- fn(ctx) }() + select { + case err := <-done: + return err + case <-time.After(grace + 100*time.Millisecond): + return apperr.New(apperr.Cancelled, "Timed out.") + } +} + +// bounded runs work until the time limit or a cancel request; then asks +// the session to cancel and gives it grace to stop. healthy says whether +// the session is still usable. +func (s *server) bounded(session drivers.Session, c *callCancel, work func(ctx context.Context) error) (err error, healthy bool) { + ctx, stop := context.WithCancel(context.Background()) + defer stop() + done := make(chan error, 1) + go func() { done <- work(ctx) }() + timer := time.NewTimer(s.timeout) + defer timer.Stop() + timedOut := false + select { + case err := <-done: + return err, true + case <-timer.C: + timedOut = true + case <-c.done: + } + err = s.limitError(timedOut) + cancelled := withGrace(session.Cancel) == nil + stopped := false + if cancelled { + select { + case <-done: + stopped = true + case <-time.After(grace): + } + } + return err, stopped +} + +// open opens the agent session of profile under the time limit. +func (s *server) open(p model.ConnectionProfile, c *callCancel) (drivers.Session, error) { + type opened struct { + session drivers.Session + err error + } + ctx, stop := context.WithCancel(context.Background()) + defer stop() + ch := make(chan opened, 1) + go func() { + session, err := openSession(ctx, p) + ch <- opened{session, err} + }() + timer := time.NewTimer(s.timeout) + defer timer.Stop() + timedOut := false + select { + case o := <-ch: + return o.session, o.err + case <-timer.C: + timedOut = true + case <-c.done: + } + // A session that opens after all is closed. + go func() { + if o := <-ch; o.session != nil { + _ = o.session.Close() + } + }() + return nil, s.limitError(timedOut) +} + +// drop closes a session that is no longer used, without waiting for it. +func drop(session drivers.Session) { + if session != nil { + go func() { _ = session.Close() }() + } +} + +// run runs op on the agent session of profile, opening it when needed. +// Calls on one connection wait for each other. On read-only connections +// every call runs in a read-only transaction (where the engine has one) +// that is always rolled back. +func (s *server) run(p model.ConnectionProfile, kind callKind, c *callCancel, op func(ctx context.Context, session drivers.Session) error) error { + sl := s.slot(p.ID) + sl.mu.Lock() + defer sl.mu.Unlock() + fp, _ := json.Marshal(p) + if sl.fingerprint != string(fp) { + drop(sl.session) + sl.session = nil + sl.fingerprint = string(fp) + } + readOnly := p.AiAccess == accessRead + // A stale connection fails the first read; a write is never retried. + attempts := 2 + if kind == kindWrite { + attempts = 1 + } + for attempt := 1; ; attempt++ { + reused := sl.session != nil + session := sl.session + if session == nil { + opened, err := s.open(p, c) + if err != nil { + return err + } + sl.session = opened + session = opened + } + + outcome, healthy := s.bounded(session, c, func(ctx context.Context) error { + if readOnly { + if err := beginRead(ctx, session, kind); err != nil { + return err + } + } + return op(ctx, session) + }) + engine := session.Engine() + // Redis and Cassandra have no transactions to roll back. + if healthy && readOnly && engine != model.Redis && engine != model.Cassandra { + healthy = withGrace(func(ctx context.Context) error { + _, err := session.EndTransaction(ctx, false) + return err + }) == nil + } + if healthy && kind == kindWrite && session.TxState().InTransaction { + healthy = withGrace(func(ctx context.Context) error { + _, err := session.EndTransaction(ctx, false) + return err + }) == nil + outcome = apperr.New(apperr.Invalid, "The statement left a transaction open, so LowQuery rolled it back. Each execute call commits on its own; do not open transactions.") + } + // The Oracle driver does not report a transaction opened by a query + // (SELECT ... FOR UPDATE), so its locks would outlive the call; DML + // has already been committed by autocommit. + if healthy && kind == kindWrite && engine == model.Oracle && outcome == nil { + healthy = withGrace(func(ctx context.Context) error { + _, err := session.EndTransaction(ctx, true) + return err + }) == nil + } + lost := outcome != nil && apperr.From(outcome).Kind == apperr.Connection + // SQL Server explains between SET SHOWPLAN_ALL ON and OFF: a failure + // may leave the session returning plans instead of rows. + showplan := kind == kindExplain && engine == model.SQLServer && outcome != nil + if !healthy || lost || showplan { + drop(sl.session) + sl.session = nil + } + if lost && reused && attempt < attempts { + continue + } + return outcome + } +} + +func execSQL(ctx context.Context, session drivers.Session, sql string) error { + _, err := session.Execute(ctx, model.ExecRequest{SQL: sql, MaxRows: 0}) + return err +} + +// beginRead starts the read-only transaction of one call. +func beginRead(ctx context.Context, session drivers.Session, kind callKind) error { + switch session.Engine() { + case model.Postgres: + return execSQL(ctx, session, "SET TRANSACTION READ ONLY") + case model.MySQL, model.MariaDB: + return execSQL(ctx, session, "START TRANSACTION READ ONLY") + case model.Oracle: + if kind != kindExplain { + return execSQL(ctx, session, "SET TRANSACTION READ ONLY") + } + } + // SQLite is read-only by session setting; Redis and Cassandra have no + // read-only transaction (the guard is the protection). + return nil +} + +// makeReadOnly applies the session settings of read-only connections: +// read-only by default where the engine allows it, and manual commit so +// every call can be rolled back. +func makeReadOnly(ctx context.Context, session drivers.Session) error { + var err error + switch session.Engine() { + case model.Postgres: + err = execSQL(ctx, session, "SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY") + case model.MySQL, model.MariaDB: + err = execSQL(ctx, session, "SET SESSION TRANSACTION READ ONLY") + case model.SQLite: + err = execSQL(ctx, session, "PRAGMA query_only = ON") + case model.Redis, model.Cassandra: + return nil + } + if err != nil { + return err + } + _, err = session.SetAutocommit(ctx, false) + return err +} + +// authFailureCodes are the engine codes of a rejected sign-in. +var authFailureCodes = map[string]bool{ + "28P01": true, "28000": true, "ORA-01017": true, "ORA-01005": true, + "1045 (28000)": true, "1044 (42000)": true, "1698 (28000)": true, + "NOAUTH": true, "WRONGPASS": true, "AuthenticationError": true, +} + +func isAuthFailure(e *apperr.Error) bool { + return authFailureCodes[e.Code] || + strings.HasPrefix(e.Code, "Msg 18456,") || + strings.Contains(strings.ToLower(e.Message), "password") +} + +const noPassword = "Open this connection once in LowQuery and save its password so agents can use it." + +// testPasswords holds passwords by profile id, used instead of the OS +// credential store in tests (CI has none). A nil value means the profile has +// no password. +var ( + testPasswordsMu sync.Mutex + testPasswords map[string]*string +) + +// setTestPassword makes openSession use password for the profile id. +func setTestPassword(id string, password *string) { + testPasswordsMu.Lock() + defer testPasswordsMu.Unlock() + if testPasswords == nil { + testPasswords = map[string]*string{} + } + testPasswords[id] = password +} + +func storedPassword(id string) (*string, error) { + testPasswordsMu.Lock() + pw, ok := testPasswords[id] + testPasswordsMu.Unlock() + if ok { + return pw, nil + } + return profiles.StoredPassword(id) +} + +func openSession(ctx context.Context, p model.ConnectionProfile) (drivers.Session, error) { + readOnly := p.AiAccess == accessRead + var session drivers.Session + var err error + switch { + case p.Engine == model.SQLite: + session, err = openSqlite(ctx, p, readOnly) + case p.Engine == model.SQLServer && p.WindowsAuth: + session, err = engines.Open(ctx, p, nil) + default: + var pw *string + if pw, err = storedPassword(p.ID); err != nil { + return nil, err + } + session, err = engines.Open(ctx, p, pw) + // Servers with trust or no authentication need none. + if err != nil && pw == nil { + if e := apperr.From(err); isAuthFailure(e) { + out := apperr.New(apperr.PasswordRequired, noPassword) + out.Detail = e.Error() + err = out + } + } + } + if err != nil { + return nil, err + } + if readOnly { + if err := makeReadOnly(ctx, session); err != nil { + _ = session.Close() + out := apperr.New(apperr.Connection, "Could not make the agent session read-only.") + out.Detail = apperr.From(err).Error() + return nil, out + } + } + return session, nil +} + +// openSqlite opens SQLite files of read-only connections with mode=ro when +// the path can be written as a URI, so the file itself is read-only for the +// session. +func openSqlite(ctx context.Context, p model.ConnectionProfile, readOnly bool) (drivers.Session, error) { + if readOnly { + p.CreateFile = false + if uri, ok := readOnlyURI(p.Database); ok { + ro := p + ro.Database = uri + // A WAL database without its -shm file cannot open read-only; + // query_only still applies to the normal open below. + if s, err := engines.Open(ctx, ro, nil); err == nil { + return s, nil + } + } + } + return engines.Open(ctx, p, nil) +} + +func readOnlyURI(path string) (string, bool) { + path = strings.TrimSpace(path) + if path == "" || path == ":memory:" || strings.HasPrefix(path, "file:") || strings.HasPrefix(path, `\\`) { + return "", false + } + path = strings.ReplaceAll(path, `\`, "/") + encoded := strings.NewReplacer("%", "%25", "?", "%3f", "#", "%23").Replace(path) + // file:C:/... for drive paths: the SQLite VFS of the Go driver refuses + // the file:///C:/... form. + prefix := "file:" + if strings.HasPrefix(path, "/") { + prefix = "file://" + } + return prefix + encoded + "?mode=ro", true +} + +// obj is what goes on the wire. +var _ json.Marshaler = obj{} diff --git a/internal/mcp/server_test.go b/internal/mcp/server_test.go new file mode 100644 index 0000000..36c4ea1 --- /dev/null +++ b/internal/mcp/server_test.go @@ -0,0 +1,497 @@ +package mcp + +import ( + "context" + "fmt" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/model" +) + +func TestProtocolBasics(t *testing.T) { + dir := t.TempDir() + c, _ := startClient(t, dir, defaultTimeout) + + init := c.initialize("2025-06-18") + result := mapOf(init["result"]) + if result["protocolVersion"] != "2025-06-18" { + t.Fatalf("version: %v", init) + } + if mapOf(result["serverInfo"])["name"] != "lowquery" { + t.Fatalf("serverInfo: %v", init) + } + if mapOf(mapOf(result["capabilities"])["tools"])["listChanged"] != false { + t.Fatalf("capabilities: %v", init) + } + if !strings.Contains(result["instructions"].(string), "list_connections") { + t.Fatalf("instructions: %v", init) + } + + init = c.initialize("1999-01-01") + if mapOf(init["result"])["protocolVersion"] != protocolVersions[0] { + t.Fatalf("fallback version: %v", init) + } + + missing := c.request("initialize", map[string]any{}) + if mapOf(missing["error"])["code"] != float64(-32602) { + t.Fatalf("missing version: %v", missing) + } + + // Notifications get no reply: the next line answers the ping. + c.sendRaw(`{"jsonrpc":"2.0","method":"notifications/whatever"}`) + pong := c.request("ping", map[string]any{}) + if jsonText(pong["result"]) != "{}" { + t.Fatalf("ping: %v", pong) + } + + unknown := c.request("resources/list", map[string]any{}) + if mapOf(unknown["error"])["code"] != float64(-32601) { + t.Fatalf("unknown method: %v", unknown) + } + + c.sendRaw("{not json") + bad := c.recv() + if mapOf(bad["error"])["code"] != float64(-32700) { + t.Fatalf("parse error: %v", bad) + } + if v, ok := bad["id"]; !ok || v != nil { + t.Fatalf("parse error id: %v", bad) + } + + c.sendRaw(`[{"jsonrpc":"2.0","id":99,"method":"ping"}]`) + if r := c.recv(); mapOf(r["error"])["code"] != float64(-32600) { + t.Fatalf("batch: %v", r) + } + + noTool := c.request("tools/call", map[string]any{"name": "drop_everything"}) + if mapOf(noTool["error"])["code"] != float64(-32602) { + t.Fatalf("unknown tool: %v", noTool) + } + noName := c.request("tools/call", map[string]any{}) + if mapOf(noName["error"])["code"] != float64(-32602) { + t.Fatalf("no name: %v", noName) + } + + // String ids come back as strings; ids of other types are refused. + c.sendRaw(`{"jsonrpc":"2.0","id":"a-1","method":"ping"}`) + if r := c.recv(); r["id"] != "a-1" || r["result"] == nil { + t.Fatalf("string id: %v", r) + } + c.sendRaw(`{"jsonrpc":"2.0","id":true,"method":"ping"}`) + if r := c.recv(); mapOf(r["error"])["code"] != float64(-32600) || r["id"] != nil { + t.Fatalf("bool id: %v", r) + } + c.sendRaw(`{"jsonrpc":"1.0","id":5,"method":"ping"}`) + if r := c.recv(); mapOf(r["error"])["code"] != float64(-32600) || r["id"] != float64(5) { + t.Fatalf("jsonrpc 1.0: %v", r) + } + c.sendRaw(`{"jsonrpc":"2.0","id":6,"method":"ping","params":[1]}`) + if r := c.recv(); mapOf(r["error"])["code"] != float64(-32602) { + t.Fatalf("array params: %v", r) + } + c.sendRaw("\xff\xfe") + if r := c.recv(); mapOf(r["error"])["code"] != float64(-32700) { + t.Fatalf("not UTF-8: %v", r) + } +} + +func TestToolsListShape(t *testing.T) { + dir := t.TempDir() + c, _ := startClient(t, dir, defaultTimeout) + c.initialize("2025-11-25") + list := c.request("tools/list", map[string]any{}) + tools := arr(mapOf(list["result"])["tools"]) + names := []string{} + for _, tool := range tools { + names = append(names, mapOf(tool)["name"].(string)) + } + if !slices.Equal(names, toolNames) { + t.Fatalf("names: %v", names) + } + for _, v := range tools { + tool := mapOf(v) + if mapOf(tool["inputSchema"])["type"] != "object" { + t.Fatalf("inputSchema: %v", tool) + } + if len(tool["description"].(string)) <= 20 { + t.Fatalf("description: %v", tool) + } + if mapOf(tool["outputSchema"])["type"] != "object" { + t.Fatalf("outputSchema: %v", tool) + } + ann := mapOf(tool["annotations"]) + if ann["openWorldHint"] != false { + t.Fatalf("annotations: %v", tool) + } + write := tool["name"] == "execute" + if ann["readOnlyHint"] != !write { + t.Fatalf("readOnlyHint: %v", tool) + } + if write && (ann["destructiveHint"] != true || ann["idempotentHint"] != false) { + t.Fatalf("execute hints: %v", tool) + } + } + + // Older clients get the fields their revision defines. + c.initialize("2024-11-05") + list = c.request("tools/list", map[string]any{}) + first := mapOf(arr(mapOf(list["result"])["tools"])[0]) + if _, ok := first["outputSchema"]; ok { + t.Fatalf("outputSchema on 2024-11-05: %v", first) + } + if _, ok := first["annotations"]; ok { + t.Fatalf("annotations on 2024-11-05: %v", first) + } + c.initialize("2025-03-26") + list = c.request("tools/list", map[string]any{}) + first = mapOf(arr(mapOf(list["result"])["tools"])[0]) + if _, ok := first["annotations"]; !ok { + t.Fatalf("annotations on 2025-03-26: %v", first) + } + if _, ok := first["title"]; ok { + t.Fatalf("title on 2025-03-26: %v", first) + } +} + +func TestEndToEndSqlite(t *testing.T) { + dir := t.TempDir() + roDB := filepath.Join(dir, "ro.db") + rwDB := filepath.Join(dir, "rw.db") + makeDB(t, roDB) + makeDB(t, rwDB) + writeProfiles(t, dir, + sqliteProfile("p-ro", "Local RO", roDB, accessRead), + sqliteProfile("p-off", "Hidden", roDB, "off"), + sqliteProfile("p-rw", "Local RW", rwDB, accessWrite), + ) + + c, srv := startClient(t, dir, 2*time.Second) + c.initialize("2025-11-25") + + // Off connections do not exist for agents. + list := c.call("list_connections", map[string]any{}) + conns := arr(structuredOf(list)["connections"]) + if len(conns) != 2 || mapOf(conns[0])["name"] != "Local RO" || mapOf(conns[1])["name"] != "Local RW" { + t.Fatalf("connections: %v", conns) + } + if mapOf(conns[0])["access"] != "read" || mapOf(conns[1])["access"] != "write" { + t.Fatalf("access: %v", conns) + } + if mapOf(conns[0])["where"] != "ro.db" { + t.Fatalf("where: %v", conns) + } + if strings.Contains(textOf(list), "Hidden") { + t.Fatalf("hidden listed: %s", textOf(list)) + } + hidden := c.call("query", map[string]any{"connection": "Hidden", "sql": "select 1"}) + if !isErr(hidden) || !strings.Contains(textOf(hidden), "Unknown connection") { + t.Fatalf("hidden by name: %v", hidden) + } + if r := c.call("query", map[string]any{"connection": "p-off", "sql": "select 1"}); !isErr(r) { + t.Fatalf("hidden by id: %v", r) + } + + // Query, by name in any case. + q := c.call("query", map[string]any{"connection": "local ro", "sql": "SELECT id, name, bio FROM users ORDER BY id;"}) + if isErr(q) { + t.Fatal(textOf(q)) + } + s := structuredOf(q) + if s["rowCount"] != float64(3) || s["truncated"] != false { + t.Fatalf("structured: %v", s) + } + if mapOf(arr(s["columns"])[1])["name"] != "name" { + t.Fatalf("columns: %v", s) + } + if got := jsonText(arr(s["rows"])[1]); got != `["2","Bob","line1\nline2"]` { + t.Fatalf("row: %s", got) + } + if arr(arr(s["rows"])[0])[2] != nil { + t.Fatalf("NULL: %v", s["rows"]) + } + if !strings.Contains(textOf(q), `| 2 | Bob | line1\nline2 |`) { + t.Fatalf("text: %s", textOf(q)) + } + + q = c.call("query", map[string]any{"connection": "p-ro", "sql": "select * from users", "max_rows": 1}) + if structuredOf(q)["rowCount"] != float64(1) || structuredOf(q)["truncated"] != true { + t.Fatalf("max_rows: %v", q) + } + if !strings.Contains(textOf(q), "more rows exist") { + t.Fatalf("max_rows text: %s", textOf(q)) + } + + q = c.call("query", map[string]any{"connection": "p-ro", "sql": "select nope from users"}) + if !isErr(q) || !strings.Contains(textOf(q), "nope") { + t.Fatalf("bad column: %s", textOf(q)) + } + + // describe_table: columns always, foreign keys when the catalog has them. + d := c.call("describe_table", map[string]any{"connection": "p-ro", "table": "main.users"}) + if isErr(d) { + t.Fatal(textOf(d)) + } + s = structuredOf(d) + if s["table"] != "users" { + t.Fatalf("table: %v", s) + } + if got := jsonText(arr(s["columns"])[0]); got != `{"name":"id","nullable":true,"primaryKey":true,"type":"INTEGER"}` { + t.Fatalf("first column: %s", got) + } + if mapOf(arr(s["columns"])[1])["nullable"] != false { + t.Fatalf("nullable: %v", s) + } + _, fkErr := s["foreignKeysError"].(string) + if !fkErr && mapOf(arr(s["foreignKeys"])[0])["refTable"] != "teams" { + t.Fatalf("foreign keys: %v", s) + } + if d := c.call("describe_table", map[string]any{"connection": "p-ro", "table": "missing"}); !isErr(d) { + t.Fatalf("missing table: %v", d) + } + + // Read-only, classifier level. + for _, sql := range []string{ + "DELETE FROM users", + "WITH x AS (SELECT 1) INSERT INTO teams SELECT 2, 'x' FROM x", + "PRAGMA user_version = 7", + "select 1; delete from users", + } { + if r := c.call("query", map[string]any{"connection": "p-ro", "sql": sql}); !isErr(r) { + t.Fatalf("%s: %v", sql, r) + } + } + r := c.call("query", map[string]any{"connection": "p-ro", "sql": "update users set name = 'x'"}) + if !strings.Contains(textOf(r), "This connection is read-only for AI agents.") { + t.Fatalf("read-only text: %s", textOf(r)) + } + r = c.call("execute", map[string]any{"connection": "p-ro", "sql": "delete from users"}) + if !isErr(r) || !strings.Contains(textOf(r), "read-only for AI agents") { + t.Fatalf("execute on read: %s", textOf(r)) + } + + // Read-only, engine level: the agent session refuses writes that get + // past the classifier. + all, err := srv.agentProfiles() + if err != nil { + t.Fatal(err) + } + var profile model.ConnectionProfile + for _, p := range all { + if p.ID == "p-ro" { + profile = p + } + } + for _, sql := range []string{ + "DELETE FROM users", + "WITH x AS (SELECT 1) INSERT INTO teams SELECT 2, 'x' FROM x", + "PRAGMA user_version = 7", + "PRAGMA query_only = OFF", + } { + err := srv.run(profile, kindRead, newCancel(), func(ctx context.Context, s drivers.Session) error { + if _, err := execOn(ctx, s, sql); err != nil { + return err + } + _, err := execOn(ctx, s, "DELETE FROM users") + return err + }) + if err == nil { + t.Fatalf("%s: not refused", sql) + } + } + got := [3]string{ + scalarOf(t, roDB, "select count(*) from users"), + scalarOf(t, roDB, "select count(*) from teams"), + scalarOf(t, roDB, "pragma user_version"), + } + if got != [3]string{"3", "1", "0"} { + t.Fatalf("read-only file changed: %v", got) + } + + // Time limit: the query is interrupted and the session keeps working. + r = c.call("query", map[string]any{"connection": "p-ro", "sql": "with recursive c(x) as (select 1 union all select x + 1 from c) select count(*) from c"}) + if !isErr(r) || !strings.Contains(textOf(r), "longer than") { + t.Fatalf("time limit: %s", textOf(r)) + } + r = c.call("query", map[string]any{"connection": "p-ro", "sql": "select count(*) from users"}) + if showRows(rowsOf(r)) != "[3]" { + t.Fatalf("after the time limit: %v", r) + } + + // Write connection. + w := c.call("execute", map[string]any{"connection": "Local RW", "sql": "INSERT INTO users (name) VALUES ('Zed')"}) + if isErr(w) { + t.Fatal(textOf(w)) + } + if structuredOf(w)["rowsAffected"] != float64(1) { + t.Fatalf("rowsAffected: %v", w) + } + for _, sql := range []string{ + "BEGIN", + "insert into teams values (5, 'a'); insert into teams values (6, 'b')", + } { + if r := c.call("execute", map[string]any{"connection": "p-rw", "sql": sql}); !isErr(r) { + t.Fatalf("%s: %v", sql, r) + } + } + r = c.call("query", map[string]any{"connection": "p-rw", "sql": "delete from users"}) + if !isErr(r) || !strings.Contains(textOf(r), "use execute") { + t.Fatalf("query on write: %s", textOf(r)) + } + if n := scalarOf(t, rwDB, "select count(*) from users") + "/" + scalarOf(t, rwDB, "select count(*) from teams"); n != "4/1" { + t.Fatalf("write file: %s", n) + } + + // Activity log. + log, err := ReadRecent(dir, 100) + if err != nil { + t.Fatal(err) + } + for _, e := range log { + if e.Client != "test-client 1.0" { + t.Fatalf("client: %+v", e) + } + } + if log[0].Tool != "query" { + t.Fatalf("newest: %+v", log[0]) + } + find := func(detail string) *AuditEntry { + for i := range log { + if log[i].Detail != nil && *log[i].Detail == detail { + return &log[i] + } + } + t.Fatalf("no entry for %s", detail) + return nil + } + zed := find("INSERT INTO users (name) VALUES ('Zed')") + if !zed.OK || zed.Tool != "execute" || zed.Rows == nil || *zed.Rows != 1 { + t.Fatalf("zed: %+v", zed) + } + if zed.ConnectionName == nil || *zed.ConnectionName != "Local RW" { + t.Fatalf("zed name: %+v", zed) + } + if first := log[len(log)-1]; first.Tool != "list_connections" { + t.Fatalf("oldest: %+v", first) + } + if h := find("select 1"); h.OK || h.ConnectionID != nil { + t.Fatalf("hidden entry: %+v", h) + } + if refused := find("DELETE FROM users"); refused.OK || refused.Error == nil || !strings.Contains(*refused.Error, "read-only") { + t.Fatalf("refused entry: %+v", refused) + } +} + +// Calls on different connections run at the same time, and a cancelled +// call gets no response. +func TestConcurrentCallsAndCancel(t *testing.T) { + dir := t.TempDir() + a := filepath.Join(dir, "a.db") + b := filepath.Join(dir, "b.db") + makeDB(t, a) + makeDB(t, b) + writeProfiles(t, dir, + sqliteProfile("a", "A", a, accessRead), + sqliteProfile("b", "B", b, accessRead), + ) + c, _ := startClient(t, dir, 30*time.Second) + c.initialize("2025-11-25") + slow := `{"jsonrpc":"2.0","id":%d,"method":"tools/call","params":{"name":"query","arguments":{"connection":"%s","sql":"with recursive c(x) as (select 1 union all select x + 1 from c) select count(*) from c"}}}` + c.sendRaw(fmt.Sprintf(slow, 100, "a")) + started := time.Now() + r := c.call("query", map[string]any{"connection": "b", "sql": "select count(*) from users"}) + if showRows(rowsOf(r)) != "[3]" || time.Since(started) > 10*time.Second { + t.Fatalf("second connection waited: %v", r) + } + c.sendRaw(`{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":100,"reason":"test"}}`) + // The next reply is the ping's, not the cancelled call's. + pong := c.request("ping", map[string]any{}) + if pong["result"] == nil { + t.Fatalf("ping: %v", pong) + } + // The connection works again once the cancelled call has stopped. + r = c.call("query", map[string]any{"connection": "a", "sql": "select count(*) from users"}) + if showRows(rowsOf(r)) != "[3]" { + t.Fatalf("after cancel: %v", r) + } + log, _ := ReadRecent(dir, 100) + cancelled := false + for _, e := range log { + if e.Error != nil && strings.Contains(*e.Error, "The client cancelled the call.") { + cancelled = true + } + } + if !cancelled { + t.Fatalf("no log entry for the cancelled call: %+v", log) + } +} + +func TestReadOnlySqliteOpensTheFileReadOnly(t *testing.T) { + dir := t.TempDir() + db := filepath.Join(dir, "my db.sqlite") + makeDB(t, db) + profile := sqliteProfile("p", "p", db, accessRead) + ctx := context.Background() + s, err := openSqlite(ctx, profile, true) + if err != nil { + t.Fatal(err) + } + defer s.Close() + // Even with query_only turned off, the file itself refuses writes. + if _, err := execOn(ctx, s, "PRAGMA query_only = OFF"); err != nil { + t.Fatal(err) + } + _, err = execOn(ctx, s, "DELETE FROM users") + if err == nil || !strings.Contains(err.Error(), "readonly") { + t.Fatalf("delete on a read-only file: %v", err) + } +} + +func TestSqliteURIs(t *testing.T) { + cases := map[string]string{ + `C:\data\my db#1.sqlite`: "file:C:/data/my db%231.sqlite?mode=ro", + "/tmp/a?b.db": "file:///tmp/a%3fb.db?mode=ro", + "rel/x.db": "file:rel/x.db?mode=ro", + } + for in, want := range cases { + if got, ok := readOnlyURI(in); !ok || got != want { + t.Errorf("%s: %s", in, got) + } + } + for _, in := range []string{":memory:", "file:x.db?mode=rw", `\\server\share\x.db`, " "} { + if _, ok := readOnlyURI(in); ok { + t.Errorf("%s: got a URI", in) + } + } +} + +func TestTimeoutFromEnv(t *testing.T) { + t.Setenv("LOWQUERY_MCP_TIMEOUT", " 7 ") + if timeoutFromEnv() != 7*time.Second { + t.Fatal(timeoutFromEnv()) + } + for _, v := range []string{"", "0", "x", "-3"} { + t.Setenv("LOWQUERY_MCP_TIMEOUT", v) + if timeoutFromEnv() != defaultTimeout { + t.Fatalf("%q: %v", v, timeoutFromEnv()) + } + } +} + +func TestAuthFailures(t *testing.T) { + for _, code := range []string{"28P01", "ORA-01017", "1045 (28000)", "NOAUTH", "Msg 18456, Level 14, State 1"} { + if !isAuthFailure(&apperrError{Code: code}) { + t.Errorf("%s", code) + } + } + if !isAuthFailure(&apperrError{Message: "Password authentication failed"}) { + t.Error("message") + } + if isAuthFailure(&apperrError{Code: "42P01", Message: "relation does not exist"}) { + t.Error("not an auth failure") + } +} diff --git a/internal/mcp/tools.go b/internal/mcp/tools.go new file mode 100644 index 0000000..c243563 --- /dev/null +++ b/internal/mcp/tools.go @@ -0,0 +1,1099 @@ +package mcp + +// The tools agents call: definitions for tools/list and their handlers. + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "math" + "path/filepath" + "slices" + "strconv" + "strings" + "unicode/utf8" + + "github.com/LowBloat/LowQuery/internal/apperr" + "github.com/LowBloat/LowQuery/internal/drivers" + "github.com/LowBloat/LowQuery/internal/model" +) + +const readOnlyText = "This connection is read-only for AI agents. Ask the user to allow changes in LowQuery (connection → AI access)." + +const ( + defaultRows = 100 + maxRows = 1_000 + defaultMatches = 50 + maxMatches = 200 +) + +var toolNames = []string{ + "list_connections", + "list_schemas", + "list_tables", + "describe_table", + "search_objects", + "query", + "explain", + "execute", +} + +func toolExists(name string) bool { return slices.Contains(toolNames, name) } + +// --------------------------------------------------------------------------- +// Definitions + +func connectionProp() obj { + return obj{{"type", "string"}, {"description", "Connection id or name, from list_connections."}} +} + +func object(properties obj, required ...string) obj { + return obj{{"type", "object"}, {"properties", properties}, {"required", required}, {"additionalProperties", false}} +} + +func str() obj { return obj{{"type", "string"}} } + +func nullable(t string) obj { return obj{{"type", []string{t, "null"}}} } + +func resultSchema() obj { + return obj{ + {"type", "object"}, + {"properties", obj{ + {"columns", obj{ + {"type", "array"}, + {"items", obj{ + {"type", "object"}, + {"properties", obj{{"name", str()}, {"type", str()}}}, + {"required", []string{"name", "type"}}, + }}, + }}, + {"rows", obj{ + {"type", "array"}, + {"description", "Values as text, null for NULL; long values are cut."}, + {"items", obj{{"type", "array"}, {"items", nullable("string")}}}, + }}, + {"rowCount", obj{{"type", "integer"}, {"description", "Rows in this result."}}}, + {"truncated", obj{{"type", "boolean"}, {"description", "More rows exist than are shown."}}}, + {"elapsedMs", obj{{"type", "integer"}}}, + {"rowsAffected", nullable("integer")}, + {"notices", obj{{"type", "array"}, {"items", str()}}}, + }}, + {"required", []string{"columns", "rows", "rowCount", "truncated", "elapsedMs"}}, + } +} + +func toolDef(name, title, description string, input, output obj) obj { + write := name == "execute" + return obj{ + {"name", name}, + {"title", title}, + {"description", description}, + {"inputSchema", input}, + {"outputSchema", output}, + {"annotations", obj{ + {"title", title}, + {"readOnlyHint", !write}, + {"destructiveHint", write}, + {"idempotentHint", !write}, + {"openWorldHint", false}, + }}, + } +} + +func maxRowsProp() obj { + return obj{{"type", "integer"}, {"minimum", 1}, {"maximum", maxRows}, {"default", defaultRows}} +} + +// toolList is the tools/list result for the negotiated revision: title and +// outputSchema came in 2025-06-18, annotations in 2025-03-26. +func toolList(version string) obj { + tools := []obj{ + toolDef( + "list_connections", + "List connections", + "Lists the database connections the user opened to AI agents: id, name, engine, where it points (never passwords), access (read or write) and notes on the SQL dialect. Call this first.", + obj{{"type", "object"}, {"additionalProperties", false}}, + obj{ + {"type", "object"}, + {"properties", obj{{"connections", obj{{"type", "array"}, {"items", obj{ + {"type", "object"}, + {"properties", obj{ + {"id", str()}, {"name", str()}, + {"engine", str()}, {"where", str()}, + {"access", obj{{"type", "string"}, {"enum", []string{"read", "write"}}}}, + {"dialect", str()}, + }}, + {"required", []string{"id", "name", "engine", "where", "access", "dialect"}}, + }}}}}}, + {"required", []string{"connections"}}, + }, + ), + toolDef( + "list_schemas", + "List schemas", + "Lists the schemas (databases on MySQL, attached databases on SQLite, keyspaces on Cassandra, db0... on Redis) of a connection, and the current one.", + object(obj{{"connection", connectionProp()}}, "connection"), + obj{ + {"type", "object"}, + {"properties", obj{ + {"schemas", obj{{"type", "array"}, {"items", str()}}}, + {"current", nullable("string")}, + }}, + {"required", []string{"schemas"}}, + }, + ), + toolDef( + "list_tables", + "List tables", + "Lists the tables, views and other objects of a schema (default: the current schema) with their kind. For large schemas prefer search_objects.", + object(obj{ + {"connection", connectionProp()}, + {"schema", obj{{"type", "string"}, {"description", "Schema to list; default: the current schema."}}}, + }, "connection"), + obj{ + {"type", "object"}, + {"properties", obj{ + {"schema", str()}, + {"tables", obj{{"type", "array"}, {"items", obj{ + {"type", "object"}, + {"properties", obj{{"name", str()}, {"kind", str()}}}, + {"required", []string{"name", "kind"}}, + }}}}, + {"truncated", obj{{"type", "boolean"}}}, + }}, + {"required", []string{"schema", "tables"}}, + }, + ), + toolDef( + "describe_table", + "Describe table", + "Columns of a table or view (name, type, nullable, primary key; on Cassandra the key role: partition, clustering, static or regular) and its foreign keys, both outgoing and those referencing it. Read this before writing SQL against a table.", + object(obj{ + {"connection", connectionProp()}, + {"table", obj{{"type", "string"}, {"description", "Table or view name; schema.table also works."}}}, + {"schema", obj{{"type", "string"}, {"description", "Default: the current schema."}}}, + }, "connection", "table"), + obj{ + {"type", "object"}, + {"properties", obj{ + {"schema", str()}, + {"table", str()}, + {"columns", obj{{"type", "array"}, {"items", obj{ + {"type", "object"}, + {"properties", obj{ + {"name", str()}, {"type", str()}, + {"nullable", obj{{"type", "boolean"}}}, {"primaryKey", obj{{"type", "boolean"}}}, + {"keyRole", nullable("string")}, + }}, + {"required", []string{"name", "type", "nullable", "primaryKey"}}, + }}}}, + {"foreignKeys", obj{{"type", "array"}, {"items", obj{{"type", "object"}}}}}, + {"referencedBy", obj{{"type", "array"}, {"items", obj{{"type", "object"}}}}}, + {"foreignKeysError", str()}, + }}, + {"required", []string{"schema", "table", "columns"}}, + }, + ), + toolDef( + "search_objects", + "Search objects", + "Finds tables, views and columns whose name contains the pattern (case-insensitive) across the schemas of a connection (on Cassandra: tables, materialized views, columns and user-defined types of every keyspace); exact and prefix matches first. On Redis, finds keys.", + object(obj{ + {"connection", connectionProp()}, + {"pattern", obj{{"type", "string"}, {"description", "Part of a table or column name."}}}, + {"limit", obj{{"type", "integer"}, {"minimum", 1}, {"maximum", maxMatches}, {"default", defaultMatches}}}, + }, "connection", "pattern"), + obj{ + {"type", "object"}, + {"properties", obj{{"matches", obj{{"type", "array"}, {"items", obj{ + {"type", "object"}, + {"properties", obj{ + {"schema", nullable("string")}, {"table", str()}, + {"kind", str()}, {"column", nullable("string")}, + {"columnType", nullable("string")}, + }}, + {"required", []string{"table", "kind"}}, + }}}}}}, + {"required", []string{"matches"}}, + }, + ), + toolDef( + "query", + "Run a query", + "Runs ONE read statement (SELECT, WITH, SHOW, DESCRIBE, EXPLAIN without ANALYZE, VALUES, TABLE, reading PRAGMAs; on Cassandra SELECT and LIST; on Redis one read command) in the connection's dialect (CQL on Cassandra) and returns the rows as a table. Rows are capped at max_rows; select only the columns you need and filter in SQL.", + object(obj{ + {"connection", connectionProp()}, + {"sql", obj{{"type", "string"}, {"description", "One read statement; a trailing ; is fine."}}}, + {"max_rows", maxRowsProp()}, + }, "connection", "sql"), + resultSchema(), + ), + toolDef( + "explain", + "Explain a statement", + "Shows the engine's execution plan for one statement without running it. Pass the statement itself, not EXPLAIN ...", + object(obj{ + {"connection", connectionProp()}, + {"sql", obj{{"type", "string"}, {"description", "The statement to explain."}}}, + }, "connection", "sql"), + obj{{"type", "object"}, {"properties", obj{{"plan", str()}}}, {"required", []string{"plan"}}}, + ), + toolDef( + "execute", + "Execute a change", + "Runs ONE statement of any kind (INSERT, UPDATE, DELETE, DDL, a procedure call, a CQL BEGIN BATCH ... APPLY BATCH; on Redis one command) on a connection with write access, and commits it. Use only when the user asked for the change. Returns rows affected, notices and any rows. Transaction control (BEGIN, COMMIT...) is refused: each call commits on its own.", + object(obj{ + {"connection", connectionProp()}, + {"sql", obj{{"type", "string"}, {"description", "One statement."}}}, + {"max_rows", maxRowsProp()}, + }, "connection", "sql"), + resultSchema(), + ), + } + for i, t := range tools { + if version < "2025-06-18" { + t = t.without("title", "outputSchema") + } + if version < "2025-03-26" { + t = t.without("annotations") + } + tools[i] = t + } + return obj{{"tools", tools}} +} + +// --------------------------------------------------------------------------- +// Arguments + +// strArg is a string argument; nil when it is missing, null or blank. +func strArg(args map[string]any, key string) (*string, error) { + switch v := args[key].(type) { + case nil: + return nil, nil + case string: + if strings.TrimSpace(v) == "" { + return nil, nil + } + return &v, nil + } + return nil, fmt.Errorf("Argument %s must be a string.", key) +} + +func requiredArg(args map[string]any, key string) (string, error) { + v, err := strArg(args, key) + if err != nil { + return "", err + } + if v == nil { + return "", fmt.Errorf("Missing argument: %s.", key) + } + return *v, nil +} + +// intArg is an integer argument (a numeric string also works), clamped to +// 1..max. +func intArg(args map[string]any, key string, def, limit uint64) (uint64, error) { + var n uint64 + ok := false + switch v := args[key].(type) { + case nil: + return def, nil + case json.Number: + if u, err := strconv.ParseUint(string(v), 10, 64); err == nil { + n, ok = u, true + } else if f, err := strconv.ParseFloat(string(v), 64); err == nil { + n, ok = floatToUint(f), true + } + case float64: + n, ok = floatToUint(v), true + case string: + if u, err := strconv.ParseUint(strings.TrimSpace(v), 10, 64); err == nil { + n, ok = u, true + } + } + if !ok { + return 0, fmt.Errorf("Argument %s must be a positive integer.", key) + } + return min(max(n, 1), limit), nil +} + +// floatToUint converts as Rust's `f.max(0.0) as u64`: saturating, NaN is 0. +func floatToUint(f float64) uint64 { + switch { + case math.IsNaN(f) || f <= 0: + return 0 + case f >= math.MaxUint64: + return math.MaxUint64 + } + return uint64(f) +} + +// --------------------------------------------------------------------------- +// Connections + +func engineLabel(engine model.Engine) string { + switch engine { + case model.Postgres: + return "PostgreSQL" + case model.Oracle: + return "Oracle" + case model.MySQL: + return "MySQL" + case model.MariaDB: + return "MariaDB" + case model.SQLServer: + return "SQL Server" + case model.SQLite: + return "SQLite" + case model.Redis: + return "Redis" + case model.Cassandra: + return "Cassandra" + } + return string(engine) +} + +func dialectNotes(engine model.Engine) string { + switch engine { + case model.Postgres: + return "PostgreSQL: LIMIT n; double-quote mixed-case names; ILIKE for case-insensitive matches; schema.table names." + case model.Oracle: + return "Oracle: use FETCH FIRST n ROWS ONLY (no LIMIT); unquoted names are stored uppercase; FROM dual for expressions; DATE 'YYYY-MM-DD' literals; no trailing ; needed." + case model.MySQL: + return "MySQL: LIMIT n; backtick-quote names; databases are the schemas." + case model.MariaDB: + return "MariaDB: LIMIT n; backtick-quote names; databases are the schemas." + case model.SQLServer: + return "SQL Server (T-SQL): SELECT TOP (n) or ORDER BY ... OFFSET 0 ROWS FETCH NEXT n ROWS ONLY; [bracket] names; schema.table names (dbo.x)." + case model.SQLite: + return "SQLite: LIMIT n; flexible column types; schemas are attached databases (main)." + case model.Cassandra: + return "Cassandra (CQL): no joins or subqueries; filter on the partition key (other columns need an index or ALLOW FILTERING); LIMIT n; keyspaces are the schemas (write keyspace.table); names are lowercase unless double-quoted; text literals use single quotes." + case model.Redis: + return "Redis: not SQL; pass one redis-cli command, such as GET key, HGETALL key or SCAN 0 MATCH user:* COUNT 100 (KEYS is refused)." + } + return "" +} + +func withPort(host string, port uint16) string { + if port == 0 { + return strings.TrimSpace(host) + } + return fmt.Sprintf("%s:%d", strings.TrimSpace(host), port) +} + +// fileName is the last element of a path, as Rust's Path::file_name. +func fileName(path string) (string, bool) { + trimmed := strings.TrimRight(path, `/`+string(filepath.Separator)) + if trimmed == "" { + return "", false + } + base := filepath.Base(trimmed) + if base == "." || base == ".." || base == string(filepath.Separator) || strings.HasSuffix(base, ":") { + return "", false + } + return base, true +} + +// location says where the connection points, without secrets. +func location(p model.ConnectionProfile) string { + user := strings.TrimSpace(p.User) + at := func(rest string) string { + if user == "" { + return rest + } + return user + "@" + rest + } + db := strings.TrimSpace(p.Database) + switch p.Engine { + case model.SQLite: + if name, ok := fileName(db); ok { + return name + } + return db + case model.Oracle: + switch p.OracleConnectType { + case model.OracleTNS: + return at(strings.TrimSpace(p.TnsAlias)) + case model.OracleCustom: + return at("(custom connect descriptor)") + } + return at(withPort(p.Host, p.Port) + "/" + db) + case model.SQLServer: + host := strings.TrimSpace(p.Host) + if instance := strings.TrimSpace(p.Instance); instance != "" { + host = host + `\` + instance + } else if p.Port != 0 { + host = withPort(host, p.Port) + } + target := host + "/" + db + if p.WindowsAuth { + return "Windows account@" + target + } + return at(target) + case model.Redis: + n := db + if n == "" { + n = "0" + } + return at(withPort(p.Host, p.Port) + "/db" + n) + case model.Cassandra: + if db == "" { + return at(withPort(p.Host, p.Port)) + } + } + return at(withPort(p.Host, p.Port) + "/" + db) +} + +func accessLabel(p model.ConnectionProfile) string { + if p.AiAccess == accessWrite { + return "write" + } + return "read" +} + +// keyLabel is the key cell of describe_table: PK, and on Cassandra the role +// of the column in the key. +func keyLabel(c model.DbColumn) string { + role := "" + if c.KeyRole != nil { + role = *c.KeyRole + } + switch { + case role == "partition": + return "PK (partition)" + case role == "clustering": + return "PK (clustering)" + case role == "static": + return "static" + case c.PrimaryKey: + return "PK" + } + return "" +} + +// resolve finds a connection by id or by name (case-insensitive). +func resolve(s *server, key string, info *callInfo) (model.ConnectionProfile, error) { + all, err := s.agentProfiles() + if err != nil { + return model.ConnectionProfile{}, err + } + key = strings.TrimSpace(key) + var found *model.ConnectionProfile + for i := range all { + if equalFoldASCII(all[i].ID, key) { + found = &all[i] + break + } + } + if found == nil { + lower := strings.ToLower(key) + named := []model.ConnectionProfile{} + for _, p := range all { + if strings.ToLower(strings.TrimSpace(p.Name)) == lower { + named = append(named, p) + } + } + switch len(named) { + case 0: + return model.ConnectionProfile{}, fmt.Errorf("Unknown connection: %s. Use list_connections to see the connections open to agents.", key) + case 1: + found = &named[0] + default: + ids := make([]string, len(named)) + for i, p := range named { + ids[i] = fmt.Sprintf("%s (%s, %s)", p.ID, engineLabel(p.Engine), location(p)) + } + return model.ConnectionProfile{}, fmt.Errorf("Several connections are named %s; pass one of these ids instead: %s.", key, strings.Join(ids, "; ")) + } + } + info.connectionID = model.Str(found.ID) + info.connectionName = model.Str(found.Name) + return *found, nil +} + +// toolError is the text of a failed call. +type toolError string + +func (e toolError) Error() string { return string(e) } + +func dbError(err error, sql *string) error { + return toolError(errorText(err, sql)) +} + +// --------------------------------------------------------------------------- +// Handlers + +func runTool(s *server, name string, args map[string]any, c *callCancel, info *callInfo) *reply { + var r *reply + var err error + switch name { + case "list_connections": + r, err = listConnections(s) + case "list_schemas": + r, err = listSchemas(s, args, c, info) + case "list_tables": + r, err = listTables(s, args, c, info) + case "describe_table": + r, err = describeTable(s, args, c, info) + case "search_objects": + r, err = searchObjects(s, args, c, info) + case "query": + r, err = queryTool(s, args, c, info) + case "explain": + r, err = explainTool(s, args, c, info) + case "execute": + r, err = executeTool(s, args, c, info) + default: + err = fmt.Errorf("Unknown tool: %s", name) + } + if err != nil { + return errReply(err.Error()) + } + return r +} + +func listConnections(s *server) (*reply, error) { + all, err := s.agentProfiles() + if err != nil { + return nil, err + } + if len(all) == 0 { + return okReply( + "No connections are open to AI agents. Ask the user to turn on AI access for a connection in LowQuery (connection → AI access).", + obj{{"connections", []obj{}}}, + ).withRows(0), nil + } + var text strings.Builder + items := []obj{} + for _, p := range all { + items = append(items, obj{ + {"id", p.ID}, + {"name", p.Name}, + {"engine", engineLabel(p.Engine)}, + {"where", location(p)}, + {"access", accessLabel(p)}, + {"dialect", dialectNotes(p.Engine)}, + }) + fmt.Fprintf(&text, "- %s (id %s): %s, %s, %s access. %s\n", + p.Name, p.ID, engineLabel(p.Engine), location(p), accessLabel(p), dialectNotes(p.Engine)) + } + return okReply(text.String(), obj{{"connections", items}}).withRows(len(all)), nil +} + +func listSchemas(s *server, args map[string]any, c *callCancel, info *callInfo) (*reply, error) { + key, err := requiredArg(args, "connection") + if err != nil { + return nil, err + } + p, err := resolve(s, key, info) + if err != nil { + return nil, err + } + var schemas []string + var current *string + err = s.run(p, kindRead, c, func(ctx context.Context, session drivers.Session) error { + var err error + if schemas, err = session.ListSchemas(ctx); err != nil { + return err + } + current = session.CurrentSchema() + return nil + }) + if err != nil { + return nil, dbError(err, nil) + } + if schemas == nil { + schemas = []string{} + } + var text strings.Builder + fmt.Fprintf(&text, "%s in %s:\n", plural(len(schemas), "schema"), p.Name) + for _, sc := range schemas { + fmt.Fprintf(&text, "- %s\n", sc) + } + if current != nil { + fmt.Fprintf(&text, "Current schema: %s\n", *current) + } + return okReply(text.String(), obj{{"schemas", schemas}, {"current", current}}).withRows(len(schemas)), nil +} + +func noCurrentSchema() error { + return apperr.New(apperr.Invalid, "This connection has no current schema; pass schema (see list_schemas).") +} + +func listTables(s *server, args map[string]any, c *callCancel, info *callInfo) (*reply, error) { + key, err := requiredArg(args, "connection") + if err != nil { + return nil, err + } + p, err := resolve(s, key, info) + if err != nil { + return nil, err + } + schemaArg, err := strArg(args, "schema") + if err != nil { + return nil, err + } + info.detail = schemaArg + var schema string + var objects []model.DbObject + err = s.run(p, kindRead, c, func(ctx context.Context, session drivers.Session) error { + switch { + case schemaArg != nil: + schema = strings.TrimSpace(*schemaArg) + case session.CurrentSchema() != nil: + schema = *session.CurrentSchema() + default: + return noCurrentSchema() + } + var err error + objects, err = session.ListObjects(ctx, schema) + return err + }) + if err != nil { + return nil, dbError(err, nil) + } + var text strings.Builder + fmt.Fprintf(&text, "%s in %s:\n", plural(len(objects), "object"), schema) + kept := []obj{} + for _, o := range objects { + line := fmt.Sprintf("- %s (%s)\n", o.Name, o.Kind) + if text.Len()+len(line) > textCap-200 { + break + } + text.WriteString(line) + kept = append(kept, obj{{"name", o.Name}, {"kind", o.Kind}}) + } + omitted := len(objects) - len(kept) + if omitted > 0 { + fmt.Fprintf(&text, "%s not shown; use search_objects to find the ones you need.\n", plural(omitted, "more object")) + } + return okReply(text.String(), obj{{"schema", schema}, {"tables", kept}, {"truncated", omitted > 0}}).withRows(len(kept)), nil +} + +func describeTable(s *server, args map[string]any, c *callCancel, info *callInfo) (*reply, error) { + key, err := requiredArg(args, "connection") + if err != nil { + return nil, err + } + p, err := resolve(s, key, info) + if err != nil { + return nil, err + } + table, err := requiredArg(args, "table") + if err != nil { + return nil, err + } + table = strings.TrimSpace(table) + schemaArg, err := strArg(args, "schema") + if err != nil { + return nil, err + } + if schemaArg != nil { + trimmed := strings.TrimSpace(*schemaArg) + schemaArg = &trimmed + } else if sc, t, ok := strings.Cut(table, "."); ok && !strings.Contains(t, ".") && sc != "" && t != "" { + schemaArg = &sc + table = t + } + if schemaArg != nil { + info.detail = model.Str(*schemaArg + "." + table) + } else { + info.detail = model.Str(table) + } + if p.Engine == model.Redis { + return nil, errors.New("Redis keys have no columns. Use query with TYPE key, then GET, HGETALL, LRANGE, SMEMBERS or ZRANGE to read it.") + } + var ( + schema, name string + columns []model.DbColumn + outgoing []foreignKey + incoming []incomingKey + fkErr error + ) + err = s.run(p, kindRead, c, func(ctx context.Context, session drivers.Session) error { + switch { + case schemaArg != nil: + schema = *schemaArg + case session.CurrentSchema() != nil: + schema = *session.CurrentSchema() + default: + return noCurrentSchema() + } + name = table + var err error + if columns, err = session.ListColumns(ctx, schema, name); err != nil { + return err + } + if len(columns) == 0 { + // employees for EMPLOYEES on Oracle, and similar. + if objects, err := session.ListObjects(ctx, schema); err == nil { + for _, o := range objects { + if equalFoldASCII(o.Name, table) { + name = o.Name + if columns, err = session.ListColumns(ctx, schema, name); err != nil { + return err + } + break + } + } + } + } + if len(columns) == 0 { + return apperr.Newf(apperr.NotFound, "Table %s.%s was not found (or has no columns). Use list_tables or search_objects.", schema, table) + } + outgoing, incoming, fkErr = foreignKeys(ctx, session, &schema, name) + return nil + }) + if err != nil { + return nil, dbError(err, nil) + } + + var text strings.Builder + fmt.Fprintf(&text, "Table %s.%s (%s):\n| column | type | nullable | key |\n| --- | --- | --- | --- |\n", + schema, name, plural(len(columns), "column")) + cols := []obj{} + for _, col := range columns { + nullableText := "no" + if col.Nullable { + nullableText = "yes" + } + fmt.Fprintf(&text, "| %s | %s | %s | %s |\n", col.Name, col.TypeName, nullableText, keyLabel(col)) + item := obj{ + {"name", col.Name}, + {"type", col.TypeName}, + {"nullable", col.Nullable}, + {"primaryKey", col.PrimaryKey}, + } + if col.KeyRole != nil { + item.set("keyRole", *col.KeyRole) + } + cols = append(cols, item) + } + structured := obj{{"schema", schema}, {"table", name}, {"columns", cols}} + if fkErr == nil { + if len(outgoing) > 0 { + text.WriteString("Foreign keys:\n") + } + for _, fk := range outgoing { + target := fk.RefTable + if fk.RefSchema != nil { + target = *fk.RefSchema + "." + fk.RefTable + } + named := "" + if fk.Name != nil { + named = *fk.Name + ": " + } + fmt.Fprintf(&text, "- %s(%s) → %s(%s)\n", named, strings.Join(fk.Columns, ", "), target, strings.Join(fk.RefColumns, ", ")) + } + if len(incoming) > 0 { + text.WriteString("Referenced by:\n") + } + by := []obj{} + for _, in := range incoming { + source := in.Table + if in.Schema != nil { + source = *in.Schema + "." + in.Table + } + named := "" + if in.Key.Name != nil { + named = " [" + *in.Key.Name + "]" + } + fmt.Fprintf(&text, "- %s(%s) → (%s)%s\n", source, strings.Join(in.Key.Columns, ", "), strings.Join(in.Key.RefColumns, ", "), named) + by = append(by, obj{ + {"schema", in.Schema}, {"table", in.Table}, {"name", in.Key.Name}, + {"columns", in.Key.Columns}, {"refColumns", in.Key.RefColumns}, + }) + } + if outgoing == nil { + outgoing = []foreignKey{} + } + structured.set("foreignKeys", outgoing) + structured.set("referencedBy", by) + } else { + message := apperr.From(fkErr).Message + fmt.Fprintf(&text, "Foreign keys unavailable: %s\n", message) + structured.set("foreignKeysError", message) + } + return okReply(text.String(), structured).withRows(len(columns)), nil +} + +func searchObjects(s *server, args map[string]any, c *callCancel, info *callInfo) (*reply, error) { + key, err := requiredArg(args, "connection") + if err != nil { + return nil, err + } + p, err := resolve(s, key, info) + if err != nil { + return nil, err + } + pattern, err := requiredArg(args, "pattern") + if err != nil { + return nil, err + } + limit, err := intArg(args, "limit", defaultMatches, maxMatches) + if err != nil { + return nil, err + } + info.detail = model.Str(pattern) + var matches []objectMatch + err = s.run(p, kindRead, c, func(ctx context.Context, session drivers.Session) error { + var err error + matches, err = search(ctx, session, pattern, int(limit)) + return err + }) + if err != nil { + return nil, dbError(err, nil) + } + if matches == nil { + matches = []objectMatch{} + } + var text strings.Builder + fmt.Fprintf(&text, "%s for \"%s\":\n", plural(len(matches), "match"), pattern) + for _, m := range matches { + table := m.Table + if m.Schema != nil { + table = *m.Schema + "." + m.Table + } + if m.Column != nil { + ty := "" + if m.ColumnType != nil { + ty = " " + *m.ColumnType + } + fmt.Fprintf(&text, "- column %s.%s%s (%s)\n", table, *m.Column, ty, m.Kind) + } else { + fmt.Fprintf(&text, "- %s (%s)\n", table, m.Kind) + } + } + if len(matches) >= int(limit) { + text.WriteString("More may exist; use a longer pattern or raise limit.\n") + } + return okReply(text.String(), obj{{"matches", matches}}).withRows(len(matches)), nil +} + +// checkedSQL is the text to send after the checks of query (read) or +// execute. +func checkedSQL(p model.ConnectionProfile, sql string, write bool) (string, error) { + refusal := func(why error) error { + switch { + case write: + return why + case p.AiAccess == accessRead: + return fmt.Errorf("%s %s", why, readOnlyText) + } + return fmt.Errorf("%s query runs read statements only; use execute for changes.", why) + } + if p.Engine == model.Redis { + if err := checkRedis(sql, write); err != nil { + return "", refusal(err) + } + return strings.TrimSpace(sql), nil + } + stmt, err := oneStatement(sql, p.Engine) + if err != nil { + return "", err + } + if write { + if err := checkWrite(stmt, p.Engine); err != nil { + return "", err + } + } else if err := checkRead(stmt, p.Engine); err != nil { + return "", refusal(err) + } + return stmt.sql, nil +} + +func render(res *model.ExecResult, maxRowsArg int, write bool) *reply { + var text strings.Builder + structured := obj{} + count := 0 + if res.RowsAffected != nil { + count = int(*res.RowsAffected) + } + if res.Columns != nil { + table, kept := table(res.Columns, res.Rows, textCap-2_000) + text.WriteString(table) + omitted := len(res.Rows) - len(kept) + shown := len(kept) + switch { + case omitted > 0: + fmt.Fprintf(&text, "Showing %d of %s fetched; %s omitted to keep the reply short. Narrow the query (fewer columns, a WHERE clause) to see the rest.\n", + shown, plural(len(res.Rows), "row"), plural(omitted, "row")) + case res.Truncated: + fmt.Fprintf(&text, "%s shown; more rows exist (max_rows %d). Narrow the query, aggregate, or raise max_rows (at most %d).\n", + plural(shown, "row"), maxRowsArg, maxRows) + default: + fmt.Fprintf(&text, "%s (%d ms).\n", plural(shown, "row"), res.ElapsedMs) + } + if !write || res.RowsAffected == nil { + count = shown + } + columns := make([]obj, len(res.Columns)) + for i, col := range res.Columns { + columns[i] = obj{{"name", col.Name}, {"type", col.TypeName}} + } + structured.set("columns", columns) + structured.set("rowCount", shown) + structured.set("truncated", res.Truncated || omitted > 0) + structured.set("rows", kept) + } else { + if res.RowsAffected != nil { + fmt.Fprintf(&text, "%s affected (%d ms).\n", plural(int(*res.RowsAffected), "row"), res.ElapsedMs) + } else { + fmt.Fprintf(&text, "Done (%d ms).\n", res.ElapsedMs) + } + structured.set("columns", []obj{}) + structured.set("rows", [][]*string{}) + structured.set("rowCount", 0) + structured.set("truncated", false) + } + if res.RowsAffected != nil && res.Columns != nil { + fmt.Fprintf(&text, "%s affected.\n", plural(int(*res.RowsAffected), "row")) + } + notices := make([]string, len(res.Notices)) + if len(res.Notices) > 0 { + text.WriteString("Notices:\n") + for i, n := range res.Notices { + notices[i] = cutValue(n) + fmt.Fprintf(&text, "- %s\n", notices[i]) + } + } + structured.set("elapsedMs", res.ElapsedMs) + if write { + structured.set("rowsAffected", res.RowsAffected) + } + structured.set("notices", notices) + return okReply(text.String(), structured).withRows(count) +} + +func queryTool(s *server, args map[string]any, c *callCancel, info *callInfo) (*reply, error) { + sql, err := requiredArg(args, "sql") + if err != nil { + return nil, err + } + info.detail = model.Str(sql) + key, err := requiredArg(args, "connection") + if err != nil { + return nil, err + } + p, err := resolve(s, key, info) + if err != nil { + return nil, err + } + limit, err := intArg(args, "max_rows", defaultRows, maxRows) + if err != nil { + return nil, err + } + send, err := checkedSQL(p, sql, false) + if err != nil { + return nil, err + } + var res *model.ExecResult + err = s.run(p, kindRead, c, func(ctx context.Context, session drivers.Session) error { + var err error + res, err = session.Execute(ctx, model.ExecRequest{SQL: send, MaxRows: int(limit)}) + return err + }) + if err != nil { + return nil, dbError(err, &send) + } + return render(res, int(limit), false), nil +} + +func explainTool(s *server, args map[string]any, c *callCancel, info *callInfo) (*reply, error) { + sql, err := requiredArg(args, "sql") + if err != nil { + return nil, err + } + info.detail = model.Str(sql) + key, err := requiredArg(args, "connection") + if err != nil { + return nil, err + } + p, err := resolve(s, key, info) + if err != nil { + return nil, err + } + var send string + if p.Engine == model.Redis { + send = strings.TrimSpace(sql) + } else { + stmt, err := oneStatement(sql, p.Engine) + if err != nil { + return nil, err + } + if err := checkExplain(stmt); err != nil { + return nil, err + } + send = stmt.sql + } + var plan string + err = s.run(p, kindExplain, c, func(ctx context.Context, session drivers.Session) error { + var err error + plan, err = explainPlan(ctx, session, send) + return err + }) + if err != nil { + text := errorText(err, &send) + if p.Engine == model.Oracle && strings.Contains(send, ":") { + text += "\nIf the statement has :name placeholders, write literal values in their place for explain." + } + return nil, toolError(text) + } + text := plan + if len(text) > textCap { + text = fmt.Sprintf("%s\n… (plan cut; %d chars in all)", firstChars(plan, textCap), utf8.RuneCountInString(plan)) + } + return okReply(text, obj{{"plan", text}}).withRows(countLines(plan)), nil +} + +// countLines counts lines as Rust's str::lines: a final newline does not +// start another line. +func countLines(s string) int { + if s == "" { + return 0 + } + n := strings.Count(s, "\n") + if !strings.HasSuffix(s, "\n") { + n++ + } + return n +} + +func executeTool(s *server, args map[string]any, c *callCancel, info *callInfo) (*reply, error) { + sql, err := requiredArg(args, "sql") + if err != nil { + return nil, err + } + info.detail = model.Str(sql) + key, err := requiredArg(args, "connection") + if err != nil { + return nil, err + } + p, err := resolve(s, key, info) + if err != nil { + return nil, err + } + if p.AiAccess != accessWrite { + return nil, fmt.Errorf("%s Use query for read statements.", readOnlyText) + } + limit, err := intArg(args, "max_rows", defaultRows, maxRows) + if err != nil { + return nil, err + } + send, err := checkedSQL(p, sql, true) + if err != nil { + return nil, err + } + var res *model.ExecResult + err = s.run(p, kindWrite, c, func(ctx context.Context, session drivers.Session) error { + var err error + res, err = session.Execute(ctx, model.ExecRequest{SQL: send, MaxRows: int(limit)}) + return err + }) + if err != nil { + return nil, dbError(err, &send) + } + return render(res, int(limit), true), nil +} diff --git a/internal/mcp/tools_test.go b/internal/mcp/tools_test.go new file mode 100644 index 0000000..6e4536a --- /dev/null +++ b/internal/mcp/tools_test.go @@ -0,0 +1,196 @@ +package mcp + +import ( + "encoding/json" + "runtime" + "strings" + "testing" + + "github.com/LowBloat/LowQuery/internal/model" +) + +func profileOf(engine model.Engine) model.ConnectionProfile { + p := model.DefaultProfile() + p.ID = "x" + p.Name = "X" + p.Engine = engine + p.Host = "db.local" + p.Port = 5432 + p.Database = "app" + p.User = "ann" + return p +} + +func TestLocationsNeverHoldSecrets(t *testing.T) { + if got := location(profileOf(model.Postgres)); got != "ann@db.local:5432/app" { + t.Error(got) + } + lite := profileOf(model.SQLite) + lite.Database = `C:\data\shop.db` + if runtime.GOOS == "windows" { + if got := location(lite); got != "shop.db" { + t.Error(got) + } + } + lite.Database = "/data/shop.db" + if got := location(lite); got != "shop.db" { + t.Error(got) + } + ora := profileOf(model.Oracle) + ora.OracleConnectType = model.OracleTNS + ora.TnsAlias = "PROD" + if got := location(ora); got != "ann@PROD" { + t.Error(got) + } + ms := profileOf(model.SQLServer) + ms.Instance = "SQLEXPRESS" + ms.WindowsAuth = true + if got := location(ms); got != `Windows account@db.local\SQLEXPRESS/app` { + t.Error(got) + } + cass := profileOf(model.Cassandra) + cass.Port = 9042 + if got := location(cass); got != "ann@db.local:9042/app" { + t.Error(got) + } + cass.Database = "" + if got := location(cass); got != "ann@db.local:9042" { + t.Error(got) + } + redis := profileOf(model.Redis) + redis.Database = "" + redis.Port = 6379 + if got := location(redis); got != "ann@db.local:6379/db0" { + t.Error(got) + } + if engineLabel(model.Cassandra) != "Cassandra" { + t.Error(engineLabel(model.Cassandra)) + } + if !strings.Contains(dialectNotes(model.Cassandra), "ALLOW FILTERING") { + t.Error(dialectNotes(model.Cassandra)) + } +} + +func TestIntegerArgumentsAreClamped(t *testing.T) { + var args map[string]any + dec := json.NewDecoder(strings.NewReader(`{"a": 5000, "b": "20", "c": "x", "d": 0, "e": -5, "f": 2.7, "g": true}`)) + dec.UseNumber() + if err := dec.Decode(&args); err != nil { + t.Fatal(err) + } + check := func(key string, want uint64) { + t.Helper() + if got, err := intArg(args, key, 100, 1000); err != nil || got != want { + t.Errorf("%s: %d %v", key, got, err) + } + } + check("a", 1000) + check("b", 20) + check("d", 1) + check("e", 1) + check("f", 2) + check("none", 100) + for _, key := range []string{"c", "g"} { + if _, err := intArg(args, key, 100, 1000); err == nil || err.Error() != "Argument "+key+" must be a positive integer." { + t.Errorf("%s: %v", key, err) + } + } +} + +func TestStringArguments(t *testing.T) { + args := map[string]any{"a": " ", "b": 3, "c": " x "} + if v, err := strArg(args, "a"); v != nil || err != nil { + t.Error(v, err) + } + if _, err := strArg(args, "b"); err == nil || err.Error() != "Argument b must be a string." { + t.Error(err) + } + if v, _ := strArg(args, "c"); v == nil || *v != " x " { + t.Error(v) + } + if _, err := requiredArg(args, "a"); err == nil || err.Error() != "Missing argument: a." { + t.Error(err) + } +} + +func TestResultsNoteTruncation(t *testing.T) { + res := &model.ExecResult{ + Columns: []model.ColumnInfo{{Name: "n", TypeName: "int", Kind: model.KindNumber}}, + Rows: []model.Row{{model.Str("1")}, {model.Str("2")}}, + Truncated: true, + } + r := render(res, 2, false) + if !strings.Contains(r.text, "2 rows shown; more rows exist (max_rows 2)") { + t.Fatal(r.text) + } + s := r.structured.(obj) + if v, _ := s.get("truncated"); v != true { + t.Fatal(s) + } + if v, _ := s.get("rowCount"); v != 2 { + t.Fatal(s) + } + if _, ok := s.get("rowsAffected"); ok { + t.Fatal(s) + } + + // Wide results are cut to the text budget and say how many rows were + // left out. + wide := &model.ExecResult{Columns: res.Columns} + for range 1000 { + wide.Rows = append(wide.Rows, model.Row{model.Str(strings.Repeat("x", 900))}) + } + r = render(wide, 1000, false) + if len(r.text) > textCap { + t.Fatal(len(r.text)) + } + if !strings.Contains(r.text, "omitted to keep the reply short") { + t.Fatal(r.text[len(r.text)-300:]) + } + if v, _ := r.structured.(obj).get("truncated"); v != true { + t.Fatal(v) + } + + three := uint64(3) + r = render(&model.ExecResult{RowsAffected: &three}, 100, true) + if !strings.HasPrefix(r.text, "3 rows affected") { + t.Fatal(r.text) + } + if v, _ := r.structured.(obj).get("rowsAffected"); v != &three { + t.Fatal(v) + } + if r.rows == nil || *r.rows != 3 { + t.Fatal(r.rows) + } + b, _ := marshal(r.structured) + if want := `{"columns":[],"rows":[],"rowCount":0,"truncated":false,"elapsedMs":0,"rowsAffected":3,"notices":[]}`; string(b) != want { + t.Fatal(string(b)) + } +} + +func TestReadRefusalsNameTheAccess(t *testing.T) { + p := profileOf(model.Postgres) + p.AiAccess = accessRead + if _, err := checkedSQL(p, "delete from t", false); err == nil || !strings.HasSuffix(err.Error(), readOnlyText) { + t.Fatal(err) + } + p.AiAccess = accessWrite + if _, err := checkedSQL(p, "delete from t", false); err == nil || !strings.Contains(err.Error(), "use execute") { + t.Fatal(err) + } + if got, err := checkedSQL(p, "delete from t;", true); err != nil || got != "delete from t" { + t.Fatal(got, err) + } + r := profileOf(model.Redis) + r.AiAccess = accessRead + if _, err := checkedSQL(r, "DEL k", false); err == nil || !strings.HasSuffix(err.Error(), readOnlyText) { + t.Fatal(err) + } +} + +func TestOrderedJSON(t *testing.T) { + b, err := marshal(obj{{"b", 1}, {"a", ""}, {"c", obj{{"z", nil}}}}) + if err != nil || string(b) != `{"b":1,"a":"","c":{"z":null}}` { + t.Fatal(string(b), err) + } +} diff --git a/main.go b/main.go index 1bde0ff..47be1f1 100644 --- a/main.go +++ b/main.go @@ -15,6 +15,7 @@ import ( "github.com/wailsapp/wails/v3/pkg/application" "github.com/LowBloat/LowQuery/internal/app" + "github.com/LowBloat/LowQuery/internal/mcp" "github.com/LowBloat/LowQuery/internal/profiles" ) @@ -42,6 +43,12 @@ func main() { if err != nil { log.Fatalf("user configuration directory unavailable: %v", err) } + + // `lowquery mcp`: MCP server for AI agents over stdio, without a window. + if len(os.Args) > 1 && os.Args[1] == "mcp" { + mcp.Run(configDir, pkg.Version) + return + } store, err := profiles.NewStore(configDir) if err != nil { log.Fatalf("could not create the configuration directory: %v", err) From 88c25c503da0d3a16f30dcbac71f9e8d978d628c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A1bio=20Henrique=20Ara=C3=BAjo?= Date: Fri, 4 Dec 2026 12:31:50 -0300 Subject: [PATCH 7/8] ci: check that the Windows GUI build answers lowquery mcp over stdio --- .github/workflows/ci.yml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8056892..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 From 360aff5585643c2cc3306e2010262d83308cbca3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A1bio=20Henrique=20Ara=C3=BAjo?= Date: Fri, 4 Dec 2026 12:55:48 -0300 Subject: [PATCH 8/8] test(go/mcp): wait for the cancelled call's activity entry --- internal/mcp/server_test.go | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/internal/mcp/server_test.go b/internal/mcp/server_test.go index 36c4ea1..d58660a 100644 --- a/internal/mcp/server_test.go +++ b/internal/mcp/server_test.go @@ -418,11 +418,19 @@ func TestConcurrentCallsAndCancel(t *testing.T) { if showRows(rowsOf(r)) != "[3]" { t.Fatalf("after cancel: %v", r) } - log, _ := ReadRecent(dir, 100) + // The cancelled call writes its entry after it frees the connection, so + // the query above can finish first. + var log []AuditEntry cancelled := false - for _, e := range log { - if e.Error != nil && strings.Contains(*e.Error, "The client cancelled the call.") { - cancelled = true + for deadline := time.Now().Add(5 * time.Second); !cancelled && time.Now().Before(deadline); { + log, _ = ReadRecent(dir, 100) + for _, e := range log { + if e.Error != nil && strings.Contains(*e.Error, "The client cancelled the call.") { + cancelled = true + } + } + if !cancelled { + time.Sleep(50 * time.Millisecond) } } if !cancelled {