"""`harlequin.query_log`: the store both commands write, and what it promises. Three promises, and the tests are grouped by them: a row survives a round trip with its types intact, a schema change is a migration rather than a new file, and nothing here ever fails the query it was recording. """ from __future__ import annotations import sqlite3 import sys from concurrent.futures import ProcessPoolExecutor from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Any import pytest from harlequin import query_log from harlequin.query_log import ( MIGRATIONS, PROGRAMS, READ_COLUMNS, RETENTION_ROWS, SCHEMA_VERSION, QueryLog, Record, adopt, connection_id, default_path, get_connection_hash, recent, ) from harlequin.redact import REDACTED, hide_secrets_in SECRET = "hunter2-and-then-some" @pytest.fixture def store(tmp_path: Path) -> Path: return tmp_path / "log" / "history.db" @pytest.fixture def log(store: Path) -> QueryLog: return QueryLog(program="hsql", connection="abc123", path=store) def next_process(monkeypatch: pytest.MonkeyPatch) -> None: """Forget which stores have been trimmed, as starting a process does.""" monkeypatch.setattr("harlequin.query_log._trimmed", set()) def rows(store: Path, columns: str = "*") -> list[dict[str, Any]]: db = sqlite3.connect(store) db.row_factory = sqlite3.Row try: return [ dict(row) for row in db.execute(f"select {columns} from queries order by id") ] finally: db.close() # --- a record ---------------------------------------------------------------- def test_a_row_survives_the_round_trip(log: QueryLog, store: Path) -> None: log.write( "select 1", rows=42, truncated=True, elapsed_ms=12.5, ) (record,) = rows(store) assert record["program"] == "hsql" assert record["connection"] == "abc123" assert record["sql"] == "select 1" assert record["status"] == "ok" assert record["rows"] == 42 assert record["truncated"] == 1 assert record["elapsed_ms"] == 12.5 assert record["error"] is None # UTC, ISO-8601, and a value `datetime` reads back assert datetime.fromisoformat(record["run_at"]).tzinfo is not None def test_a_duration_is_rounded_to_microseconds(log: QueryLog, store: Path) -> None: """A double's sixteen digits are noise in a column a person reads, and the value is written once and printed every time the history is.""" row = log.write("select 1", elapsed_ms=0.013326999976470688) (record,) = rows(store) assert record["elapsed_ms"] == 0.013 log.update(row, elapsed_ms=1234.56789) (record,) = rows(store) assert record["elapsed_ms"] == 1234.568 def test_a_statement_is_recorded_before_its_rows_are_known( log: QueryLog, store: Path ) -> None: """Which is what a session killed mid-fetch keeps.""" row = log.write("select 1") (written,) = rows(store) assert (written["sql"], written["status"], written["rows"]) == ( "select 1", "ok", None, ) log.update(row, rows=7, truncated=False, elapsed_ms=3.0) (record,) = rows(store) assert (record["rows"], record["truncated"], record["elapsed_ms"]) == (7, 0, 3.0) def test_updating_a_row_that_was_never_written_does_nothing( log: QueryLog, store: Path ) -> None: log.update(None, rows=7) assert not store.exists(), "it did not even open the store" def test_an_error_keeps_its_message(log: QueryLog, store: Path) -> None: log.write("select nope", status="error", error="no such column: nope") (record,) = rows(store) assert record["status"] == "error" assert record["error"] == "no such column: nope" assert record["rows"] is None def test_a_canceled_statement_says_so(log: QueryLog, store: Path) -> None: """A cancelled cursor comes back empty and error-free, so only the caller that cancelled it can tell it from a query that matched nothing.""" row = log.write("select * from big") log.update(row, status="canceled") assert rows(store)[0]["status"] == "canceled" def test_a_record_can_predate_the_store(log: QueryLog, store: Path) -> None: """What a one-time migration out of an older history needs.""" then = datetime.now(timezone.utc) - timedelta(days=30) log.write("select 1", run_at=then) assert datetime.fromisoformat(rows(store)[0]["run_at"]) == then def test_a_registered_secret_never_reaches_the_store(store: Path) -> None: """The store outlives the process, and a query can quote a profile's value.""" hide_secrets_in({"password": SECRET}) log = QueryLog(program="hsql", path=store) log.write( f"select '{SECRET}'", status="error", error=f"could not connect with password {SECRET}", ) (record,) = rows(store) assert SECRET not in record["sql"] assert SECRET not in record["error"] assert REDACTED in record["sql"] @pytest.mark.parametrize( "sql", [ "attach 'postgres://reporting:s3kr3t-unregistered@warehouse:5432/analytics'", "create secret (type s3, key_id 'AKIA0000', secret 's3kr3t-unregistered')", "set s3_secret_access_key = 's3kr3t-unregistered'", ], ) def test_a_credential_typed_into_a_query_never_reaches_the_store( store: Path, sql: str ) -> None: """Nothing registered it, and no option describes it: the store is the only place it would have been written down.""" log = QueryLog(program="hsql", path=store) log.write(sql, status="error", error=f"the database refused: {sql}") (record,) = rows(store) assert "s3kr3t-unregistered" not in record["sql"] assert "s3kr3t-unregistered" not in record["error"] assert REDACTED in record["sql"] def test_a_query_that_carries_no_credential_is_stored_verbatim(store: Path) -> None: """Over-redaction is the safe direction, but not at the cost of the log.""" log = QueryLog(program="hsql", path=store) sql = "select name, token_count from tokens where name = 'alice'" log.write(sql) assert rows(store)[0]["sql"] == sql # --- the schema -------------------------------------------------------------- def test_a_new_store_arrives_at_the_current_version(log: QueryLog, store: Path) -> None: log.write("select 1") db = sqlite3.connect(store) try: assert db.execute("pragma user_version").fetchone()[0] == SCHEMA_VERSION finally: db.close() def test_migrating_from_zero_runs_every_step(store: Path) -> None: """An empty file at `user_version = 0` is what a first run finds.""" store.parent.mkdir(parents=True) sqlite3.connect(store).close() log = QueryLog(program="hsql", path=store) log.write("select 1") assert log.enabled, log.failure assert len(rows(store)) == 1 def test_a_store_already_at_the_current_version_is_left_alone(store: Path) -> None: first = QueryLog(program="hsql", path=store) first.write("select 1") first.close() second = QueryLog(program="harlequin", path=store) second.write("select 2") assert [record["sql"] for record in rows(store)] == ["select 1", "select 2"] def test_a_store_written_by_a_newer_harlequin_is_still_written(store: Path) -> None: """Its columns are a superset of these, so the inserts still name what they mean -- and discarding a history nothing can re-fetch is the wrong answer.""" store.parent.mkdir(parents=True) db = sqlite3.connect(store) for statement in MIGRATIONS[0]: db.execute(statement) db.execute("alter table queries add column something_new text") db.execute(f"pragma user_version = {SCHEMA_VERSION + 1}") db.commit() db.close() log = QueryLog(program="hsql", path=store) log.write("select 1") assert log.failure is None assert len(rows(store)) == 1 def test_retention_trims_from_the_oldest_end( store: Path, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setattr("harlequin.query_log.RETENTION_ROWS", 5) first = QueryLog(program="hsql", path=store) for n in range(8): first.write(f"select {n}") first.close() # trimming is once per process, so it is the next run that finds them assert len(rows(store)) == 8 next_process(monkeypatch) QueryLog(program="hsql", path=store).write("select 8") assert [record["sql"] for record in rows(store)] == [ f"select {n}" for n in range(3, 9) ] def test_retention_keeps_a_store_smaller_than_the_cap_whole( store: Path, monkeypatch: pytest.MonkeyPatch ) -> None: first = QueryLog(program="hsql", path=store) first.write("select 1") first.close() next_process(monkeypatch) QueryLog(program="hsql", path=store).write("select 2") assert len(rows(store)) == 2 def test_a_second_log_on_one_store_does_not_trim_it_again( store: Path, monkeypatch: pytest.MonkeyPatch ) -> None: """What keeps retention off a warm session's per-request path: it opens a log for every request it answers, and the walk a trim costs grows with the store.""" monkeypatch.setattr("harlequin.query_log.RETENTION_ROWS", 5) QueryLog(program="hsql", path=store).write("select 0") trims = 0 real_trim = query_log._trim def counted(db: sqlite3.Connection) -> None: nonlocal trims trims += 1 real_trim(db) monkeypatch.setattr("harlequin.query_log._trim", counted) for n in range(1, 9): QueryLog(program="hsql", path=store).write(f"select {n}") assert trims == 0 # and so the rows over the cap are still there for the next process assert len(rows(store)) == 9 def test_holding_a_log_opens_nothing(store: Path) -> None: """Which is what keeps it off the IDE's start-up path.""" log = QueryLog(program="harlequin", path=store) assert not store.exists() assert log.enabled, "it has not tried yet, so nothing has gone wrong" log.write("select 1") assert store.exists() def test_the_default_store_is_one_file_under_the_state_dir() -> None: """One store, wherever the platform puts a user's state.""" assert default_path().name == "history.db" assert default_path().parent.name == "harlequin" # --- failure never fails a query --------------------------------------------- def test_a_store_that_cannot_be_opened_disables_logging(tmp_path: Path) -> None: blocked = tmp_path / "not-a-directory" blocked.write_text("") log = QueryLog(program="hsql", path=blocked / "history.db") # the write is what opens it, so the write is what discovers it cannot be assert log.write("select 1") is None assert not log.enabled assert log.failure is not None log.update(None) log.close() def test_a_store_that_is_not_a_database_disables_logging(store: Path) -> None: store.parent.mkdir(parents=True) store.write_bytes(b"this is not a SQLite file, it is a note") log = QueryLog(program="hsql", path=store) assert log.write("select 1") is None assert not log.enabled assert log.failure is not None def test_a_write_that_fails_disables_logging_and_does_not_raise( log: QueryLog, store: Path ) -> None: log.write("select 1") db = sqlite3.connect(store) db.execute("drop table queries") db.commit() db.close() assert log.write("select 2") is None assert not log.enabled assert log.failure is not None def test_a_disabled_log_writes_nothing(store: Path) -> None: """`--no-write-history`: a disabled log is a real object whose writes do nothing.""" log = QueryLog(program="hsql", path=store, enabled=False) assert not log.enabled assert log.failure is None assert log.write("select 1") is None assert not store.exists() class _RefusesWal: """A connection that cannot enter WAL, which is a network home directory.""" def __init__(self, db: sqlite3.Connection) -> None: self._db = db def execute(self, sql: str, *args: Any) -> Any: if "journal_mode" in sql: raise sqlite3.OperationalError("unable to open database file") return self._db.execute(sql, *args) def __getattr__(self, name: str) -> Any: return getattr(self._db, name) def __enter__(self) -> Any: return self._db.__enter__() def __exit__(self, *exc: Any) -> Any: return self._db.__exit__(*exc) def test_the_default_journal_still_works( store: Path, monkeypatch: pytest.MonkeyPatch ) -> None: """A store that cannot enter WAL still records every row.""" connect = sqlite3.connect monkeypatch.setattr( "harlequin.query_log.sqlite3.connect", lambda *args, **kwargs: _RefusesWal(connect(*args, **kwargs)), ) log = QueryLog(program="hsql", path=store) log.write("select 1") assert log.enabled, log.failure log.close() monkeypatch.undo() assert len(rows(store)) == 1 def _insert_many(store: str) -> None: log = QueryLog(program="hsql", path=Path(store)) for n in range(100): log.write(f"select {n}") assert log.enabled, log.failure assert log.failure is None, log.failure log.close() @pytest.mark.skipif( sys.platform == "win32", reason="a process pool per test is slow on Windows" ) def test_several_processes_can_write_at_once(store: Path) -> None: """What `busy_timeout` buys, and the reason a second writer is a non-event.""" QueryLog(program="hsql", path=store).close() with ProcessPoolExecutor(max_workers=4) as pool: for future in [pool.submit(_insert_many, str(store)) for _ in range(4)]: future.result() assert len(rows(store)) == 400 # --- adopting what ran before the store -------------------------------------- def adopted(sql: str, *, rows: int | None = 1) -> Record: return Record( sql=sql, run_at=datetime(2026, 8, 1, 9, 30, tzinfo=timezone.utc), rows=rows, elapsed_ms=500.0, ) def test_adopting_writes_the_records_and_says_how_many(store: Path) -> None: moved = adopt( "abc123", [adopted("select 1"), adopted("select 2")], program="harlequin", path=store, ) assert moved == 2 written_rows = rows(store) assert [row["sql"] for row in written_rows] == ["select 1", "select 2"] assert all(row["program"] == "harlequin" for row in written_rows) assert all(row["connection"] == "abc123" for row in written_rows) def test_a_connection_is_adopted_once(store: Path) -> None: """The marker, not the rows, is what says the move already happened.""" assert adopt("abc123", [adopted("select 1")], program="harlequin", path=store) == 1 assert ( adopt("abc123", [adopted("select 1")], program="harlequin", path=store) is None ) assert len(rows(store)) == 1 def test_a_connection_that_has_run_since_is_still_adopted(store: Path) -> None: """A store with rows for this connection is not a store that has adopted it. Both commands write the store under the same key, and only the IDE adopts, so one `hsql` run against a database is all it takes for rows to be there. """ other = QueryLog(program="hsql", connection="abc123", path=store) other.write("select 2") other.close() assert adopt("abc123", [adopted("select 1")], program="harlequin", path=store) == 1 assert sorted(row["sql"] for row in rows(store)) == ["select 1", "select 2"] def test_adopting_nothing_still_claims_the_connection(store: Path) -> None: """An empty history is moved once, rather than looked for forever.""" assert adopt("abc123", [], program="harlequin", path=store) == 0 assert ( adopt("abc123", [adopted("select 1")], program="harlequin", path=store) is None ) def test_a_failed_adoption_leaves_nothing_behind( store: Path, monkeypatch: pytest.MonkeyPatch ) -> None: """One transaction, so the next attempt sees a store it has not touched.""" def explode(sql: str) -> str: if sql == "select 2": raise RuntimeError("boom") return sql monkeypatch.setattr("harlequin.query_log.redact_sql", explode) with pytest.raises(RuntimeError): adopt( "abc123", [adopted("select 1"), adopted("select 2")], program="harlequin", path=store, ) assert rows(store) == [] monkeypatch.undo() assert ( adopt( "abc123", [adopted("select 1"), adopted("select 2")], program="harlequin", path=store, ) == 2 ) assert len(rows(store)) == 2 def test_an_adopted_record_is_redacted(store: Path) -> None: hide_secrets_in({"password": SECRET}) adopt( "abc123", [adopted(f"attach 'dbname=x password={SECRET}'")], program="harlequin", path=store, ) (row,) = rows(store) assert SECRET not in row["sql"] assert REDACTED in row["sql"] def _adopt_one(store: str) -> str: moved = adopt( "abc123", [adopted(f"select {n}") for n in range(200)], program="harlequin", path=Path(store), ) return "claimed" if moved is not None else "skipped" @pytest.mark.skipif( sys.platform == "win32", reason="a process pool per test is slow on Windows" ) def test_only_one_of_several_processes_adopts(store: Path) -> None: """Two panes restoring the same database at login is the ordinary case.""" QueryLog(program="hsql", path=store).close() with ProcessPoolExecutor(max_workers=3) as pool: outcomes = [ f.result() for f in [pool.submit(_adopt_one, str(store)) for _ in range(3)] ] assert sorted(outcomes) == ["claimed", "skipped", "skipped"] assert len(rows(store)) == 200 # --- reading it back --------------------------------------------------------- def written(store: Path, *records: tuple[str, str | None]) -> None: """One row per (sql, connection) pair, in the order given.""" for sql, connection in records: log = QueryLog(program="hsql", connection=connection, path=store) log.write(sql) log.close() def test_recent_returns_the_newest_rows_first(store: Path) -> None: written(store, ("select 1", "a"), ("select 2", "a"), ("select 3", "a")) assert [row[-1] for row in recent(path=store)] == [ "select 3", "select 2", "select 1", ] def test_recent_returns_the_columns_the_history_mode_names(store: Path) -> None: """The listing labels its columns out of one of these and reads the other.""" from harlequin.hsql.modes.history import COLUMNS assert READ_COLUMNS == tuple(name for name, _ in COLUMNS) written(store, ("select 1", "a")) (row,) = recent(path=store) assert len(row) == len(READ_COLUMNS) assert dict(zip(READ_COLUMNS, row, strict=True))["program"] == "hsql" def test_recent_narrows_to_one_connection(store: Path) -> None: written(store, ("select 1", "a"), ("select 2", "b"), ("select 3", "a")) assert [row[-1] for row in recent(connection="a", path=store)] == [ "select 3", "select 1", ] def test_recent_takes_its_limit_from_the_newest_end(store: Path) -> None: written(store, ("select 1", "a"), ("select 2", "a")) assert [row[-1] for row in recent(limit=1, path=store)] == ["select 2"] assert recent(limit=0, path=store) == [] def test_recent_searches_the_sql_wherever_the_term_falls(store: Path) -> None: written(store, ("select * from orders", "a"), ("select 1", "a")) assert [row[-1] for row in recent(search="ORD", path=store)] == [ "select * from orders" ] def test_recent_matches_a_wildcard_in_a_term_literally(store: Path) -> None: """`_` and `%` are `like`'s, and a table name is full of the first.""" written(store, ("select line_items", "a"), ("select lineXitems", "a")) assert [row[-1] for row in recent(search="line_items", path=store)] == [ "select line_items" ] written(store, ("select '100%'", "a"), ("select '100 pct'", "a")) assert [row[-1] for row in recent(search="100%", path=store)] == ["select '100%'"] def test_recent_reads_a_store_that_is_not_there_as_a_history_of_nothing( store: Path, ) -> None: assert recent(path=store) == [] assert not store.exists() def test_recent_reads_a_store_nothing_was_migrated_into_as_empty(store: Path) -> None: """What a store an opener created and then could not build looks like.""" store.parent.mkdir(parents=True) store.touch() assert recent(path=store) == [] def test_recent_raises_for_a_store_that_is_there_and_is_not_a_database( store: Path, ) -> None: """The caller reports it: a history that could not be read is not an empty one, and saying so is the difference between a bug and a blank listing.""" store.parent.mkdir(parents=True) store.write_text("this is not a database") with pytest.raises(sqlite3.Error): recent(path=store) # --- what a connection is keyed by ------------------------------------------- def test_a_declared_connection_id_is_used_as_it_stands() -> None: assert connection_id("postgres://warehouse", ("ignored",), {}) == ( "postgres://warehouse" ) def test_an_adapter_that_declares_nothing_keys_on_its_details() -> None: keyed = connection_id(None, ("my.db",), {"read_only": True}) assert keyed == get_connection_hash(("my.db",), {"read_only": True}) def test_two_tunnels_to_the_same_looking_database_key_differently() -> None: """Both look like `localhost:15439`, and the details cannot tell them apart.""" one = connection_id(None, ("localhost:15439",), {}, through=("bastion_one",)) two = connection_id(None, ("localhost:15439",), {}, through=("bastion_two",)) assert one != two def test_an_untunneled_connection_keys_on_its_details_alone() -> None: assert connection_id(None, ("my.db",), {}, through=()) == get_connection_hash( ("my.db",), {} ) def test_the_programs_offered_are_the_ones_that_write() -> None: """`PROGRAMS` is what a reader offers to filter by, so it has to be every command that writes. The IDE's own spelling is pinned where it writes it, by `test_a_query_is_recorded_as_it_runs`.""" from harlequin.hsql.cli import PROGRAM as HSQL_PROGRAM assert set(PROGRAMS) == {"harlequin", HSQL_PROGRAM} def test_the_retention_cap_matches_the_history_screen() -> None: assert RETENTION_ROWS == 100_000