Skip to content

Fix: sidebar schema selection, explain tab, autocomplete, run/explain flow - #1

Merged
EVWorth merged 6 commits into
mainfrom
bugfix/sidebar-schema-selection
Apr 8, 2026
Merged

EVWorth merged 6 commits into
mainfrom
bugfix/sidebar-schema-selection

Conversation

@EVWorth

@EVWorth EVWorth commented Apr 8, 2026

Copy link
Copy Markdown
Owner

Bug fixes in this PR

  • Sidebar schema selection: double-click to set active DB, query context passed correctly
  • Explain tab switching: auto-switch to explain on explain result, back to results on run
  • MariaDB EXPLAIN ANALYZE: use ANALYZE SELECT syntax on MariaDB instead of EXPLAIN ANALYZE
  • Autocomplete: fix FROM context detection bug, add views, add column suggestions from FROM clause
  • useQueryExecution hook: centralizes connection ID + database threading — eliminates entire class of wrong-DB bugs
  • QueryToolbar: refactored to use the new hook
  • Version: 0.1.0 → 0.1.1

EVWorth and others added 6 commits April 7, 2026 21:56
- Fix Windows Monaco editor loading by bundling workers locally instead of
  loading from CDN (blocked by Tauri CSP in packaged builds)
- Fix macOS Copilot CLI PATH by augmenting launchd PATH at startup to include
  /opt/homebrew/bin, /usr/local/bin, etc.
- Change sidebar table single-click to run SELECT inline without opening a tab;
  double-click inserts table name at cursor
- Add sidebar filter/search (Ctrl+Shift+F) with eager fetch across all schemas
- Fix filter to match only object names, not database names
- Fix filter expansion to keep DBs visible during async data load
- Add schema double-click to select active database for query context
- Prepend USE `db` to queries when a schema is selected on the active tab
- Extract single/double click timer logic into src/hooks/useClickHandler.ts

Co-authored-by: Copilot <[email protected]>
Move database context handling from frontend (USE prepend) to the Rust
execute_query command. Accepts an optional database param; if provided,
acquires a dedicated pool connection and runs USE `db` on it before
executing statements — guaranteeing both share the same MySQL session.

This fixes the regression where Run/Explain showed no results after
the USE statement ran on a different pool connection than the query.

Also update mas-ai/tools.rs callers to pass None for the new param.

Co-authored-by: Copilot <[email protected]>
- Use useEffect for explain tab auto-switch (was broken render-time mutation)
- Sidebar table/view clicks now pass dbName as database param
- Context menu 'Select Top 100 Rows' also passes dbName
- executeExplain/executeExplainAnalyze now accept and pass optional database
- QueryToolbar passes activeTab?.database to both explain calls

Co-authored-by: Copilot <[email protected]>
- Run now switches back to results tab when new query results arrive
- EXPLAIN ANALYZE detects MariaDB and uses 'ANALYZE SELECT' syntax
- Fixed detectContext trimEnd() bug causing FROM to show keywords
- FROM/JOIN now suggests views alongside tables (no keyword leakage)
- SELECT column suggestions now parse FROM clause to show relevant columns only

Co-authored-by: Copilot <[email protected]>
- New hook reads selectedConnectionId and activeTab.database from stores
  so callers never manually thread these params through component layers
- QueryToolbar now uses useQueryExecution instead of calling store actions
  directly with connectionId/database args
- 10 new tests covering: canExecute states, correct param forwarding,
  database reflection after tab connection change, no-op when disconnected

Co-authored-by: Copilot <[email protected]>
Copilot AI review requested due to automatic review settings April 8, 2026 04:05
@EVWorth
EVWorth merged commit a761ab2 into main Apr 8, 2026
@EVWorth
EVWorth deleted the bugfix/sidebar-schema-selection branch April 8, 2026 04:05

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes several query-context and UX issues around schema selection, explain/run flows, and autocomplete by threading an explicit database context from the UI down to the Rust query executor.

Changes:

  • Add optional database context to query execution across frontend store/API and the Rust execute_query command/executor.
  • Improve sidebar schema interactions (double-click DB selection, filter UI, single vs double click behavior) and results/explain tab switching behavior.
  • Enhance SQL autocomplete with better context detection, view suggestions, and FROM-clause-aware column suggestions; bump version to 0.1.1.

Reviewed changes

Copilot reviewed 18 out of 19 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
src/stores/resultStore.ts Threads database through query/explain execution and history entries; MariaDB explain-analyze handling.
src/main.tsx Configures Monaco loader + editor worker environment.
src/lib/tauri-api.ts Extends executeQuery IPC wrapper to accept optional database.
src/lib/schema-completion-provider.ts Fixes context detection; adds view suggestions and FROM-clause-based column suggestions.
src/hooks/useQueryExecution.ts Introduces a hook to centralize query execution context for the toolbar.
src/hooks/useClickHandler.ts Adds shared single vs double click handler logic.
src/hooks/tests/useQueryExecution.test.ts Adds unit tests for useQueryExecution.
src/components/layout/Sidebar.tsx Adds schema filter, DB selection via double-click, and table/view click behaviors.
src/components/layout/MainPanel.tsx Updates results/explain tab auto-switching logic.
src/components/editor/SQLEditor.tsx Wires view data into completion provider.
src/components/editor/QueryToolbar.tsx Refactors to use useQueryExecution.
src-tauri/tauri.conf.json Bumps app version to 0.1.1.
src-tauri/src/lib.rs Adds macOS PATH augmentation for GUI app launches.
src-tauri/src/commands/mod.rs Adds database arg to execute_query command and forwards it to executor.
src-tauri/crates/mas-core/src/query/executor.rs Executes queries on a dedicated connection; applies USE <db> when provided.
src-tauri/crates/mas-ai/src/tools.rs Updates executor callsites to pass None for new database parameter.
src-tauri/Cargo.toml Bumps Rust package version to 0.1.1.
package.json Bumps version; adds @vitest/coverage-v8.
package-lock.json Locks dependency changes for coverage.

Comment on lines 18 to +22
pub async fn execute(
&self,
connection_id: &str,
sql: &str,
database: Option<&str>,

Copilot AI Apr 8, 2026

Copy link

Choose a reason for hiding this comment

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

QueryExecutor::execute now requires a database: Option<&str> argument, but there are still call sites using the old 2-arg signature (e.g. src-tauri/crates/mas-core/tests/integration_tests.rs calls executor.execute(&info.id, "SELECT …")). This will fail to compile; update the remaining call sites/tests to pass None (or Some(db) where appropriate).

Copilot uses AI. Check for mistakes.
Comment on lines +33 to +37
if let Some(db) = database {
let use_sql = format!("USE `{}`", db);
tracing::debug!(database = %db, "Switching database context");
sqlx::query(&use_sql)
.execute(conn.as_mut())

Copilot AI Apr 8, 2026

Copy link

Choose a reason for hiding this comment

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

USE {}is built via string interpolation without escaping backticks in `db`. If a database name contains a backtick, the statement will break and this also widens the surface for SQL injection via a crafted name. Escape backticks (e.g. replace ` with) before formatting, or otherwise safely quote/validate the identifier.

Copilot uses AI. Check for mistakes.
Comment on lines +365 to +390
for (const tableName of fromTables) {
for (const [db, dbTables] of tables.entries()) {
const match = dbTables.find(
(t) => t.toLowerCase() === tableName.toLowerCase(),
);
if (match) {
const key = `${db}.${match}`;
const cachedCols = columns.get(key);
const cols = cachedCols
? cachedCols
: await schemaData.fetchColumns(connectionId, db, match);
for (const col of cols) {
suggestions.push({
label: col.name,
kind: monaco.languages.CompletionItemKind.Field,
insertText: col.name,
range,
detail: `${col.column_type} (${key})`,
documentation: buildColumnDoc(col),
sortText: colPriority + col.name,
});
}
break; // found db for this table
}
}
}

Copilot AI Apr 8, 2026

Copy link

Choose a reason for hiding this comment

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

This completion path can perform multiple await schemaData.fetchColumns(...) calls serially while building suggestions. Because completion providers run on each trigger, sequential round-trips here can noticeably stall autocomplete (especially with multiple FROM/JOIN tables). Consider fetching columns in parallel (e.g. collect promises + Promise.all), and/or returning cached columns immediately while refreshing in the background.

Suggested change
for (const tableName of fromTables) {
for (const [db, dbTables] of tables.entries()) {
const match = dbTables.find(
(t) => t.toLowerCase() === tableName.toLowerCase(),
);
if (match) {
const key = `${db}.${match}`;
const cachedCols = columns.get(key);
const cols = cachedCols
? cachedCols
: await schemaData.fetchColumns(connectionId, db, match);
for (const col of cols) {
suggestions.push({
label: col.name,
kind: monaco.languages.CompletionItemKind.Field,
insertText: col.name,
range,
detail: `${col.column_type} (${key})`,
documentation: buildColumnDoc(col),
sortText: colPriority + col.name,
});
}
break; // found db for this table
}
}
}
const matchedTables: Array<{ key: string; db: string; table: string }> = [];
for (const tableName of fromTables) {
for (const [db, dbTables] of tables.entries()) {
const match = dbTables.find(
(t) => t.toLowerCase() === tableName.toLowerCase(),
);
if (match) {
matchedTables.push({
key: `${db}.${match}`,
db,
table: match,
});
break; // found db for this table
}
}
}
const columnResults = await Promise.all(
matchedTables.map(async ({ key, db, table }) => ({
key,
cols:
columns.get(key) ??
(await schemaData.fetchColumns(connectionId, db, table)),
})),
);
for (const { key, cols } of columnResults) {
for (const col of cols) {
suggestions.push({
label: col.name,
kind: monaco.languages.CompletionItemKind.Field,
insertText: col.name,
range,
detail: `${col.column_type} (${key})`,
documentation: buildColumnDoc(col),
sortText: colPriority + col.name,
});
}
}

Copilot uses AI. Check for mistakes.
Comment on lines +13 to +15
export function useClickHandler() {
const timers = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());

Copilot AI Apr 8, 2026

Copy link

Choose a reason for hiding this comment

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

Timers created for pending single-clicks are never cleared on unmount. If a component using this hook unmounts while a timer is pending, onSingle/onDouble can still fire afterward (and may call setState on an unmounted component). Add a cleanup effect in this hook to clear all pending timeouts when the hook owner unmounts.

Copilot uses AI. Check for mistakes.
Comment on lines +370 to +374
const handleTableClick = (dbName: string, tableName: string) =>
makeClickHandler(
`${dbName}.${tableName}`,
() => executeQuery(connectionId, `SELECT * FROM \`${dbName}\`.\`${tableName}\` LIMIT 100`, dbName),
() => insertNameAtCursor(tableName),

Copilot AI Apr 8, 2026

Copy link

Choose a reason for hiding this comment

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

handleTableClick/handleViewClick use the same timer key shape (${dbName}.${objectName}). If a table and view share the same name in a schema, clicks can interfere (a second click on the view could be treated as a double-click for the table handler, and vice-versa). Prefix the key with the object type (e.g. table: vs view:) to avoid collisions.

Copilot uses AI. Check for mistakes.
Comment on lines +486 to +491
<button
onClick={() => setFilterText("")}
className="absolute right-2 top-1/2 -translate-y-1/2 text-[var(--color-text-muted)] hover:text-[var(--color-text-primary)]"
>
<X className="h-3 w-3" />
</button>

Copilot AI Apr 8, 2026

Copy link

Choose a reason for hiding this comment

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

The filter clear button is icon-only and currently has no accessible name. Add an aria-label (and/or title) so screen readers can announce what it does.

Copilot uses AI. Check for mistakes.
Comment on lines +24 to +28
const isExecuting = useResultStore((s) => s.isExecuting);

const connectionId = selectedConnectionId ?? undefined;
const database = activeTab?.database;

Copilot AI Apr 8, 2026

Copy link

Choose a reason for hiding this comment

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

connectionId is derived only from selectedConnectionId, even though the active editor tab also carries its own connectionId. If the user changes the selected connection while keeping a tab from a different connection active, this hook can execute queries against the wrong connection. Prefer activeTab?.connectionId (fallback to selectedConnectionId) and adjust the docstring/tests accordingly.

Copilot uses AI. Check for mistakes.
EVWorth added a commit that referenced this pull request Jul 20, 2026
Two parallel research agents audited SQLPilot against SQuirreL,
HeidiSQL, MySQL Workbench, DBeaver, DataGrip, Navicat, TablePlus,
pgAdmin, Postico, SQLTools (VS Code). Landed the small wins + the
two bugs they uncovered in one shot.

## Bugs fixed

1. Ctrl+Shift+A (Explain Analyze) was advertised in ShortcutsDialog
   but no Monaco action existed. Pressing it did nothing. Now: real
   Monaco action wired to executeExplainAnalyze.

2. F5 was double-bound to two conflicting semantics:
   - useKeyboardShortcuts.ts -> F5 = 'execute query whole tab'
   - src-tauri/src/menu.rs -> F5 = 'Refresh Schema'
   Industry consensus (8/10 tools: DBeaver, HeidiSQL, pgAdmin, Navicat,
   MySQL Workbench, TablePlus, DataGrip, SQLTools) says F5 = Refresh
   Schema. Resolved by:
   - Removed F5 from useKeyboardShortcuts.ts execute-all path.
   - Added a Monaco action 'refresh-schema' with F5 keybinding so the
     bind works inside the editor too.
   - Left Tauri menu.rs F5 = refresh-schema as-is.
   Ctrl+Shift+Enter remains the only 'execute all' binding.

3. Ctrl+Shift+F collision with Format SQL. SchemaTree filter input
   focus was on Ctrl+Shift+F, colliding with Format SQL when both
   Monaco was focused and the tree visible. Rebound to Ctrl+Shift+O.

## New Monaco actions (SQLEditor.tsx)

- explain-analyze: Ctrl+Shift+A (fixes #1)
- lowercase-selected: Ctrl+Shift+L (industry standard, 8/10 tools)
- uppercase-selected: Ctrl+Shift+U (industry standard, 8/10 tools)
- refresh-schema: F5 (fixes #2)

## New app-level shortcuts (useKeyboardShortcuts.ts)

- Ctrl+B: toggle sidebar (alias for Ctrl+Shift+C; 8/10 industry tools
  use Ctrl+B). Both bindings work.
- Ctrl+1..9: switch to tab by index (industry standard 6/10).

## Docs updated (ShortcutsDialog.tsx)

- Removed F5 = Run all statements (now = Refresh schema)
- Added Monaco-default entries (Ctrl+/, Ctrl+D, Alt+Up/Down, F12)
  that were previously undocumented
- Toggle sidebar shows both Ctrl+B / Ctrl+Shift+C
- Switch to tab by index shows Ctrl+1..9
- Focus schema tree filter shows Ctrl+Shift+O (was Ctrl+Shift+F)

## Tests

- Delete obsolete F5 app-level execute query block (5 tests removed).
- Add ShortcutsDialog tests for new entries.
- Add useKeyboardShortcuts tests for Ctrl+B and Ctrl+1..9 (5 cases).
- Add SQLEditor browser tests for new Monaco actions (8 tests covering
  registration + run() delegation for explain-analyze, refresh-schema,
  lowercase, uppercase).

Total: ~16 added, ~5 removed. vitest full: 1462/1462 pass (was 1453).

## Out of scope (deliberate)

Industry research surfaced several larger asks that need new UI
components / store work and are better as separate PRs or issues:
- Command palette (Ctrl+Shift+P)
- Quick file/tab switcher (Ctrl+P)
- Restore closed tab (Ctrl+Shift+T) -- needs tab history in editorStore
- Query history view (no history UI yet)
- Settings dialog (Ctrl+,) -- no global settings dialog exists
- Inline commit pending grid edits, add/delete/duplicate row from grid
- "Cancel running query" -- low industry prevalence + Escape
  interference

Items NOT changed but worth flagging:
- Ctrl+Shift+C for sidebar kept as alias alongside new Ctrl+B
- shortcut choices follow industry consensus except where SQLPilot's
  choice was already better
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants