Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions sqlit/core/input_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
1 change: 1 addition & 0 deletions sqlit/core/keymap.py
Original file line number Diff line number Diff line change
Expand Up @@ -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("ctrl+o", "navigate_back", "results"),
ActionKeyDef("y", "results_yank_leader_key", "results"),
ActionKeyDef("x", "clear_results", "results"),
ActionKeyDef("slash", "results_filter", "results"),
Expand Down
4 changes: 4 additions & 0 deletions sqlit/domains/query/ui/mixins/query_results.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)."""
Expand All @@ -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")

Expand Down
16 changes: 16 additions & 0 deletions sqlit/domains/results/state/results_focused.py
Original file line number Diff line number Diff line change
Expand Up @@ -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="^o",
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")
Expand Down Expand Up @@ -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 "^o",
label="Back",
action="navigate_back",
)
)
if app.cursor_column_is_foreign_key_target:
left.append(
DisplayBinding(
Expand Down Expand Up @@ -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",
Expand Down
84 changes: 82 additions & 2 deletions sqlit/domains/results/ui/mixins/results.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
FK_NAVIGATION_DEFAULT_LIMIT = 100


NAVIGATION_HISTORY_LIMIT = 50


def build_fk_navigation_query(
*,
adapter: Any,
Expand Down Expand Up @@ -1159,16 +1162,93 @@ 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:
# 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)
Expand Down
5 changes: 5 additions & 0 deletions sqlit/domains/shell/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
3 changes: 3 additions & 0 deletions sqlit/domains/shell/state/machine.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,9 @@ def lk(action: str, menu: str, fallback: str) -> str:
s.binding(k("next_result_section", "<tab>"), "Next result set")
s.binding(k("prev_result_section", "<s-tab>"), "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", "^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")
Expand Down
2 changes: 2 additions & 0 deletions sqlit/shared/ui/protocols/results.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
98 changes: 98 additions & 0 deletions tests/ui/keybindings/test_navigation_back.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
"""Ctrl+O 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
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_ctrl_o_is_bound_to_navigate_back_in_results() -> None:
from sqlit.core.keymap import get_keymap

assert get_keymap().action("navigate_back") == "ctrl+o"


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"
)