| 1 |
"""`harlequin.history`: the query log, as the History screen reads it. |
| 2 |
|
| 3 |
One read per screen, and the records it builds are what a human scrolls -- so |
| 4 |
what this pins is the mapping: newest first, the store's UTC in the reader's |
| 5 |
own time zone, and a run whose rows were never counted rendering as something |
| 6 |
rather than as a crash. |
| 7 |
""" |
| 8 |
|
| 9 |
from __future__ import annotations |
| 10 |
|
| 11 |
import sqlite3 |
| 12 |
import sys |
| 13 |
from datetime import datetime, timezone |
| 14 |
from pathlib import Path |
| 15 |
|
| 16 |
import pytest |
| 17 |
from rich.console import Console |
| 18 |
|
| 19 |
from harlequin.history import ( |
| 20 |
MAX_LINES, |
| 21 |
History, |
| 22 |
QueryExecution, |
| 23 |
migrate_pickled_history, |
| 24 |
) |
| 25 |
from harlequin.query_log import QueryLog |
| 26 |
from tests.conftest import LEGACY_HISTORY |
| 27 |
|
| 28 |
|
| 29 |
@pytest.fixture |
| 30 |
def store(query_log_path: Path) -> Path: |
| 31 |
"""The throwaway store every default path in this module already points at.""" |
| 32 |
return query_log_path |
| 33 |
|
| 34 |
|
| 35 |
@pytest.fixture |
| 36 |
def log(store: Path) -> QueryLog: |
| 37 |
return QueryLog(program="harlequin", connection="abc123") |
| 38 |
|
| 39 |
|
| 40 |
def programs(store: Path) -> set[str]: |
| 41 |
"""Which command every row in the store says ran it.""" |
| 42 |
db = sqlite3.connect(store) |
| 43 |
try: |
| 44 |
return {program for (program,) in db.execute("select program from queries")} |
| 45 |
finally: |
| 46 |
db.close() |
| 47 |
|
| 48 |
|
| 49 |
def rendered(record: QueryExecution) -> str: |
| 50 |
console = Console(width=80, no_color=True) |
| 51 |
with console.capture() as capture: |
| 52 |
console.print(record) |
| 53 |
return capture.get() |
| 54 |
|
| 55 |
|
| 56 |
def test_recent_returns_the_newest_queries_first(log: QueryLog) -> None: |
| 57 |
for sql in ("select 1", "select 2", "select 3"): |
| 58 |
log.write(sql, rows=1, elapsed_ms=12.5) |
| 59 |
|
| 60 |
assert [record.query_text for record in History.recent()] == [ |
| 61 |
"select 3", |
| 62 |
"select 2", |
| 63 |
"select 1", |
| 64 |
] |
| 65 |
|
| 66 |
|
| 67 |
def test_recent_reads_only_the_connection_it_was_asked_for(store: Path) -> None: |
| 68 |
"""The screen shows this database's queries, whichever command ran them.""" |
| 69 |
for connection, sql in (("mine", "select 1"), ("theirs", "select 2")): |
| 70 |
other = QueryLog(program="hsql", connection=connection) |
| 71 |
other.write(sql) |
| 72 |
other.close() |
| 73 |
|
| 74 |
assert [record.query_text for record in History.recent(connection="mine")] == [ |
| 75 |
"select 1" |
| 76 |
] |
| 77 |
|
| 78 |
|
| 79 |
def test_recent_takes_its_rows_from_the_newest_end(log: QueryLog) -> None: |
| 80 |
for i in range(10): |
| 81 |
log.write(f"select {i}") |
| 82 |
|
| 83 |
assert [record.query_text for record in History.recent(limit=2)] == [ |
| 84 |
"select 9", |
| 85 |
"select 8", |
| 86 |
] |
| 87 |
|
| 88 |
|
| 89 |
def test_recent_searches_the_stored_sql(log: QueryLog) -> None: |
| 90 |
log.write("select * from line_items") |
| 91 |
log.write("select * from orders") |
| 92 |
|
| 93 |
assert [record.query_text for record in History.recent(search="line_items")] == [ |
| 94 |
"select * from line_items" |
| 95 |
] |
| 96 |
|
| 97 |
|
| 98 |
def test_recent_reads_a_store_that_is_not_there_as_no_history(store: Path) -> None: |
| 99 |
assert not store.exists() |
| 100 |
assert len(History.recent()) == 0 |
| 101 |
|
| 102 |
|
| 103 |
def test_a_record_keeps_what_the_run_it_describes_did(log: QueryLog) -> None: |
| 104 |
log.write("select 1", rows=42, elapsed_ms=1500.0) |
| 105 |
|
| 106 |
(record,) = History.recent() |
| 107 |
assert record.query_text == "select 1" |
| 108 |
assert record.result_row_count == 42 |
| 109 |
# the store keeps milliseconds; a record is rendered in seconds |
| 110 |
assert record.elapsed == 1.5 |
| 111 |
assert record.status == "ok" |
| 112 |
|
| 113 |
|
| 114 |
def test_a_stored_time_is_read_in_the_readers_own_zone(log: QueryLog) -> None: |
| 115 |
"""Both commands write UTC, and a human reads the clock on their wall.""" |
| 116 |
ran_at = datetime(2024, 1, 26, 18, 30, tzinfo=timezone.utc) |
| 117 |
log.write("select 1", run_at=ran_at) |
| 118 |
|
| 119 |
(record,) = History.recent() |
| 120 |
assert record.executed_at == ran_at.astimezone() |
| 121 |
|
| 122 |
|
| 123 |
def test_a_failed_query_renders_as_an_error(log: QueryLog) -> None: |
| 124 |
log.write("sel", status="error", error="Parser Error") |
| 125 |
|
| 126 |
(record,) = History.recent() |
| 127 |
assert record.status == "error" |
| 128 |
assert "ERROR" in rendered(record) |
| 129 |
|
| 130 |
|
| 131 |
def test_a_canceled_query_is_not_an_error(log: QueryLog) -> None: |
| 132 |
"""The distinction the store keeps is one the screen can show.""" |
| 133 |
log.write("select pg_sleep(60)", status="canceled") |
| 134 |
|
| 135 |
(record,) = History.recent() |
| 136 |
assert "CANCELED" in rendered(record) |
| 137 |
|
| 138 |
|
| 139 |
def test_a_query_whose_rows_were_never_counted_still_renders(log: QueryLog) -> None: |
| 140 |
"""DDL, and a session that died between running a query and fetching it.""" |
| 141 |
log.write("create table foo (a int)") |
| 142 |
|
| 143 |
(record,) = History.recent() |
| 144 |
assert record.result_row_count is None |
| 145 |
assert record.elapsed is None |
| 146 |
assert "SUCCESS" in rendered(record) |
| 147 |
|
| 148 |
|
| 149 |
def test_a_long_line_is_ellipsised_rather_than_wrapped(log: QueryLog) -> None: |
| 150 |
"""One line of a query is one line of the row. |
| 151 |
|
| 152 |
A wrapped line grows the row with the query's length, so one query could be |
| 153 |
taller than the pane it is listed in. |
| 154 |
""" |
| 155 |
log.write("select '" + "x" * 5_000 + "'", rows=1, elapsed_ms=12.5) |
| 156 |
|
| 157 |
(record,) = History.recent() |
| 158 |
body = rendered(record).splitlines() |
| 159 |
assert len(body) == 3, "the row grew with the query" |
| 160 |
assert body[1].rstrip().endswith("…") |
| 161 |
|
| 162 |
|
| 163 |
def test_a_row_is_no_taller_than_the_lines_it_shows(log: QueryLog) -> None: |
| 164 |
log.write("\n".join(f"select {i}," for i in range(40)), rows=1, elapsed_ms=12.5) |
| 165 |
|
| 166 |
(record,) = History.recent() |
| 167 |
body = rendered(record).splitlines() |
| 168 |
# the timestamp, MAX_LINES - 1 of the query, the count of what is left, |
| 169 |
# and the blank line that separates one row from the next |
| 170 |
assert len(body) == MAX_LINES + 2 |
| 171 |
assert any("… (33 more lines)" in line for line in body) |
| 172 |
|
| 173 |
|
| 174 |
def test_a_row_with_an_unreadable_timestamp_costs_only_that_row( |
| 175 |
log: QueryLog, store: Path |
| 176 |
) -> None: |
| 177 |
log.write("select 1") |
| 178 |
log.write("select 2") |
| 179 |
db = sqlite3.connect(store) |
| 180 |
with db: |
| 181 |
db.execute("update queries set run_at = 'yesterday' where sql = 'select 2'") |
| 182 |
db.close() |
| 183 |
|
| 184 |
assert [record.query_text for record in History.recent()] == ["select 1"] |
| 185 |
|
| 186 |
|
| 187 |
# --- the one-time move out of the pickle ------------------------------------- |
| 188 |
|
| 189 |
|
| 190 |
def local(ran_at: datetime) -> datetime: |
| 191 |
"""A version-2 timestamp, which was naive local time, as the store reads it.""" |
| 192 |
return ran_at.astimezone() |
| 193 |
|
| 194 |
|
| 195 |
def test_a_pickled_history_moves_into_the_store( |
| 196 |
legacy_history_cache: Path, store: Path |
| 197 |
) -> None: |
| 198 |
assert migrate_pickled_history("abc123") == 2 |
| 199 |
|
| 200 |
records = list(History.recent(connection="abc123")) |
| 201 |
assert [record.query_text for record in records] == ["sel", "select 1"] |
| 202 |
# its own timestamp, from before the store existed, rather than the moment |
| 203 |
# it was moved |
| 204 |
assert records[-1].executed_at == local(LEGACY_HISTORY["abc123"][0][1]) |
| 205 |
assert records[-1].result_row_count == 1 |
| 206 |
assert records[-1].elapsed == 0.5 |
| 207 |
assert records[0].status == "error" |
| 208 |
assert programs(store) == {"harlequin"} |
| 209 |
|
| 210 |
|
| 211 |
def test_a_pickled_history_moves_once(legacy_history_cache: Path, store: Path) -> None: |
| 212 |
assert migrate_pickled_history("abc123") == 2 |
| 213 |
assert migrate_pickled_history("abc123") == 0 |
| 214 |
assert len(History.recent(connection="abc123")) == 2 |
| 215 |
|
| 216 |
|
| 217 |
def test_a_pickled_history_moves_once_across_processes( |
| 218 |
legacy_history_cache: Path, store: Path, monkeypatch: pytest.MonkeyPatch |
| 219 |
) -> None: |
| 220 |
"""The store's marker is what holds, not this process's memory of the move.""" |
| 221 |
assert migrate_pickled_history("abc123") == 2 |
| 222 |
|
| 223 |
monkeypatch.setattr("harlequin.history._migrated", set()) |
| 224 |
assert migrate_pickled_history("abc123") == 0 |
| 225 |
assert len(History.recent(connection="abc123")) == 2 |
| 226 |
|
| 227 |
|
| 228 |
def test_a_connection_hsql_wrote_first_still_gets_its_pickle( |
| 229 |
legacy_history_cache: Path, store: Path |
| 230 |
) -> None: |
| 231 |
"""Both commands key the store alike, and only the IDE moves the pickle. |
| 232 |
|
| 233 |
So rows for this connection are no evidence that the move has happened -- |
| 234 |
one `hsql` run against the database puts them there. |
| 235 |
""" |
| 236 |
agent = QueryLog(program="hsql", connection="abc123") |
| 237 |
agent.write("select * from orders") |
| 238 |
agent.close() |
| 239 |
|
| 240 |
assert migrate_pickled_history("abc123") == 2 |
| 241 |
assert sorted(record.query_text for record in History.recent()) == [ |
| 242 |
"sel", |
| 243 |
"select * from orders", |
| 244 |
"select 1", |
| 245 |
] |
| 246 |
|
| 247 |
|
| 248 |
def test_a_connection_the_cache_does_not_hold_moves_nothing( |
| 249 |
legacy_history_cache: Path, store: Path |
| 250 |
) -> None: |
| 251 |
assert migrate_pickled_history("other") == 0 |
| 252 |
assert len(History.recent()) == 0 |
| 253 |
|
| 254 |
|
| 255 |
def test_there_is_nothing_to_move_without_a_pickle( |
| 256 |
catalog_cache_dir: Path, store: Path |
| 257 |
) -> None: |
| 258 |
assert migrate_pickled_history("abc123") == 0 |
| 259 |
assert not store.exists() |
| 260 |
|
| 261 |
|
| 262 |
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX file modes") |
| 263 |
def test_a_moved_pickle_is_no_longer_readable_by_everyone( |
| 264 |
legacy_history_cache: Path, store: Path |
| 265 |
) -> None: |
| 266 |
"""It holds every statement it recorded, and nothing redacted them.""" |
| 267 |
legacy_history_cache.chmod(0o644) |
| 268 |
|
| 269 |
migrate_pickled_history("abc123") |
| 270 |
|
| 271 |
assert legacy_history_cache.stat().st_mode & 0o077 == 0 |
| 272 |
|
| 273 |
|
| 274 |
def test_a_cache_this_version_cannot_unpickle_is_not_an_error( |
| 275 |
legacy_history_cache: Path, store: Path |
| 276 |
) -> None: |
| 277 |
"""A rename since the file was written must not cost the screen. |
| 278 |
|
| 279 |
The classes a version-2 pickle names are `harlequin.history`'s, so its |
| 280 |
load is the one place this app reads a format an older one wrote. |
| 281 |
""" |
| 282 |
legacy_history_cache.write_bytes( |
| 283 |
legacy_history_cache.read_bytes().replace(b"QueryExecution", b"QueryExecutioZ") |
| 284 |
) |
| 285 |
|
| 286 |
assert migrate_pickled_history("abc123") == 0 |
| 287 |
assert len(History.recent()) == 0 |