From dbc6456f99f1131bb2f2a558a69fc5e7791e7feb Mon Sep 17 00:00:00 2001 From: Lenin Mookiah <2639584+leninworld@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:55:49 -0800 Subject: [PATCH] Clear /llm schema cache on completion refresh Fixes #2497 --- changelog.md | 1 + mycli/client_query.py | 1 + mycli/packages/special_commands/__init__.py | 5 ++ mycli/packages/special_commands/llm.py | 6 +++ mycli_test/pytests/test_client_query.py | 12 +++++ .../pytests/test_special_commands_init.py | 2 + mycli_test/pytests/test_special_llm.py | 53 +++++++++++++++++++ 7 files changed, 80 insertions(+) diff --git a/changelog.md b/changelog.md index 035683288..640459987 100644 --- a/changelog.md +++ b/changelog.md @@ -8,6 +8,7 @@ Features Bug Fixes -------- +* Refresh `/llm` schema and sample data when completions are refreshed, such as after DDL. * Display `DATE` and `TIME` scalars returned by `.|` transforms. * Stop truncating `/llm` table schemas at MySQL's `group_concat_max_len`. * Allow backslash-escaped apostrophes in REPL queries with or without Polars transforms. diff --git a/mycli/client_query.py b/mycli/client_query.py index 6838653cf..5c3d20405 100644 --- a/mycli/client_query.py +++ b/mycli/client_query.py @@ -37,6 +37,7 @@ def log_output(self, output: str) -> None: ... def format_sqlresult(self, *args: Any, **kwargs: Any) -> Any: ... def refresh_completions(self, reset: bool = False) -> list[SQLResult]: + special_commands.clear_llm_cache() # Cancel any in-flight schema prefetch before the completer is # replaced. Loaded-schema bookkeeping is intentionally preserved # so switching between already-loaded schemas does not re-fetch. diff --git a/mycli/packages/special_commands/__init__.py b/mycli/packages/special_commands/__init__.py index 02f7dc386..1f23020b7 100644 --- a/mycli/packages/special_commands/__init__.py +++ b/mycli/packages/special_commands/__init__.py @@ -52,6 +52,7 @@ if not os.environ.get('MYCLI_LLM_OFF'): from mycli.packages.special_commands.llm import ( FinishIteration, + clear_llm_cache, handle_llm, is_llm_command, sql_using_llm, @@ -62,6 +63,9 @@ class FinishIteration(Exception): # type: ignore[no-redef] def __init__(self, results=None): self.results = results + def clear_llm_cache() -> None: # type: ignore[no-redef] + """Do nothing when LLM support is disabled.""" + def is_llm_command(command: str) -> bool: # type: ignore[no-redef] return False @@ -86,6 +90,7 @@ def sql_using_llm(*args, **kwargs): # type: ignore[no-redef, misc] 'CommandNotFound', 'FinishIteration', 'SpecialCommandAlias', + 'clear_llm_cache', 'clip_command', 'close_tee', 'copy_query_to_clipboard', diff --git a/mycli/packages/special_commands/llm.py b/mycli/packages/special_commands/llm.py index 44659d03e..b9240eba5 100644 --- a/mycli/packages/special_commands/llm.py +++ b/mycli/packages/special_commands/llm.py @@ -48,6 +48,12 @@ SAMPLE_DATA_CACHE: dict[str, dict] = {} +def clear_llm_cache() -> None: + """Clear cached schema and sample data used by LLM prompts.""" + SCHEMA_DATA_CACHE.clear() + SAMPLE_DATA_CACHE.clear() + + def run_external_cmd( cmd: str, *args, diff --git a/mycli_test/pytests/test_client_query.py b/mycli_test/pytests/test_client_query.py index 35fc9ef9a..3f4f2b3ac 100644 --- a/mycli_test/pytests/test_client_query.py +++ b/mycli_test/pytests/test_client_query.py @@ -5,6 +5,7 @@ from mycli import client_query import mycli.client as mycli_client +from mycli.packages.special_commands import llm as llm_module from mycli.packages.sql_result.sql_result import SQLResult from mycli.types import Query from mycli_test.utils import ( # type: ignore[attr-defined] @@ -57,6 +58,17 @@ def test_refresh_completions_stops_prefetch() -> None: assert state['stopped'] == [True] +def test_refresh_completions_clears_llm_cache() -> None: + cli, _state = make_refresh_cli() + llm_module.SCHEMA_DATA_CACHE['current'] = 'cached schema' + llm_module.SAMPLE_DATA_CACHE['current'] = {'cached': 'sample'} + + mycli_client.MyCli.refresh_completions(cli) + + assert llm_module.SCHEMA_DATA_CACHE == {} + assert llm_module.SAMPLE_DATA_CACHE == {} + + def test_refresh_completions_returns_started_status() -> None: cli, _state = make_refresh_cli() diff --git a/mycli_test/pytests/test_special_commands_init.py b/mycli_test/pytests/test_special_commands_init.py index 7af891710..8a842fc38 100644 --- a/mycli_test/pytests/test_special_commands_init.py +++ b/mycli_test/pytests/test_special_commands_init.py @@ -77,6 +77,7 @@ def test_special_commands_init_uses_llm_implementation_when_enabled(load_special llm = importlib.import_module('mycli.packages.special_commands.llm') assert special_commands.FinishIteration is llm.FinishIteration + assert special_commands.clear_llm_cache is llm.clear_llm_cache assert special_commands.is_llm_command is llm.is_llm_command assert special_commands.handle_llm is llm.handle_llm assert special_commands.sql_using_llm is llm.sql_using_llm @@ -85,6 +86,7 @@ def test_special_commands_init_uses_llm_implementation_when_enabled(load_special def test_special_commands_init_uses_llm_stubs_when_disabled(load_special_commands: Callable[[bool], ModuleType]) -> None: special_commands = load_special_commands(True) + assert special_commands.clear_llm_cache() is None assert special_commands.is_llm_command(r'/llm prompt') is False with pytest.raises(special_commands.FinishIteration) as handle_exc: special_commands.handle_llm(cast_args := object()) diff --git a/mycli_test/pytests/test_special_llm.py b/mycli_test/pytests/test_special_llm.py index bb8b9984b..2c7f587a7 100644 --- a/mycli_test/pytests/test_special_llm.py +++ b/mycli_test/pytests/test_special_llm.py @@ -473,6 +473,59 @@ def fetchone(self) -> tuple[int, str] | None: assert sum(1 for query in cursor.executed if "information_schema.columns" in query) == 1 +def test_clear_llm_cache_refreshes_schema_and_sample_data(monkeypatch) -> None: + llm_module.SCHEMA_DATA_CACHE.clear() + llm_module.SAMPLE_DATA_CACHE.clear() + monkeypatch.setattr(llm_module.click, 'echo', lambda message: None) + + class DummyCursor: + def __init__(self) -> None: + self.executed: list[str] = [] + self.tables = ['orders'] + self.description: list[tuple[str, None]] = [] + self._rows: list[tuple[str, ...]] = [] + self._row: tuple[int] | None = None + + def execute(self, query: str) -> None: + self.executed.append(query) + if 'information_schema.columns' in query: + self._rows = [(table, 'id', 'int') for table in self.tables] + elif query == 'SHOW TABLES': + self._rows = [(table,) for table in self.tables] + else: + self.description = [('id', None)] + self._row = (len(self.tables),) + + def fetchall(self) -> list[tuple[str, ...]]: + return self._rows + + def fetchone(self) -> tuple[int] | None: + return self._row + + cursor = DummyCursor() + + assert get_schema(cast(Any, cursor), 'shop', 0) == 'orders(id int)' + assert get_sample_data(cast(Any, cursor), 'shop', 0, 0) == {'orders': [('id', 1)]} + cursor.tables.append('refunds') + assert get_schema(cast(Any, cursor), 'shop', 0) == 'orders(id int)' + assert get_sample_data(cast(Any, cursor), 'shop', 0, 0) == {'orders': [('id', 1)]} + + llm_module.clear_llm_cache() + + assert get_schema(cast(Any, cursor), 'shop', 0) == 'orders(id int)\nrefunds(id int)' + assert get_sample_data(cast(Any, cursor), 'shop', 0, 0) == { + 'orders': [('id', 2)], + 'refunds': [('id', 2)], + } + assert sum('information_schema.columns' in query for query in cursor.executed) == 2 + assert cursor.executed.count('SHOW TABLES') == 2 + + llm_module.clear_llm_cache() + + assert llm_module.SCHEMA_DATA_CACHE == {} + assert llm_module.SAMPLE_DATA_CACHE == {} + + # Test sql_using_llm with dummy cursor and fenced SQL output @patch("mycli.packages.special_commands.llm.run_external_cmd") def test_sql_using_llm_success(mock_run_cmd):