Debian Codegraph @

tests/unit_tests/test_query_log.py

raw
1 """`harlequin.query_log`: the store both commands write, and what it promises.
2
3 Three promises, and the tests are grouped by them: a row survives a round trip
4 with its types intact, a schema change is a migration rather than a new file,
5 and nothing here ever fails the query it was recording.
6 """
7
8 from __future__ import annotations
9
10 import sqlite3
11 import sys
12 from concurrent.futures import ProcessPoolExecutor
13 from datetime import datetime, timedelta, timezone
14 from pathlib import Path
15 from typing import Any
16
17 import pytest
18
19 from harlequin import query_log
20 from harlequin.query_log import (
21 MIGRATIONS,
22 PROGRAMS,
23 READ_COLUMNS,
24 RETENTION_ROWS,
25 SCHEMA_VERSION,
26 QueryLog,
27 Record,
28 adopt,
29 connection_id,
30 default_path,
31 get_connection_hash,
32 recent,
33 )
34 from harlequin.redact import REDACTED, hide_secrets_in
35
36 SECRET = "hunter2-and-then-some"
37
38
39 @pytest.fixture
40 def store(tmp_path: Path) -> Path:
41 return tmp_path / "log" / "history.db"
42
43
44 @pytest.fixture
45 def log(store: Path) -> QueryLog:
46 return QueryLog(program="hsql", connection="abc123", path=store)
47
48
49 def next_process(monkeypatch: pytest.MonkeyPatch) -> None:
50 """Forget which stores have been trimmed, as starting a process does."""
51 monkeypatch.setattr("harlequin.query_log._trimmed", set())
52
53
54 def rows(store: Path, columns: str = "*") -> list[dict[str, Any]]:
55 db = sqlite3.connect(store)
56 db.row_factory = sqlite3.Row
57 try:
58 return [
59 dict(row)
60 for row in db.execute(f"select {columns} from queries order by id")
61 ]
62 finally:
63 db.close()
64
65
66 # --- a record ----------------------------------------------------------------
67
68
69 def test_a_row_survives_the_round_trip(log: QueryLog, store: Path) -> None:
70 log.write(
71 "select 1",
72 rows=42,
73 truncated=True,
74 elapsed_ms=12.5,
75 )
76 (record,) = rows(store)
77 assert record["program"] == "hsql"
78 assert record["connection"] == "abc123"
79 assert record["sql"] == "select 1"
80 assert record["status"] == "ok"
81 assert record["rows"] == 42
82 assert record["truncated"] == 1
83 assert record["elapsed_ms"] == 12.5
84 assert record["error"] is None
85 # UTC, ISO-8601, and a value `datetime` reads back
86 assert datetime.fromisoformat(record["run_at"]).tzinfo is not None
87
88
89 def test_a_duration_is_rounded_to_microseconds(log: QueryLog, store: Path) -> None:
90 """A double's sixteen digits are noise in a column a person reads, and the
91 value is written once and printed every time the history is."""
92 row = log.write("select 1", elapsed_ms=0.013326999976470688)
93 (record,) = rows(store)
94 assert record["elapsed_ms"] == 0.013
95
96 log.update(row, elapsed_ms=1234.56789)
97 (record,) = rows(store)
98 assert record["elapsed_ms"] == 1234.568
99
100
101 def test_a_statement_is_recorded_before_its_rows_are_known(
102 log: QueryLog, store: Path
103 ) -> None:
104 """Which is what a session killed mid-fetch keeps."""
105 row = log.write("select 1")
106 (written,) = rows(store)
107 assert (written["sql"], written["status"], written["rows"]) == (
108 "select 1",
109 "ok",
110 None,
111 )
112
113 log.update(row, rows=7, truncated=False, elapsed_ms=3.0)
114 (record,) = rows(store)
115 assert (record["rows"], record["truncated"], record["elapsed_ms"]) == (7, 0, 3.0)
116
117
118 def test_updating_a_row_that_was_never_written_does_nothing(
119 log: QueryLog, store: Path
120 ) -> None:
121 log.update(None, rows=7)
122 assert not store.exists(), "it did not even open the store"
123
124
125 def test_an_error_keeps_its_message(log: QueryLog, store: Path) -> None:
126 log.write("select nope", status="error", error="no such column: nope")
127 (record,) = rows(store)
128 assert record["status"] == "error"
129 assert record["error"] == "no such column: nope"
130 assert record["rows"] is None
131
132
133 def test_a_canceled_statement_says_so(log: QueryLog, store: Path) -> None:
134 """A cancelled cursor comes back empty and error-free, so only the caller
135 that cancelled it can tell it from a query that matched nothing."""
136 row = log.write("select * from big")
137 log.update(row, status="canceled")
138 assert rows(store)[0]["status"] == "canceled"
139
140
141 def test_a_record_can_predate_the_store(log: QueryLog, store: Path) -> None:
142 """What a one-time migration out of an older history needs."""
143 then = datetime.now(timezone.utc) - timedelta(days=30)
144 log.write("select 1", run_at=then)
145 assert datetime.fromisoformat(rows(store)[0]["run_at"]) == then
146
147
148 def test_a_registered_secret_never_reaches_the_store(store: Path) -> None:
149 """The store outlives the process, and a query can quote a profile's value."""
150 hide_secrets_in({"password": SECRET})
151 log = QueryLog(program="hsql", path=store)
152 log.write(
153 f"select '{SECRET}'",
154 status="error",
155 error=f"could not connect with password {SECRET}",
156 )
157 (record,) = rows(store)
158 assert SECRET not in record["sql"]
159 assert SECRET not in record["error"]
160 assert REDACTED in record["sql"]
161
162
163 @pytest.mark.parametrize(
164 "sql",
165 [
166 "attach 'postgres://reporting:s3kr3t-unregistered@warehouse:5432/analytics'",
167 "create secret (type s3, key_id 'AKIA0000', secret 's3kr3t-unregistered')",
168 "set s3_secret_access_key = 's3kr3t-unregistered'",
169 ],
170 )
171 def test_a_credential_typed_into_a_query_never_reaches_the_store(
172 store: Path, sql: str
173 ) -> None:
174 """Nothing registered it, and no option describes it: the store is the only
175 place it would have been written down."""
176 log = QueryLog(program="hsql", path=store)
177 log.write(sql, status="error", error=f"the database refused: {sql}")
178 (record,) = rows(store)
179 assert "s3kr3t-unregistered" not in record["sql"]
180 assert "s3kr3t-unregistered" not in record["error"]
181 assert REDACTED in record["sql"]
182
183
184 def test_a_query_that_carries_no_credential_is_stored_verbatim(store: Path) -> None:
185 """Over-redaction is the safe direction, but not at the cost of the log."""
186 log = QueryLog(program="hsql", path=store)
187 sql = "select name, token_count from tokens where name = 'alice'"
188 log.write(sql)
189 assert rows(store)[0]["sql"] == sql
190
191
192 # --- the schema --------------------------------------------------------------
193
194
195 def test_a_new_store_arrives_at_the_current_version(log: QueryLog, store: Path) -> None:
196 log.write("select 1")
197 db = sqlite3.connect(store)
198 try:
199 assert db.execute("pragma user_version").fetchone()[0] == SCHEMA_VERSION
200 finally:
201 db.close()
202
203
204 def test_migrating_from_zero_runs_every_step(store: Path) -> None:
205 """An empty file at `user_version = 0` is what a first run finds."""
206 store.parent.mkdir(parents=True)
207 sqlite3.connect(store).close()
208 log = QueryLog(program="hsql", path=store)
209 log.write("select 1")
210 assert log.enabled, log.failure
211 assert len(rows(store)) == 1
212
213
214 def test_a_store_already_at_the_current_version_is_left_alone(store: Path) -> None:
215 first = QueryLog(program="hsql", path=store)
216 first.write("select 1")
217 first.close()
218
219 second = QueryLog(program="harlequin", path=store)
220 second.write("select 2")
221 assert [record["sql"] for record in rows(store)] == ["select 1", "select 2"]
222
223
224 def test_a_store_written_by_a_newer_harlequin_is_still_written(store: Path) -> None:
225 """Its columns are a superset of these, so the inserts still name what they
226 mean -- and discarding a history nothing can re-fetch is the wrong answer."""
227 store.parent.mkdir(parents=True)
228 db = sqlite3.connect(store)
229 for statement in MIGRATIONS[0]:
230 db.execute(statement)
231 db.execute("alter table queries add column something_new text")
232 db.execute(f"pragma user_version = {SCHEMA_VERSION + 1}")
233 db.commit()
234 db.close()
235
236 log = QueryLog(program="hsql", path=store)
237 log.write("select 1")
238 assert log.failure is None
239 assert len(rows(store)) == 1
240
241
242 def test_retention_trims_from_the_oldest_end(
243 store: Path, monkeypatch: pytest.MonkeyPatch
244 ) -> None:
245 monkeypatch.setattr("harlequin.query_log.RETENTION_ROWS", 5)
246 first = QueryLog(program="hsql", path=store)
247 for n in range(8):
248 first.write(f"select {n}")
249 first.close()
250
251 # trimming is once per process, so it is the next run that finds them
252 assert len(rows(store)) == 8
253 next_process(monkeypatch)
254 QueryLog(program="hsql", path=store).write("select 8")
255 assert [record["sql"] for record in rows(store)] == [
256 f"select {n}" for n in range(3, 9)
257 ]
258
259
260 def test_retention_keeps_a_store_smaller_than_the_cap_whole(
261 store: Path, monkeypatch: pytest.MonkeyPatch
262 ) -> None:
263 first = QueryLog(program="hsql", path=store)
264 first.write("select 1")
265 first.close()
266 next_process(monkeypatch)
267 QueryLog(program="hsql", path=store).write("select 2")
268 assert len(rows(store)) == 2
269
270
271 def test_a_second_log_on_one_store_does_not_trim_it_again(
272 store: Path, monkeypatch: pytest.MonkeyPatch
273 ) -> None:
274 """What keeps retention off a warm session's per-request path: it opens a
275 log for every request it answers, and the walk a trim costs grows with the
276 store."""
277 monkeypatch.setattr("harlequin.query_log.RETENTION_ROWS", 5)
278 QueryLog(program="hsql", path=store).write("select 0")
279 trims = 0
280 real_trim = query_log._trim
281
282 def counted(db: sqlite3.Connection) -> None:
283 nonlocal trims
284 trims += 1
285 real_trim(db)
286
287 monkeypatch.setattr("harlequin.query_log._trim", counted)
288 for n in range(1, 9):
289 QueryLog(program="hsql", path=store).write(f"select {n}")
290 assert trims == 0
291 # and so the rows over the cap are still there for the next process
292 assert len(rows(store)) == 9
293
294
295 def test_holding_a_log_opens_nothing(store: Path) -> None:
296 """Which is what keeps it off the IDE's start-up path."""
297 log = QueryLog(program="harlequin", path=store)
298 assert not store.exists()
299 assert log.enabled, "it has not tried yet, so nothing has gone wrong"
300
301 log.write("select 1")
302 assert store.exists()
303
304
305 def test_the_default_store_is_one_file_under_the_state_dir() -> None:
306 """One store, wherever the platform puts a user's state."""
307 assert default_path().name == "history.db"
308 assert default_path().parent.name == "harlequin"
309
310
311 # --- failure never fails a query ---------------------------------------------
312
313
314 def test_a_store_that_cannot_be_opened_disables_logging(tmp_path: Path) -> None:
315 blocked = tmp_path / "not-a-directory"
316 blocked.write_text("")
317 log = QueryLog(program="hsql", path=blocked / "history.db")
318 # the write is what opens it, so the write is what discovers it cannot be
319 assert log.write("select 1") is None
320 assert not log.enabled
321 assert log.failure is not None
322 log.update(None)
323 log.close()
324
325
326 def test_a_store_that_is_not_a_database_disables_logging(store: Path) -> None:
327 store.parent.mkdir(parents=True)
328 store.write_bytes(b"this is not a SQLite file, it is a note")
329 log = QueryLog(program="hsql", path=store)
330 assert log.write("select 1") is None
331 assert not log.enabled
332 assert log.failure is not None
333
334
335 def test_a_write_that_fails_disables_logging_and_does_not_raise(
336 log: QueryLog, store: Path
337 ) -> None:
338 log.write("select 1")
339 db = sqlite3.connect(store)
340 db.execute("drop table queries")
341 db.commit()
342 db.close()
343
344 assert log.write("select 2") is None
345 assert not log.enabled
346 assert log.failure is not None
347
348
349 def test_a_disabled_log_writes_nothing(store: Path) -> None:
350 """`--no-write-history`: a disabled log is a real object whose writes do
351 nothing."""
352 log = QueryLog(program="hsql", path=store, enabled=False)
353 assert not log.enabled
354 assert log.failure is None
355 assert log.write("select 1") is None
356 assert not store.exists()
357
358
359 class _RefusesWal:
360 """A connection that cannot enter WAL, which is a network home directory."""
361
362 def __init__(self, db: sqlite3.Connection) -> None:
363 self._db = db
364
365 def execute(self, sql: str, *args: Any) -> Any:
366 if "journal_mode" in sql:
367 raise sqlite3.OperationalError("unable to open database file")
368 return self._db.execute(sql, *args)
369
370 def __getattr__(self, name: str) -> Any:
371 return getattr(self._db, name)
372
373 def __enter__(self) -> Any:
374 return self._db.__enter__()
375
376 def __exit__(self, *exc: Any) -> Any:
377 return self._db.__exit__(*exc)
378
379
380 def test_the_default_journal_still_works(
381 store: Path, monkeypatch: pytest.MonkeyPatch
382 ) -> None:
383 """A store that cannot enter WAL still records every row."""
384 connect = sqlite3.connect
385 monkeypatch.setattr(
386 "harlequin.query_log.sqlite3.connect",
387 lambda *args, **kwargs: _RefusesWal(connect(*args, **kwargs)),
388 )
389 log = QueryLog(program="hsql", path=store)
390 log.write("select 1")
391 assert log.enabled, log.failure
392 log.close()
393 monkeypatch.undo()
394 assert len(rows(store)) == 1
395
396
397 def _insert_many(store: str) -> None:
398 log = QueryLog(program="hsql", path=Path(store))
399 for n in range(100):
400 log.write(f"select {n}")
401 assert log.enabled, log.failure
402 assert log.failure is None, log.failure
403 log.close()
404
405
406 @pytest.mark.skipif(
407 sys.platform == "win32", reason="a process pool per test is slow on Windows"
408 )
409 def test_several_processes_can_write_at_once(store: Path) -> None:
410 """What `busy_timeout` buys, and the reason a second writer is a non-event."""
411 QueryLog(program="hsql", path=store).close()
412 with ProcessPoolExecutor(max_workers=4) as pool:
413 for future in [pool.submit(_insert_many, str(store)) for _ in range(4)]:
414 future.result()
415 assert len(rows(store)) == 400
416
417
418 # --- adopting what ran before the store --------------------------------------
419
420
421 def adopted(sql: str, *, rows: int | None = 1) -> Record:
422 return Record(
423 sql=sql,
424 run_at=datetime(2026, 8, 1, 9, 30, tzinfo=timezone.utc),
425 rows=rows,
426 elapsed_ms=500.0,
427 )
428
429
430 def test_adopting_writes_the_records_and_says_how_many(store: Path) -> None:
431 moved = adopt(
432 "abc123",
433 [adopted("select 1"), adopted("select 2")],
434 program="harlequin",
435 path=store,
436 )
437
438 assert moved == 2
439 written_rows = rows(store)
440 assert [row["sql"] for row in written_rows] == ["select 1", "select 2"]
441 assert all(row["program"] == "harlequin" for row in written_rows)
442 assert all(row["connection"] == "abc123" for row in written_rows)
443
444
445 def test_a_connection_is_adopted_once(store: Path) -> None:
446 """The marker, not the rows, is what says the move already happened."""
447 assert adopt("abc123", [adopted("select 1")], program="harlequin", path=store) == 1
448 assert (
449 adopt("abc123", [adopted("select 1")], program="harlequin", path=store) is None
450 )
451 assert len(rows(store)) == 1
452
453
454 def test_a_connection_that_has_run_since_is_still_adopted(store: Path) -> None:
455 """A store with rows for this connection is not a store that has adopted it.
456
457 Both commands write the store under the same key, and only the IDE adopts,
458 so one `hsql` run against a database is all it takes for rows to be there.
459 """
460 other = QueryLog(program="hsql", connection="abc123", path=store)
461 other.write("select 2")
462 other.close()
463
464 assert adopt("abc123", [adopted("select 1")], program="harlequin", path=store) == 1
465 assert sorted(row["sql"] for row in rows(store)) == ["select 1", "select 2"]
466
467
468 def test_adopting_nothing_still_claims_the_connection(store: Path) -> None:
469 """An empty history is moved once, rather than looked for forever."""
470 assert adopt("abc123", [], program="harlequin", path=store) == 0
471 assert (
472 adopt("abc123", [adopted("select 1")], program="harlequin", path=store) is None
473 )
474
475
476 def test_a_failed_adoption_leaves_nothing_behind(
477 store: Path, monkeypatch: pytest.MonkeyPatch
478 ) -> None:
479 """One transaction, so the next attempt sees a store it has not touched."""
480
481 def explode(sql: str) -> str:
482 if sql == "select 2":
483 raise RuntimeError("boom")
484 return sql
485
486 monkeypatch.setattr("harlequin.query_log.redact_sql", explode)
487 with pytest.raises(RuntimeError):
488 adopt(
489 "abc123",
490 [adopted("select 1"), adopted("select 2")],
491 program="harlequin",
492 path=store,
493 )
494 assert rows(store) == []
495
496 monkeypatch.undo()
497 assert (
498 adopt(
499 "abc123",
500 [adopted("select 1"), adopted("select 2")],
501 program="harlequin",
502 path=store,
503 )
504 == 2
505 )
506 assert len(rows(store)) == 2
507
508
509 def test_an_adopted_record_is_redacted(store: Path) -> None:
510 hide_secrets_in({"password": SECRET})
511 adopt(
512 "abc123",
513 [adopted(f"attach 'dbname=x password={SECRET}'")],
514 program="harlequin",
515 path=store,
516 )
517
518 (row,) = rows(store)
519 assert SECRET not in row["sql"]
520 assert REDACTED in row["sql"]
521
522
523 def _adopt_one(store: str) -> str:
524 moved = adopt(
525 "abc123",
526 [adopted(f"select {n}") for n in range(200)],
527 program="harlequin",
528 path=Path(store),
529 )
530 return "claimed" if moved is not None else "skipped"
531
532
533 @pytest.mark.skipif(
534 sys.platform == "win32", reason="a process pool per test is slow on Windows"
535 )
536 def test_only_one_of_several_processes_adopts(store: Path) -> None:
537 """Two panes restoring the same database at login is the ordinary case."""
538 QueryLog(program="hsql", path=store).close()
539 with ProcessPoolExecutor(max_workers=3) as pool:
540 outcomes = [
541 f.result() for f in [pool.submit(_adopt_one, str(store)) for _ in range(3)]
542 ]
543
544 assert sorted(outcomes) == ["claimed", "skipped", "skipped"]
545 assert len(rows(store)) == 200
546
547
548 # --- reading it back ---------------------------------------------------------
549
550
551 def written(store: Path, *records: tuple[str, str | None]) -> None:
552 """One row per (sql, connection) pair, in the order given."""
553 for sql, connection in records:
554 log = QueryLog(program="hsql", connection=connection, path=store)
555 log.write(sql)
556 log.close()
557
558
559 def test_recent_returns_the_newest_rows_first(store: Path) -> None:
560 written(store, ("select 1", "a"), ("select 2", "a"), ("select 3", "a"))
561 assert [row[-1] for row in recent(path=store)] == [
562 "select 3",
563 "select 2",
564 "select 1",
565 ]
566
567
568 def test_recent_returns_the_columns_the_history_mode_names(store: Path) -> None:
569 """The listing labels its columns out of one of these and reads the other."""
570 from harlequin.hsql.modes.history import COLUMNS
571
572 assert READ_COLUMNS == tuple(name for name, _ in COLUMNS)
573 written(store, ("select 1", "a"))
574 (row,) = recent(path=store)
575 assert len(row) == len(READ_COLUMNS)
576 assert dict(zip(READ_COLUMNS, row, strict=True))["program"] == "hsql"
577
578
579 def test_recent_narrows_to_one_connection(store: Path) -> None:
580 written(store, ("select 1", "a"), ("select 2", "b"), ("select 3", "a"))
581 assert [row[-1] for row in recent(connection="a", path=store)] == [
582 "select 3",
583 "select 1",
584 ]
585
586
587 def test_recent_takes_its_limit_from_the_newest_end(store: Path) -> None:
588 written(store, ("select 1", "a"), ("select 2", "a"))
589 assert [row[-1] for row in recent(limit=1, path=store)] == ["select 2"]
590 assert recent(limit=0, path=store) == []
591
592
593 def test_recent_searches_the_sql_wherever_the_term_falls(store: Path) -> None:
594 written(store, ("select * from orders", "a"), ("select 1", "a"))
595 assert [row[-1] for row in recent(search="ORD", path=store)] == [
596 "select * from orders"
597 ]
598
599
600 def test_recent_matches_a_wildcard_in_a_term_literally(store: Path) -> None:
601 """`_` and `%` are `like`'s, and a table name is full of the first."""
602 written(store, ("select line_items", "a"), ("select lineXitems", "a"))
603 assert [row[-1] for row in recent(search="line_items", path=store)] == [
604 "select line_items"
605 ]
606 written(store, ("select '100%'", "a"), ("select '100 pct'", "a"))
607 assert [row[-1] for row in recent(search="100%", path=store)] == ["select '100%'"]
608
609
610 def test_recent_reads_a_store_that_is_not_there_as_a_history_of_nothing(
611 store: Path,
612 ) -> None:
613 assert recent(path=store) == []
614 assert not store.exists()
615
616
617 def test_recent_reads_a_store_nothing_was_migrated_into_as_empty(store: Path) -> None:
618 """What a store an opener created and then could not build looks like."""
619 store.parent.mkdir(parents=True)
620 store.touch()
621 assert recent(path=store) == []
622
623
624 def test_recent_raises_for_a_store_that_is_there_and_is_not_a_database(
625 store: Path,
626 ) -> None:
627 """The caller reports it: a history that could not be read is not an empty
628 one, and saying so is the difference between a bug and a blank listing."""
629 store.parent.mkdir(parents=True)
630 store.write_text("this is not a database")
631 with pytest.raises(sqlite3.Error):
632 recent(path=store)
633
634
635 # --- what a connection is keyed by -------------------------------------------
636
637
638 def test_a_declared_connection_id_is_used_as_it_stands() -> None:
639 assert connection_id("postgres://warehouse", ("ignored",), {}) == (
640 "postgres://warehouse"
641 )
642
643
644 def test_an_adapter_that_declares_nothing_keys_on_its_details() -> None:
645 keyed = connection_id(None, ("my.db",), {"read_only": True})
646 assert keyed == get_connection_hash(("my.db",), {"read_only": True})
647
648
649 def test_two_tunnels_to_the_same_looking_database_key_differently() -> None:
650 """Both look like `localhost:15439`, and the details cannot tell them apart."""
651 one = connection_id(None, ("localhost:15439",), {}, through=("bastion_one",))
652 two = connection_id(None, ("localhost:15439",), {}, through=("bastion_two",))
653 assert one != two
654
655
656 def test_an_untunneled_connection_keys_on_its_details_alone() -> None:
657 assert connection_id(None, ("my.db",), {}, through=()) == get_connection_hash(
658 ("my.db",), {}
659 )
660
661
662 def test_the_programs_offered_are_the_ones_that_write() -> None:
663 """`PROGRAMS` is what a reader offers to filter by, so it has to be every
664 command that writes. The IDE's own spelling is pinned where it writes it,
665 by `test_a_query_is_recorded_as_it_runs`."""
666 from harlequin.hsql.cli import PROGRAM as HSQL_PROGRAM
667
668 assert set(PROGRAMS) == {"harlequin", HSQL_PROGRAM}
669
670
671 def test_the_retention_cap_matches_the_history_screen() -> None:
672 assert RETENTION_ROWS == 100_000