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 changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions mycli/client_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 5 additions & 0 deletions mycli/packages/special_commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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

Expand All @@ -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',
Expand Down
6 changes: 6 additions & 0 deletions mycli/packages/special_commands/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
12 changes: 12 additions & 0 deletions mycli_test/pytests/test_client_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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()

Expand Down
2 changes: 2 additions & 0 deletions mycli_test/pytests/test_special_commands_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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())
Expand Down
53 changes: 53 additions & 0 deletions mycli_test/pytests/test_special_llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading