From faf440e645a363257078e9308c2fad6ff28b18c2 Mon Sep 17 00:00:00 2001 From: Jakub Vins Date: Tue, 1 Dec 2026 15:04:12 +0100 Subject: [PATCH 1/2] feat(results): go back after an FK jump with `b` o / O replace the editor query and results, with no way back to where you jumped from. Each jump now pushes the current query, its result-table context (with FK metadata), cursor position and target database onto a back-stack (max 50). `b` in the results pane pops it, re-runs that query and restores the cursor once the table renders. Repeated jumps can be unwound one at a time. `b` is only active while the stack is non-empty and shows as "Back" in the footer then; o / O / b are listed in help. Co-Authored-By: Claude Opus 5.5 --- sqlit/core/input_context.py | 1 + sqlit/core/keymap.py | 1 + .../domains/query/ui/mixins/query_results.py | 4 + .../domains/results/state/results_focused.py | 16 ++++ sqlit/domains/results/ui/mixins/results.py | 76 ++++++++++++++- sqlit/domains/shell/app/main.py | 5 + sqlit/domains/shell/state/machine.py | 3 + sqlit/shared/ui/protocols/results.py | 2 + tests/ui/keybindings/test_navigation_back.py | 95 +++++++++++++++++++ 9 files changed, 201 insertions(+), 2 deletions(-) create mode 100644 tests/ui/keybindings/test_navigation_back.py diff --git a/sqlit/core/input_context.py b/sqlit/core/input_context.py index ab726946..84c2b45b 100644 --- a/sqlit/core/input_context.py +++ b/sqlit/core/input_context.py @@ -40,3 +40,4 @@ class InputContext: # True when the column under the cursor is referenced by some other table's FK # (i.e. pressing the navigate-referrers key would open the picker). cursor_column_is_foreign_key_target: bool = False + has_navigation_history: bool = False diff --git a/sqlit/core/keymap.py b/sqlit/core/keymap.py index 522e4567..8057bb8e 100644 --- a/sqlit/core/keymap.py +++ b/sqlit/core/keymap.py @@ -505,6 +505,7 @@ def _build_action_keys(self) -> list[ActionKeyDef]: ActionKeyDef("d", "delete_row", "results"), ActionKeyDef("o", "navigate_fk", "results"), ActionKeyDef("O", "navigate_referrers", "results"), + ActionKeyDef("b", "navigate_back", "results"), ActionKeyDef("y", "results_yank_leader_key", "results"), ActionKeyDef("x", "clear_results", "results"), ActionKeyDef("slash", "results_filter", "results"), diff --git a/sqlit/domains/query/ui/mixins/query_results.py b/sqlit/domains/query/ui/mixins/query_results.py index a68da143..b768b424 100644 --- a/sqlit/domains/query/ui/mixins/query_results.py +++ b/sqlit/domains/query/ui/mixins/query_results.py @@ -364,6 +364,9 @@ async def _display_query_results( if callable(prime): prime(table_info) self._pending_result_table_info = None + restore = getattr(self, "_consume_pending_cursor_restore", None) + if callable(restore): + restore() def _display_non_query_result(self: QueryMixinHost, affected: int, elapsed_ms: float) -> None: """Display non-query result (called on main thread).""" @@ -383,6 +386,7 @@ def _display_query_error(self: QueryMixinHost, error_message: str) -> None: """Display query error (called on main thread).""" self._cancel_results_render() self._pending_result_table_info = None + self._pending_cursor_restore = None # notify(severity="error") handles displaying the error in results via _show_error_in_results self.notify(f"Query error: {error_message}", severity="error") diff --git a/sqlit/domains/results/state/results_focused.py b/sqlit/domains/results/state/results_focused.py index c61c3f78..60bd1526 100644 --- a/sqlit/domains/results/state/results_focused.py +++ b/sqlit/domains/results/state/results_focused.py @@ -22,6 +22,13 @@ def has_results(app: InputContext) -> bool: self.allows("delete_row", has_results, key="d", label="Delete row", help="Delete row (generate DELETE)") self.allows("navigate_fk", has_results, key="o", label="FK jump", help="Open row referenced by foreign key") self.allows("navigate_referrers", has_results, key="O", label="Refs", help="Show tables referencing this row") + self.allows( + "navigate_back", + lambda app: app.has_navigation_history, + key="b", + label="Back", + help="Back to the results before the last FK jump", + ) self.allows("results_yank_leader_key", has_results, key="y", label="Copy", help="Copy menu (cell/row/all)") self.allows("clear_results", has_results, key="x", label="Clear", help="Clear results") self.allows("results_filter", has_results, key="slash", label="Filter", help="Filter rows") @@ -105,6 +112,14 @@ def get_display_bindings(self, app: InputContext) -> tuple[list[DisplayBinding], action="navigate_fk", ) ) + if app.has_navigation_history: + left.append( + DisplayBinding( + key=resolve_display_key("navigate_back") or "b", + label="Back", + action="navigate_back", + ) + ) if app.cursor_column_is_foreign_key_target: left.append( DisplayBinding( @@ -157,6 +172,7 @@ def get_display_bindings(self, app: InputContext) -> tuple[list[DisplayBinding], "delete_row", "navigate_fk", "navigate_referrers", + "navigate_back", "results_yank_leader_key", "clear_results", "results_filter", diff --git a/sqlit/domains/results/ui/mixins/results.py b/sqlit/domains/results/ui/mixins/results.py index c7b34568..62ecd1f1 100644 --- a/sqlit/domains/results/ui/mixins/results.py +++ b/sqlit/domains/results/ui/mixins/results.py @@ -16,6 +16,9 @@ FK_NAVIGATION_DEFAULT_LIMIT = 100 +NAVIGATION_HISTORY_LIMIT = 50 + + def build_fk_navigation_query( *, adapter: Any, @@ -1159,10 +1162,79 @@ def _generate_fk_jump_query( ref_database=ref_database, ) + def _push_navigation_history(self: ResultsMixinHost) -> None: + """Remember the current query, results context and cursor before a jump.""" + table, _columns, _rows, stacked = self._get_active_results_context() + query = self.query_input.text + if not query.strip(): + return + cursor: tuple[int, int] | None = None + if table is not None: + try: + coord = table.cursor_coordinate + cursor = (coord.row, coord.column) + except Exception: + cursor = None + table_info = self._get_active_results_table_info(table, stacked) if table else None + history: list[dict[str, Any]] = self._navigation_history + history.append( + { + "query": query, + "table_info": table_info, + "cursor": cursor, + "database": getattr(self, "_query_target_database", None), + } + ) + if len(history) > NAVIGATION_HISTORY_LIMIT: + del history[: len(history) - NAVIGATION_HISTORY_LIMIT] + + def action_navigate_back(self: ResultsMixinHost) -> None: + """Return to the results shown before the last o/O jump.""" + history: list[dict[str, Any]] = self._navigation_history + if not history: + self.notify("Nothing to go back to", severity="warning") + return + entry = history.pop() + # Reuse the previous table_info (already FK-primed) so o/O work at once. + self._pending_result_table_info = entry["table_info"] + self._pending_cursor_restore = entry["cursor"] + self._run_navigation_query(entry["query"], entry["database"], record=False) + + def _consume_pending_cursor_restore(self: ResultsMixinHost) -> None: + """Move the results cursor to the position saved by navigate_back (once).""" + coord = self._pending_cursor_restore + if coord is None: + return + self._pending_cursor_restore = None + + def apply() -> None: + try: + table = self.results_table + except Exception: + return + if table is None or table.row_count <= 0: + return + row = max(0, min(coord[0], table.row_count - 1)) + col = max(0, min(coord[1], max(table.column_count - 1, 0))) + try: + table.move_cursor(row=row, column=col) + except Exception: + pass + + # The table was just mounted; setting the cursor synchronously is + # overwritten when the DataTable finishes initialising. + self.call_after_refresh(apply) + def _run_navigation_query( - self: ResultsMixinHost, query: str, database: str | None + self: ResultsMixinHost, query: str, database: str | None, *, record: bool = True ) -> None: - """Inject `query` into the editor and execute it (mirrors explorer's pattern).""" + """Inject `query` into the editor and execute it (mirrors explorer's pattern). + + With `record`, the current results are pushed onto the back-stack first. + """ + if record: + self._push_navigation_history() + def run_navigation() -> None: load_unsaved = getattr(self, "_load_unsaved_query_text", None) if callable(load_unsaved): diff --git a/sqlit/domains/shell/app/main.py b/sqlit/domains/shell/app/main.py index 2f85d91b..031742b1 100644 --- a/sqlit/domains/shell/app/main.py +++ b/sqlit/domains/shell/app/main.py @@ -213,6 +213,10 @@ def __init__( self._state_machine = UIStateMachine() self._last_query_table: dict[str, Any] | None = None self._pending_result_table_info: dict[str, Any] | None = None + # FK navigation back-stack (o/O push, b pops) and the cursor to restore + # once the popped query's results render. + self._navigation_history: list[dict[str, Any]] = [] + self._pending_cursor_restore: tuple[int, int] | None = None self._query_target_database: str | None = None # Target DB for auto-generated queries self._restart_requested: bool = False # Idle scheduler for background work @@ -354,6 +358,7 @@ def _get_input_context(self) -> InputContext: count_buffer=self._count_buffer, cursor_column_is_foreign_key=cursor_column_is_foreign_key, cursor_column_is_foreign_key_target=cursor_column_is_foreign_key_target, + has_navigation_history=bool(getattr(self, "_navigation_history", None)), ) def _debug_screen_label(self, screen: Any | None) -> str: diff --git a/sqlit/domains/shell/state/machine.py b/sqlit/domains/shell/state/machine.py index cea1cb8c..68007714 100644 --- a/sqlit/domains/shell/state/machine.py +++ b/sqlit/domains/shell/state/machine.py @@ -343,6 +343,9 @@ def lk(action: str, menu: str, fallback: str) -> str: s.binding(k("next_result_section", ""), "Next result set") s.binding(k("prev_result_section", ""), "Previous result set") s.binding(k("toggle_result_section", "z"), "Collapse/expand result") + s.binding(k("navigate_fk", "o"), "Open row referenced by foreign key") + s.binding(k("navigate_referrers", "O"), "Show rows referencing this row") + s.binding(k("navigate_back", "b"), "Back to results before the last jump") results_yank = k("results_yank_leader_key", "y") s.subsection(f"Copy Menu ({results_yank}):") s.binding(f"{results_yank}{lk('cell', 'ry', 'c')}", "Copy cell") diff --git a/sqlit/shared/ui/protocols/results.py b/sqlit/shared/ui/protocols/results.py index 66c71985..97fd9285 100644 --- a/sqlit/shared/ui/protocols/results.py +++ b/sqlit/shared/ui/protocols/results.py @@ -17,6 +17,8 @@ class ResultsStateProtocol(Protocol): _internal_clipboard: str _last_query_table: dict[str, Any] | None _pending_result_table_info: dict[str, Any] | None + _navigation_history: list[dict[str, Any]] + _pending_cursor_restore: tuple[int, int] | None _results_table_counter: int _results_filter_visible: bool _results_filter_text: str diff --git a/tests/ui/keybindings/test_navigation_back.py b/tests/ui/keybindings/test_navigation_back.py new file mode 100644 index 00000000..e3b5303e --- /dev/null +++ b/tests/ui/keybindings/test_navigation_back.py @@ -0,0 +1,95 @@ +"""`b` in results returns to the results shown before an `o`/`O` FK jump.""" + +from __future__ import annotations + +import sqlite3 +from pathlib import Path + +import pytest + +from sqlit.domains.shell.app.main import SSMSTUI + +from ..mocks import MockConnectionStore, MockSettingsStore, build_test_services, create_test_connection + + +@pytest.fixture +def fk_db(tmp_path: Path) -> Path: + path = tmp_path / "fk.db" + conn = sqlite3.connect(path) + conn.executescript( + """ + CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT); + CREATE TABLE posts (id INTEGER PRIMARY KEY, user_id INTEGER REFERENCES users(id), title TEXT); + INSERT INTO users VALUES (1, 'ann'), (2, 'bob'), (3, 'cy'); + INSERT INTO posts VALUES (10, 1, 'a'), (11, 3, 'b'), (12, 2, 'c'); + """ + ) + conn.commit() + conn.close() + return path + + +async def _wait(pilot, predicate, tries: int = 60) -> bool: + for _ in range(tries): + if predicate(): + return True + await pilot.pause(0.05) + return predicate() + + +@pytest.mark.asyncio +async def test_back_restores_previous_query_and_cursor(fk_db: Path) -> None: + config = create_test_connection("fk", "sqlite", file_path=str(fk_db)) + services = build_test_services( + connection_store=MockConnectionStore([config]), + settings_store=MockSettingsStore({"theme": "tokyo-night"}), + ) + app = SSMSTUI(services=services) + + async with app.run_test(size=(140, 40)) as pilot: + app.connect_to_server(config) + assert await _wait(pilot, lambda: app._session is not None) + + posts_query = "SELECT * FROM posts" + app._last_query_table = {"database": None, "schema": "", "name": "posts", "columns": []} + app._pending_result_table_info = app._last_query_table + app.query_input.text = posts_query + app.action_execute_query() + assert await _wait(pilot, lambda: app.results_table.row_count == 3) + info = app.results_table.result_table_info + assert await _wait(pilot, lambda: bool(info.get("foreign_keys"))) + + app.results_table.move_cursor(row=1, column=1) # posts row 2, user_id = 3 + await pilot.pause() + assert app._navigation_history == [] + + app.action_navigate_fk() + assert await _wait(pilot, lambda: "users" in app.query_input.text and app.results_table.row_count == 1) + assert len(app._navigation_history) == 1 + + app.action_navigate_back() + assert await _wait(pilot, lambda: app.query_input.text == posts_query and app.results_table.row_count == 3) + assert await _wait(pilot, lambda: tuple(app.results_table.cursor_coordinate) == (1, 1)) + assert app._navigation_history == [] + + app.action_navigate_back() # empty stack: no-op + await pilot.pause() + assert app.query_input.text == posts_query + + +def test_b_is_bound_to_navigate_back_in_results() -> None: + from sqlit.core.keymap import get_keymap + + assert get_keymap().action("navigate_back") == "b" + + +def test_navigate_back_only_allowed_with_history() -> None: + from sqlit.domains.shell.state.machine import UIStateMachine + + from .test_state_machine import make_context + + machine = UIStateMachine() + assert not machine.check_action(make_context(focus="results", has_results=True), "navigate_back") + assert machine.check_action( + make_context(focus="results", has_results=True, has_navigation_history=True), "navigate_back" + ) From 38c925acf43c9678ec8537cb06c40b04bf0023c2 Mon Sep 17 00:00:00 2001 From: Jakub Vins Date: Tue, 1 Dec 2026 15:10:29 +0100 Subject: [PATCH 2/2] feat(results): bind FK back to ctrl+o and keep results focused Use ctrl+o, vim's jump-list "go back", instead of b. o / O / back loaded the query through the history loader, which focuses the editor, so every jump left the results pane. Re-focus the results table after loading when navigation started there. Co-Authored-By: Claude Opus 5.5 --- sqlit/core/keymap.py | 2 +- sqlit/domains/results/state/results_focused.py | 4 ++-- sqlit/domains/results/ui/mixins/results.py | 8 ++++++++ sqlit/domains/shell/state/machine.py | 2 +- tests/ui/keybindings/test_navigation_back.py | 9 ++++++--- 5 files changed, 18 insertions(+), 7 deletions(-) diff --git a/sqlit/core/keymap.py b/sqlit/core/keymap.py index 8057bb8e..1451919f 100644 --- a/sqlit/core/keymap.py +++ b/sqlit/core/keymap.py @@ -505,7 +505,7 @@ def _build_action_keys(self) -> list[ActionKeyDef]: ActionKeyDef("d", "delete_row", "results"), ActionKeyDef("o", "navigate_fk", "results"), ActionKeyDef("O", "navigate_referrers", "results"), - ActionKeyDef("b", "navigate_back", "results"), + ActionKeyDef("ctrl+o", "navigate_back", "results"), ActionKeyDef("y", "results_yank_leader_key", "results"), ActionKeyDef("x", "clear_results", "results"), ActionKeyDef("slash", "results_filter", "results"), diff --git a/sqlit/domains/results/state/results_focused.py b/sqlit/domains/results/state/results_focused.py index 60bd1526..cc8b5b74 100644 --- a/sqlit/domains/results/state/results_focused.py +++ b/sqlit/domains/results/state/results_focused.py @@ -25,7 +25,7 @@ def has_results(app: InputContext) -> bool: self.allows( "navigate_back", lambda app: app.has_navigation_history, - key="b", + key="^o", label="Back", help="Back to the results before the last FK jump", ) @@ -115,7 +115,7 @@ def get_display_bindings(self, app: InputContext) -> tuple[list[DisplayBinding], if app.has_navigation_history: left.append( DisplayBinding( - key=resolve_display_key("navigate_back") or "b", + key=resolve_display_key("navigate_back") or "^o", label="Back", action="navigate_back", ) diff --git a/sqlit/domains/results/ui/mixins/results.py b/sqlit/domains/results/ui/mixins/results.py index 62ecd1f1..8ce478be 100644 --- a/sqlit/domains/results/ui/mixins/results.py +++ b/sqlit/domains/results/ui/mixins/results.py @@ -1236,11 +1236,19 @@ def _run_navigation_query( self._push_navigation_history() def run_navigation() -> None: + # Loading text into the editor focuses it; navigation is driven + # from the results pane, so keep the user there. + try: + results_focused = self.results_table.has_focus + except Exception: + results_focused = False load_unsaved = getattr(self, "_load_unsaved_query_text", None) if callable(load_unsaved): load_unsaved(query) else: self.query_input.text = query + if results_focused: + self.results_table.focus() if hasattr(self, "_query_target_database"): self._query_target_database = database action_execute = getattr(self, "action_execute_query", None) diff --git a/sqlit/domains/shell/state/machine.py b/sqlit/domains/shell/state/machine.py index 68007714..8514cf61 100644 --- a/sqlit/domains/shell/state/machine.py +++ b/sqlit/domains/shell/state/machine.py @@ -345,7 +345,7 @@ def lk(action: str, menu: str, fallback: str) -> str: s.binding(k("toggle_result_section", "z"), "Collapse/expand result") s.binding(k("navigate_fk", "o"), "Open row referenced by foreign key") s.binding(k("navigate_referrers", "O"), "Show rows referencing this row") - s.binding(k("navigate_back", "b"), "Back to results before the last jump") + s.binding(k("navigate_back", "^o"), "Back to results before the last jump") results_yank = k("results_yank_leader_key", "y") s.subsection(f"Copy Menu ({results_yank}):") s.binding(f"{results_yank}{lk('cell', 'ry', 'c')}", "Copy cell") diff --git a/tests/ui/keybindings/test_navigation_back.py b/tests/ui/keybindings/test_navigation_back.py index e3b5303e..174977c7 100644 --- a/tests/ui/keybindings/test_navigation_back.py +++ b/tests/ui/keybindings/test_navigation_back.py @@ -1,4 +1,4 @@ -"""`b` in results returns to the results shown before an `o`/`O` FK jump.""" +"""Ctrl+O in results returns to the results shown before an `o`/`O` FK jump.""" from __future__ import annotations @@ -60,27 +60,30 @@ async def test_back_restores_previous_query_and_cursor(fk_db: Path) -> None: assert await _wait(pilot, lambda: bool(info.get("foreign_keys"))) app.results_table.move_cursor(row=1, column=1) # posts row 2, user_id = 3 + app.results_table.focus() await pilot.pause() assert app._navigation_history == [] app.action_navigate_fk() assert await _wait(pilot, lambda: "users" in app.query_input.text and app.results_table.row_count == 1) assert len(app._navigation_history) == 1 + assert app.results_table.has_focus, "jumping must keep focus in the results pane" app.action_navigate_back() assert await _wait(pilot, lambda: app.query_input.text == posts_query and app.results_table.row_count == 3) assert await _wait(pilot, lambda: tuple(app.results_table.cursor_coordinate) == (1, 1)) assert app._navigation_history == [] + assert app.results_table.has_focus app.action_navigate_back() # empty stack: no-op await pilot.pause() assert app.query_input.text == posts_query -def test_b_is_bound_to_navigate_back_in_results() -> None: +def test_ctrl_o_is_bound_to_navigate_back_in_results() -> None: from sqlit.core.keymap import get_keymap - assert get_keymap().action("navigate_back") == "b" + assert get_keymap().action("navigate_back") == "ctrl+o" def test_navigate_back_only_allowed_with_history() -> None: