Debian Codegraph @

tests/unit_tests/test_hsql.py

raw
1 """hsql's contract: what lands on stdout, what lands on stderr, and the code.
2
3 The output format and the exit codes are the part of hsql that is an API, so
4 most of what is asserted here is a promise rather than an implementation: that
5 stdout carries data and only data, that a truncated result says so, that the
6 same query renders the same bytes wherever it is run.
7 """
8
9 from __future__ import annotations
10
11 import json
12 import subprocess
13 import sys
14 import threading
15 from pathlib import Path
16 from typing import Any, Callable, Sequence, cast
17 from unittest.mock import MagicMock
18
19 import click
20 import pytest
21 from click.testing import CliRunner, Result
22
23 from harlequin.exception import (
24 HarlequinConfigError,
25 HarlequinConnectionError,
26 HarlequinCopyError,
27 HarlequinQueryError,
28 )
29 from harlequin.hsql.cli import PROGRAM, build_cli
30 from harlequin.hsql.diagnostics import IDE_THEMES, ExitCode, exit_code_for
31 from harlequin.hsql.modes import CONFIG_MODES
32
33 Hsql = Callable[..., Result]
34
35 TEN_ROWS = (
36 "with recursive t(n) as ("
37 "select 1 union all select n + 1 from t where n < 10"
38 ") select n from t"
39 )
40 """Ten rows, in a spelling both bundled adapters accept."""
41
42 HUNDRED_ROWS = TEN_ROWS.replace("n < 10", "n < 100")
43 """More rows than any layout prints by default, and fewer than --limit fetches."""
44
45 LAYOUTS = ["table", "markdown", "md", "vertical"]
46 TEXT_FILES = ["csv", "tsv", "json", "jsonl", "ndjson"]
47 BINARY_FILES = ["parquet", "orc", "arrow"]
48 FILE_FORMATS = TEXT_FILES + BINARY_FILES
49
50
51 @pytest.fixture
52 def hsql(no_discovered_config: None) -> Hsql:
53 """Invoke hsql the way the console script does, in process."""
54 runner = CliRunner()
55
56 def _run(*args: str, **kwargs: Any) -> Result:
57 argv = [str(arg) for arg in args]
58 return runner.invoke(build_cli(argv), argv, catch_exceptions=False, **kwargs)
59
60 return _run
61
62
63 @pytest.fixture
64 def duck() -> list[str]:
65 """The arguments that get a hermetic in-memory DuckDB."""
66 return ["-a", "duckdb", "--no-init", ":memory:"]
67
68
69 @pytest.fixture(params=["duckdb", "sqlite"])
70 def both_adapters(request: pytest.FixtureRequest) -> list[str]:
71 return ["-a", request.param, "--no-init", ":memory:"]
72
73
74 # --- help, and what it costs -------------------------------------------------
75
76
77 def test_help_is_adapter_agnostic(hsql: Hsql) -> None:
78 res = hsql("--help")
79 assert res.exit_code == ExitCode.OK
80 assert "Formats:" in res.output
81 assert "Exit codes:" in res.output
82 assert "Installed adapters:" in res.output
83 assert "hsql --help -a <adapter>" in res.output
84 # no adapter's connection options, and none of the IDE's options either
85 assert "--no-init" not in res.output
86 assert "--theme" not in res.output
87 assert "--show-files" not in res.output
88
89
90 def test_help_for_one_adapter(hsql: Hsql) -> None:
91 res = hsql("--help", "-a", "duckdb")
92 assert res.exit_code == ExitCode.OK
93 assert "--no-init" in res.output
94 assert "Showing duckdb's connection options." in res.output
95
96
97 def test_bare_invocation_prints_help_and_leaves_stdout_empty(hsql: Hsql) -> None:
98 """An invocation with nothing to run is a usage error, not a result.
99
100 Putting the help on stdout would mean `hsql | ...` could carry help text
101 where data belongs, which is the one thing stdout is not allowed to do.
102 """
103 res = hsql()
104 assert res.exit_code == ExitCode.USAGE
105 assert res.stdout == ""
106 assert "Usage:" in res.stderr
107
108
109 def test_no_sql_to_run(hsql: Hsql, duck: list[str]) -> None:
110 res = hsql(*duck)
111 assert res.exit_code == ExitCode.USAGE
112 assert res.stdout == ""
113 assert "no SQL to run" in res.stderr
114
115
116 # --- the shapes of output ----------------------------------------------------
117
118
119 def test_select_1(hsql: Hsql, duck: list[str]) -> None:
120 res = hsql(*duck, "-c", "select 1 as a")
121 assert res.exit_code == ExitCode.OK
122 assert res.stdout == " a\n---\n 1\n(1 row)\n"
123 # the count is the footer's job. A run with nothing to warn about writes
124 # nothing at all to stderr.
125 assert res.stderr == ""
126
127
128 def test_the_tac_idiom(hsql: Hsql, duck: list[str]) -> None:
129 """`-tAc` capturing a scalar is the first thing a script will try."""
130 res = hsql(*duck, "-tAc", "select 42")
131 assert res.exit_code == ExitCode.OK
132 assert res.stdout == "42\n"
133
134
135 @pytest.mark.parametrize(
136 "args,expected",
137 [
138 ([], " a\n---\n 1\n(1 row)\n"),
139 (["-t"], " 1\n"),
140 (["-A"], "a\n1\n(1 row)\n"),
141 (["--no-header"], " 1\n(1 row)\n"),
142 (["--no-footer"], " a\n---\n 1\n"),
143 (["--no-header", "--no-footer"], " 1\n"),
144 (["-tA"], "1\n"),
145 ],
146 )
147 def test_psql_flag_algebra(
148 hsql: Hsql, duck: list[str], args: list[str], expected: str
149 ) -> None:
150 """`-t` and `-A` are independent switches, so `-tA` is not a special case.
151
152 `--no-header --no-footer` is `-t` spelled out, and has to agree with it.
153 """
154 res = hsql(*duck, *args, "-c", "select 1 as a")
155 assert res.exit_code == ExitCode.OK
156 assert res.stdout == expected
157
158
159 @pytest.mark.parametrize("format_name", LAYOUTS + FILE_FORMATS + ["none"])
160 def test_every_format_runs(hsql: Hsql, duck: list[str], format_name: str) -> None:
161 res = hsql(*duck, "--format", format_name, "-c", "select 1 as a, null as b")
162 assert res.exit_code == ExitCode.OK
163 assert bool(res.stdout_bytes) is (format_name != "none")
164
165
166 @pytest.mark.parametrize(
167 "flag,format_name",
168 [
169 ("--csv", "csv"),
170 ("--json", "json"),
171 ("--jsonl", "jsonl"),
172 ("--markdown", "markdown"),
173 ("--vertical", "vertical"),
174 ("-x", "vertical"),
175 ],
176 )
177 def test_format_shorthands(
178 hsql: Hsql, duck: list[str], flag: str, format_name: str
179 ) -> None:
180 sql = "select 1 as a"
181 assert (
182 hsql(*duck, flag, "-c", sql).stdout_bytes
183 == hsql(*duck, "--format", format_name, "-c", sql).stdout_bytes
184 )
185
186
187 @pytest.mark.parametrize(
188 "args",
189 [["--csv", "--json"], ["--csv", "--format", "json"], ["--format", "json", "--csv"]],
190 )
191 def test_two_formats_is_a_usage_error(
192 hsql: Hsql, duck: list[str], args: list[str]
193 ) -> None:
194 res = hsql(*duck, *args, "-c", "select 1")
195 assert res.exit_code == ExitCode.USAGE
196 assert res.stdout == ""
197 assert res.stderr.startswith("hsql: error: ")
198
199
200 def test_null_string(hsql: Hsql, duck: list[str]) -> None:
201 assert " NULL\n" in hsql(*duck, "-c", "select null as a").stdout
202 assert " ∅\n" in hsql(*duck, "--null-string", "∅", "-c", "select null as a").stdout
203 # csv renders a null as nothing at all unless told otherwise
204 assert hsql(*duck, "--csv", "-c", "select null as a").stdout == "a\n\n"
205 assert (
206 hsql(*duck, "--csv", "--null-string", "∅", "-c", "select null as a").stdout
207 == "a\n∅\n"
208 )
209
210
211 def test_zero_rows_is_not_an_error(hsql: Hsql, duck: list[str]) -> None:
212 """A0 vs A3: "matched nothing" has to be distinguishable from "failed"."""
213 res = hsql(*duck, "--csv", "--stats", "-c", "select 1 as a where false")
214 assert res.exit_code == ExitCode.OK
215 assert res.stdout == "a\n"
216 assert json.loads(res.stderr.splitlines()[-1])["rows"] == 0
217
218
219 # --- stdout is data ----------------------------------------------------------
220
221
222 @pytest.mark.parametrize("format_name", LAYOUTS + FILE_FORMATS)
223 def test_stats_does_not_touch_stdout(
224 hsql: Hsql, duck: list[str], format_name: str
225 ) -> None:
226 sql = "select 1 as a, 'x' as b"
227 plain = hsql(*duck, "--format", format_name, "-c", sql)
228 with_stats = hsql(*duck, "--format", format_name, "--stats", "-c", sql)
229 assert plain.stdout_bytes == with_stats.stdout_bytes
230 assert with_stats.stderr != plain.stderr
231
232
233 def test_stats_payload(hsql: Hsql, duck: list[str]) -> None:
234 res = hsql(*duck, "--format", "none", "--stats", "--limit", "3", "-c", TEN_ROWS)
235 payload = json.loads(res.stderr.splitlines()[-1])
236 assert payload == {
237 "status": "ok",
238 "statements": 1,
239 "rows": 3,
240 "truncated": True,
241 "limit": 3,
242 "elapsed_ms": payload["elapsed_ms"],
243 "columns": [{"name": "n", "type": payload["columns"][0]["type"]}],
244 }
245
246
247 def test_stats_reports_a_failure(hsql: Hsql, duck: list[str]) -> None:
248 res = hsql(*duck, "--stats", "-c", "select from nowhere")
249 payload = json.loads(res.stderr.splitlines()[-1])
250 assert payload["status"] == "error"
251 assert payload["rows"] == 0
252 assert payload["error"]
253
254
255 def test_a_query_error_leaves_stdout_empty(hsql: Hsql, duck: list[str]) -> None:
256 res = hsql(*duck, "-c", "select * from no_such_table")
257 assert res.exit_code == ExitCode.QUERY
258 assert res.stdout == ""
259 assert res.stderr.startswith("hsql: error: ")
260 # plain: no panel, no box drawing, no ANSI
261 assert "─" not in res.stderr
262 assert "\x1b[" not in res.stderr
263
264
265 # --- truncation --------------------------------------------------------------
266
267
268 @pytest.mark.parametrize(
269 "limit,rows,truncated", [(20, 10, False), (10, 10, False), (3, 3, True)]
270 )
271 def test_truncation(
272 hsql: Hsql, both_adapters: list[str], limit: int, rows: int, truncated: bool
273 ) -> None:
274 """Exactly at the limit is the ambiguous case, and the reason for limit+1."""
275 res = hsql(*both_adapters, "--limit", str(limit), "-c", TEN_ROWS)
276 assert res.exit_code == ExitCode.OK
277 body = res.stdout.splitlines()[2:-1] # between the rule and the footer
278 assert len(body) == rows
279 assert ("truncated" in res.stderr) is truncated
280 assert (f"({rows} of >{rows} rows)" in res.stdout) is truncated
281
282
283 def test_one_truncated_row_is_still_rows(hsql: Hsql, duck: list[str]) -> None:
284 """`-l 1` is where the count and the noun disagree.
285
286 One row was kept, and the limit+1 fetch proved there is another, so the
287 total the noun has to agree with is at least two.
288 """
289 res = hsql(*duck, "--limit", "1", "-c", TEN_ROWS)
290 assert "(1 of >1 rows)" in res.stdout
291
292
293 def test_no_limit_counts_exactly(hsql: Hsql, duck: list[str]) -> None:
294 res = hsql(*duck, "--limit", "-1", "--stats", "--format", "none", "-c", TEN_ROWS)
295 payload = json.loads(res.stderr.splitlines()[-1])
296 assert payload["rows"] == 10
297 assert payload["truncated"] is False
298 assert payload["limit"] is None
299
300
301 def test_limit_zero_fetches_a_header_and_no_rows(
302 hsql: Hsql, both_adapters: list[str]
303 ) -> None:
304 """`limit 0` is how a caller asks what a query's columns are.
305
306 So 0 is zero rows, and -1 is the spelling for "all of them" -- the reverse
307 would spend the idiom on a synonym for a flag that already exists.
308 """
309 res = hsql(*both_adapters, "--limit", "0", "-c", TEN_ROWS)
310 assert res.exit_code == ExitCode.OK
311 lines = res.stdout.splitlines()
312 assert lines[0].strip() == "n"
313 assert lines[-1] == "(0 of >0 rows)"
314
315
316 @pytest.mark.parametrize("flag", ["-t", "--no-footer"])
317 def test_the_truncation_notice_survives_a_suppressed_footer(
318 hsql: Hsql, duck: list[str], flag: str
319 ) -> None:
320 """These suppress stdout chrome. They do not suppress a warning.
321
322 The footer is where a truncated result says `3 of >3`, so with it gone the
323 stderr note is the only thing that says so at all.
324 """
325 res = hsql(*duck, flag, "--limit", "3", "-c", TEN_ROWS)
326 assert "of >3" not in res.stdout
327 assert "results truncated at --limit 3" in res.stderr
328
329
330 # --- the row cap the layouts print under -------------------------------------
331
332
333 @pytest.mark.parametrize(
334 ("format_name", "expected"), [("table", 40), ("markdown", 40), ("vertical", 10)]
335 )
336 def test_each_layout_has_its_own_default_cap(
337 hsql: Hsql, duck: list[str], format_name: str, expected: int
338 ) -> None:
339 """A screen holds ten records vertically and forty rows as a table."""
340 res = hsql(*duck, "-tA", "--format", format_name, "-c", HUNDRED_ROWS)
341 assert res.exit_code == ExitCode.OK
342 printed = [line for line in res.stdout.splitlines() if line]
343 assert len(printed) == expected
344
345
346 def test_the_footer_says_what_was_not_printed(hsql: Hsql, duck: list[str]) -> None:
347 """The rows were fetched, so unlike a hard limit this total is exact."""
348 res = hsql(*duck, "-c", HUNDRED_ROWS)
349 assert res.stdout.splitlines()[-1] == "(40 of 100 rows)"
350 assert res.stderr == ""
351
352
353 def test_both_caps_at_once_keep_their_own_meanings(hsql: Hsql, duck: list[str]) -> None:
354 """Fifty fetched of an unknown number, forty printed of the fifty."""
355 res = hsql(*duck, "--limit", "50", "-c", HUNDRED_ROWS)
356 assert res.stdout.splitlines()[-1] == "(40 of >50 rows)"
357
358
359 @pytest.mark.parametrize("value,expected", [("5", 5), ("-1", 100), ("0", 0)])
360 def test_display_rows_sets_the_cap(
361 hsql: Hsql, duck: list[str], value: str, expected: int
362 ) -> None:
363 res = hsql(
364 *duck, "-tA", "--limit", "-1", "--display-rows", value, "-c", HUNDRED_ROWS
365 )
366 assert res.exit_code == ExitCode.OK
367 assert len([line for line in res.stdout.splitlines() if line]) == expected
368
369
370 def test_the_cap_does_not_reach_a_file_format(hsql: Hsql, duck: list[str]) -> None:
371 """A csv is written for a machine; dropping rows out of it is a different
372 promise from not filling a screen with them."""
373 res = hsql(*duck, "--csv", "-c", HUNDRED_ROWS)
374 assert len(res.stdout.splitlines()) == 101 # header and every row
375 assert res.stderr == ""
376
377
378 def test_a_cap_a_file_format_cannot_honor_says_so(hsql: Hsql, duck: list[str]) -> None:
379 """Asked for five rows, given a hundred: silence would read as five."""
380 res = hsql(*duck, "--csv", "--display-rows", "5", "-c", HUNDRED_ROWS)
381 assert len(res.stdout.splitlines()) == 101
382 assert "--display-rows" in res.stderr
383 assert "csv" in res.stderr
384
385
386 @pytest.mark.parametrize("flag", ["-t", "--no-footer"])
387 def test_a_suppressed_footer_moves_the_cap_notice_to_stderr(
388 hsql: Hsql, duck: list[str], flag: str
389 ) -> None:
390 """The footer is the only thing on stdout that says rows were dropped."""
391 res = hsql(*duck, flag, "-c", HUNDRED_ROWS)
392 assert " 40" in res.stdout and " 41" not in res.stdout
393 assert "rows)" not in res.stdout
394 assert "printed 40 of 100 rows" in res.stderr
395
396
397 def test_the_footer_is_not_restated_on_stderr(hsql: Hsql, duck: list[str]) -> None:
398 """`40 of 100 rows` is already under the result; stderr adds nothing."""
399 res = hsql(*duck, "-c", HUNDRED_ROWS)
400 assert "printed" not in res.stderr
401
402
403 def test_a_profile_can_set_the_cap(hsql: Hsql, tmp_path: Path) -> None:
404 path = tmp_path / ".harlequin.toml"
405 path.write_text(
406 "default_profile = 'duck'\n"
407 "\n[profiles.duck]\n"
408 "adapter = 'duckdb'\n"
409 "conn_str = [ ':memory:' ]\n"
410 "no_init = true\n"
411 "display_rows = 3\n"
412 )
413 res = hsql("--config-path", str(path), "-tA", "-c", HUNDRED_ROWS)
414 assert res.stdout == "1\n2\n3\n"
415
416
417 def test_diagnostics_follow_the_data_they_describe(tmp_path: Path) -> None:
418 """stdout is block-buffered when it is a pipe; stderr is not.
419
420 Without a flush between them a note overtakes the result set it is about,
421 and `hsql ... 2>&1 | less` reads in an order the terminal never showed. Only
422 a real subprocess can prove it: in-process, `CliRunner`'s stdout is not a
423 pipe and so is not buffered the way the shipped command's is.
424 """
425 proc = subprocess.run(
426 [
427 sys.executable,
428 "-c",
429 "import sys; from harlequin.hsql import main; sys.argv = sys.argv[1:]; "
430 "main()",
431 "hsql",
432 *["-a", "duckdb", "--no-init", ":memory:"],
433 *["--limit", "3", "--stats", "-c", TEN_ROWS],
434 ],
435 stdout=subprocess.PIPE,
436 stderr=subprocess.STDOUT,
437 text=True,
438 cwd=tmp_path, # out of the repo, whose own .harlequin.toml would apply
439 )
440 assert proc.returncode == ExitCode.OK, proc.stdout
441 combined = proc.stdout
442 assert combined.index("(3 of >3 rows)") < combined.index("results truncated")
443 assert combined.index("results truncated") < combined.index('"status":"ok"')
444
445
446 # --- several statements ------------------------------------------------------
447
448
449 def test_result_all_by_default(hsql: Hsql, duck: list[str]) -> None:
450 res = hsql(*duck, "-tA", "-c", "select 1; select 2")
451 assert res.stdout == "1\n2\n"
452
453
454 @pytest.mark.parametrize("spec,expected", [("last", "2\n"), ("1", "1\n"), ("2", "2\n")])
455 def test_result_selection(
456 hsql: Hsql, duck: list[str], spec: str, expected: str
457 ) -> None:
458 res = hsql(*duck, "-tA", "--result", spec, "-c", "select 1; select 2")
459 assert res.exit_code == ExitCode.OK
460 assert res.stdout == expected
461
462
463 @pytest.mark.parametrize("spec", ["3", "0", "penultimate"])
464 def test_bad_result_selection(hsql: Hsql, duck: list[str], spec: str) -> None:
465 res = hsql(*duck, "--result", spec, "-c", "select 1; select 2")
466 assert res.exit_code == ExitCode.USAGE
467 assert res.stdout == ""
468
469
470 def test_two_result_sets_will_not_fit_in_a_csv(hsql: Hsql, duck: list[str]) -> None:
471 """Two headers in one file is silent corruption; an error costs one retry."""
472 res = hsql(*duck, "--csv", "-c", "select 1; select 2")
473 assert res.exit_code == ExitCode.USAGE
474 assert res.stdout == ""
475 assert "2 result sets, but csv holds one" in res.stderr
476 assert "--result last" in res.stderr
477 assert "-o DIR" in res.stderr
478
479
480 def test_two_result_sets_do_fit_in_jsonl(hsql: Hsql, duck: list[str]) -> None:
481 res = hsql(*duck, "--jsonl", "-c", "select 1 as a; select 2 as a")
482 assert res.exit_code == ExitCode.OK
483 assert res.stdout == '{"a":1}\n{"a":2}\n'
484
485
486 def test_on_error_stop(hsql: Hsql, duck: list[str]) -> None:
487 res = hsql(*duck, "-tA", "-c", "select 1; select bad; select 3")
488 assert res.exit_code == ExitCode.QUERY
489 assert res.stdout == "1\n"
490
491
492 def test_on_error_continue(hsql: Hsql, duck: list[str]) -> None:
493 res = hsql(
494 *duck, "-tA", "--on-error", "continue", "-c", "select 1; select bad; select 3"
495 )
496 assert res.exit_code == ExitCode.QUERY, "a run with a failure in it is not ok"
497 assert res.stdout == "1\n3\n"
498
499
500 def test_ddl_produces_no_result_set(hsql: Hsql, duck: list[str]) -> None:
501 res = hsql(*duck, "-c", "create table t (a int)", "-c", "insert into t values (1)")
502 assert res.exit_code == ExitCode.OK
503 assert res.stdout == ""
504
505
506 # --- where the SQL comes from ------------------------------------------------
507
508
509 def test_file_source(hsql: Hsql, duck: list[str], tmp_path: Path) -> None:
510 script = tmp_path / "q.sql"
511 script.write_text("select 42 as answer;\n")
512 res = hsql(*duck, "-tA", "-f", str(script))
513 assert res.exit_code == ExitCode.OK
514 assert res.stdout == "42\n"
515
516
517 def test_stdin_source(hsql: Hsql, duck: list[str]) -> None:
518 res = hsql(*duck, "-tA", "-f", "-", input="select 42\n")
519 assert res.exit_code == ExitCode.OK
520 assert res.stdout == "42\n"
521
522
523 def test_sources_run_in_the_order_they_were_given(
524 hsql: Hsql, duck: list[str], tmp_path: Path
525 ) -> None:
526 script = tmp_path / "setup.sql"
527 script.write_text("create table t (a int); insert into t values (7);")
528 res = hsql(*duck, "-tA", "-f", str(script), "-c", "select a from t")
529 assert res.exit_code == ExitCode.OK
530 assert res.stdout == "7\n"
531
532
533 def test_a_missing_file_is_a_usage_error(hsql: Hsql, duck: list[str]) -> None:
534 res = hsql(*duck, "-f", "no-such-file.sql")
535 assert res.exit_code == ExitCode.USAGE
536 assert "could not read" in res.stderr
537
538
539 def test_a_binary_file_is_a_usage_error(
540 hsql: Hsql, duck: list[str], tmp_path: Path
541 ) -> None:
542 """A file that isn't text says so, instead of raising a decode error."""
543 script = tmp_path / "database.db"
544 script.write_bytes(b"\xcd\xe3k.4,9\x97DUCK")
545 res = hsql(*duck, "-f", str(script))
546 assert res.exit_code == ExitCode.USAGE
547 assert "could not read" in res.stderr
548 assert "not UTF-8 text" in res.stderr
549
550
551 def test_binary_stdin_is_a_usage_error(hsql: Hsql, duck: list[str]) -> None:
552 res = hsql(*duck, "-f", "-", input=b"\xcd\xe3k.4,9\x97DUCK")
553 assert res.exit_code == ExitCode.USAGE
554 assert "could not read standard input" in res.stderr
555
556
557 # --- writing to a file -------------------------------------------------------
558
559
560 @pytest.mark.parametrize(
561 "format_name,sql",
562 [
563 *(
564 (name, "select 1 as a, null as b, 'ü' as c")
565 for name in LAYOUTS + TEXT_FILES
566 ),
567 # A null's value bytes are whatever was in the buffer, and Arrow does
568 # not zero them -- so two processes writing the same null column write
569 # different padding. That is the data, not the write path, so the
570 # columnar formats are checked without one.
571 *((name, "select 1 as a, 'ü' as c") for name in BINARY_FILES),
572 ],
573 )
574 def test_output_file_and_redirect_agree(
575 hsql: Hsql, duck: list[str], tmp_path: Path, format_name: str, sql: str
576 ) -> None:
577 """The one thing a second write path could plausibly get wrong."""
578 destination = tmp_path / f"out.{format_name}"
579 written = hsql(*duck, "--format", format_name, "-o", str(destination), "-c", sql)
580 piped = hsql(*duck, "--format", format_name, "-c", sql)
581 assert written.exit_code == ExitCode.OK
582 assert written.stdout_bytes == b""
583 assert destination.read_bytes() == piped.stdout_bytes
584
585
586 def test_a_file_never_gets_color(hsql: Hsql, duck: list[str], tmp_path: Path) -> None:
587 destination = tmp_path / "out.txt"
588 hsql(*duck, "--color", "always", "-o", str(destination), "-c", "select 1 as a")
589 assert b"\x1b[" not in destination.read_bytes()
590
591
592 def test_an_unwritable_destination_is_a_usage_error(
593 hsql: Hsql, duck: list[str], tmp_path: Path
594 ) -> None:
595 in_the_way = tmp_path / "not-a-directory"
596 in_the_way.write_text("")
597 res = hsql(*duck, "-o", str(in_the_way / "out.csv"), "-c", "select 1")
598 assert res.exit_code == ExitCode.USAGE
599 assert res.stderr.startswith("hsql: error: ")
600
601
602 def test_a_missing_parent_directory_is_created(
603 hsql: Hsql, duck: list[str], tmp_path: Path
604 ) -> None:
605 destination = tmp_path / "exports" / "nested" / "out.csv"
606 res = hsql(*duck, "-o", str(destination), "-tA", "-c", "select 1")
607 assert res.exit_code == ExitCode.OK
608 assert destination.read_text() == "1\n"
609
610
611 # --- writing to a directory --------------------------------------------------
612
613
614 def test_a_directory_takes_one_file_per_result_set(
615 hsql: Hsql, duck: list[str], tmp_path: Path
616 ) -> None:
617 """A folder is what lets a format that holds one result set take a script
618 that produced several."""
619 destination = tmp_path / "exports"
620 res = hsql(*duck, "--csv", "-o", str(destination), "-c", "select 1; select 2")
621 assert res.exit_code == ExitCode.OK
622 assert res.stdout == ""
623 assert (destination / "results_1.csv").read_text() == "1\n1\n"
624 assert (destination / "results_2.csv").read_text() == "2\n2\n"
625
626
627 def test_a_directory_names_what_it_wrote_on_stderr(
628 hsql: Hsql, duck: list[str], tmp_path: Path
629 ) -> None:
630 """The caller did not name these files, so stderr says what they are."""
631 destination = tmp_path / "exports"
632 res = hsql(*duck, "--csv", "-o", str(destination), "-c", "select 1; select 2")
633 assert "results_1.csv" in res.stderr
634 assert "results_2.csv" in res.stderr
635
636
637 def test_a_named_file_is_not_named_again(
638 hsql: Hsql, duck: list[str], tmp_path: Path
639 ) -> None:
640 destination = tmp_path / "out.csv"
641 res = hsql(*duck, "-o", str(destination), "-c", "select 1")
642 assert res.stderr == ""
643
644
645 @pytest.mark.parametrize("format_name", FILE_FORMATS + LAYOUTS)
646 def test_a_directory_file_holds_what_the_same_format_writes(
647 hsql: Hsql, duck: list[str], tmp_path: Path, format_name: str
648 ) -> None:
649 destination = tmp_path / "exports"
650 hsql(*duck, "--format", format_name, "-o", str(destination), "-c", "select 1 as a")
651 (written,) = destination.iterdir()
652 piped = hsql(*duck, "--format", format_name, "-c", "select 1 as a")
653 assert written.read_bytes() == piped.stdout_bytes
654
655
656 def test_a_directory_is_created_when_it_is_not_there(
657 hsql: Hsql, duck: list[str], tmp_path: Path
658 ) -> None:
659 destination = tmp_path / "exports" / "nested"
660 res = hsql(*duck, "--csv", "-o", f"{destination}/", "-c", "select 1")
661 assert res.exit_code == ExitCode.OK
662 assert (destination / "results_1.csv").is_file()
663
664
665 def test_an_existing_directory_takes_files_whatever_it_is_called(
666 hsql: Hsql, duck: list[str], tmp_path: Path
667 ) -> None:
668 destination = tmp_path / "exports.old"
669 destination.mkdir()
670 res = hsql(*duck, "--csv", "-o", str(destination), "-c", "select 1")
671 assert res.exit_code == ExitCode.OK
672 assert (destination / "results_1.csv").is_file()
673
674
675 @pytest.mark.parametrize(
676 "args,written",
677 [
678 (("--info",), "info.json"),
679 (("--spec",), "spec.json"),
680 (("--config", "show"), "config-show.toml"),
681 (("--config", "show", "--format", "json"), "config-show.json"),
682 (("--config", "schema"), "config-schema.json"),
683 (("--config", "list-profiles", "--csv"), "config-list-profiles.csv"),
684 ],
685 )
686 def test_a_mode_names_its_document_in_a_directory(
687 hsql: Hsql, tmp_path: Path, args: tuple[str, ...], written: str
688 ) -> None:
689 """A document has no position to be numbered by, so it takes its own name --
690 and the extension of what it is actually written as."""
691 destination = tmp_path / "exports"
692 res = hsql(*args, "-o", str(destination))
693 assert res.stdout == ""
694 assert (destination / written).stat().st_size > 0
695 assert written in res.stderr
696
697
698 def test_format_none_names_no_file(hsql: Hsql, duck: list[str], tmp_path: Path) -> None:
699 """The rows are discarded, so there is no file to write and no folder to
700 make -- but the run still reports what it did."""
701 destination = tmp_path / "exports"
702 res = hsql(
703 *duck, "--format", "none", "-o", str(destination), "--stats", "-c", "select 1"
704 )
705 assert res.exit_code == ExitCode.OK
706 assert not destination.exists()
707 assert json.loads(res.stderr.splitlines()[-1])["rows"] == 1
708
709
710 # --- color -------------------------------------------------------------------
711
712
713 def test_color_is_off_by_default(hsql: Hsql, duck: list[str]) -> None:
714 """Principle 4: the bytes may not depend on what stdout happens to be."""
715 assert "\x1b[" not in hsql(*duck, "-c", "select 1 as a").stdout
716
717
718 def test_color_always(hsql: Hsql, duck: list[str]) -> None:
719 assert "\x1b[" in hsql(*duck, "--color", "always", "-c", "select null as a").stdout
720
721
722 # --- config, profiles and adapters -------------------------------------------
723
724
725 @pytest.fixture
726 def config_file(tmp_path: Path) -> Path:
727 path = tmp_path / ".harlequin.toml"
728 path.write_text(
729 "default_profile = 'duck'\n"
730 "\n[profiles.duck]\n"
731 "adapter = 'duckdb'\n"
732 "conn_str = [ ':memory:' ]\n"
733 "no_init = true\n"
734 "theme = 'fruity'\n"
735 "locale = 'de_DE.UTF-8'\n"
736 "viewer_max_rows = 7\n"
737 "limit = 3\n"
738 "\n[profiles.lite]\n"
739 "adapter = 'sqlite'\n"
740 "conn_str = [ ':memory:' ]\n"
741 )
742 return path
743
744
745 def test_the_default_profile_applies(hsql: Hsql, config_file: Path) -> None:
746 """And the IDE's own keys are dropped rather than handed to the adapter."""
747 res = hsql("--config-path", str(config_file), "-tA", "-c", TEN_ROWS)
748 assert res.exit_code == ExitCode.OK
749 # `limit` is the one both commands honor; `viewer_max_rows = 7` is the
750 # IDE's cap on its own widget, and means nothing here.
751 assert res.stdout == "".join(f"{n}\n" for n in range(1, 4)), "profile limit of 3"
752
753
754 def test_a_cli_option_beats_the_profile(hsql: Hsql, config_file: Path) -> None:
755 res = hsql("--config-path", str(config_file), "-tA", "--limit", "2", "-c", TEN_ROWS)
756 assert res.stdout == "1\n2\n"
757
758
759 def test_a_profile_names_its_adapter(hsql: Hsql, config_file: Path) -> None:
760 res = hsql(
761 "--config-path", str(config_file), "-P", "lite", "-tA", "-c", "select 42"
762 )
763 assert res.exit_code == ExitCode.OK
764 assert res.stdout == "42\n"
765
766
767 def test_help_for_the_profiles_adapter(hsql: Hsql, config_file: Path) -> None:
768 res = hsql("--config-path", str(config_file), "-P", "lite", "--help")
769 assert "Showing sqlite's connection options." in res.output
770
771
772 def test_an_unknown_profile_is_a_usage_error(hsql: Hsql, config_file: Path) -> None:
773 res = hsql("--config-path", str(config_file), "-P", "nope", "-c", "select 1")
774 assert res.exit_code == ExitCode.USAGE
775 assert res.stdout == ""
776 assert "profile" in res.stderr
777
778
779 def test_an_option_the_adapter_never_declared_is_a_usage_error(
780 hsql: Hsql, tmp_path: Path
781 ) -> None:
782 """Before the connection, and before the query it would have run.
783
784 The adapter's own constructor takes supersets of what it declares, so this
785 is the only place a misspelling can be caught -- and a run that believed it
786 was read-only should not reach the database at all.
787 """
788 path = tmp_path / ".harlequin.toml"
789 path.write_text(
790 "[profiles.duck]\n"
791 "adapter = 'duckdb'\n"
792 "conn_str = [ ':memory:' ]\n"
793 "reed_only = true\n"
794 )
795 res = hsql("--config-path", str(path), "-P", "duck", "-c", "select 1")
796 assert res.exit_code == ExitCode.USAGE
797 assert res.stdout == ""
798 assert "reed_only" in res.stderr
799 assert "read_only" in res.stderr
800 assert "duckdb" in res.stderr
801
802
803 def test_an_unknown_adapter_is_a_usage_error(hsql: Hsql) -> None:
804 res = hsql("-a", "nosuchadapter", "-c", "select 1")
805 assert res.exit_code == ExitCode.USAGE
806 assert res.stdout == ""
807
808
809 def test_a_connection_failure_exits_three(hsql: Hsql, tmp_path: Path) -> None:
810 res = hsql(
811 "-a",
812 "duckdb",
813 "--no-init",
814 str(tmp_path / "nope" / "db.duckdb"),
815 "-c",
816 "select 1",
817 )
818 assert res.exit_code == ExitCode.CONNECTION
819 assert res.stdout == ""
820
821
822 # --- pointing back at the IDE ------------------------------------------------
823
824
825 def test_a_theme_name_after_tuples_only_is_explained(
826 hsql: Hsql, duck: list[str], monkeypatch: pytest.MonkeyPatch, tmp_path: Path
827 ) -> None:
828 """`-t nord` is the one habit the two commands can silently disagree on.
829
830 In a tmp cwd because it succeeds: DuckDB creates a database file named
831 `nord` rather than refusing, which is the whole reason this is worth a note.
832 """
833 monkeypatch.chdir(tmp_path)
834 res = hsql("-a", "duckdb", "--no-init", "-t", "nord", "-c", "select 1")
835 assert res.exit_code == ExitCode.OK
836 assert res.stdout.strip() == "1"
837 assert "hsql has no themes" not in res.stdout
838 assert "hsql has no themes" in res.stderr
839 assert "'nord' was read as a connection string" in res.stderr
840
841
842 def test_the_theme_hint_needs_both_halves(
843 hsql: Hsql, duck: list[str], monkeypatch: pytest.MonkeyPatch, tmp_path: Path
844 ) -> None:
845 """A theme name alone is a database, and `-t` alone is just psql's flag."""
846 monkeypatch.chdir(tmp_path)
847 without_dash_t = hsql("-a", "duckdb", "--no-init", "nord", "-c", "select 1")
848 assert "hsql has no themes" not in without_dash_t.stderr
849
850 without_a_theme = hsql(*duck, "-t", "-c", "select 1")
851 assert "hsql has no themes" not in without_a_theme.stderr
852
853
854 def test_the_theme_names_are_the_ides() -> None:
855 """The copy in `diagnostics` cannot import the original: it is Textual's.
856
857 So this is the seam where a Textual upgrade that adds a theme shows up.
858 """
859 from harlequin.colors import VALID_THEMES
860
861 assert IDE_THEMES == frozenset(VALID_THEMES)
862
863
864 # --- the exit-code mapping ---------------------------------------------------
865
866
867 @pytest.mark.parametrize(
868 "error,code",
869 [
870 (HarlequinQueryError("boom"), ExitCode.QUERY),
871 (HarlequinConfigError("boom"), ExitCode.USAGE),
872 (HarlequinConnectionError("boom"), ExitCode.CONNECTION),
873 (HarlequinCopyError("boom"), ExitCode.QUERY),
874 (KeyboardInterrupt(), ExitCode.INTERRUPT),
875 (RuntimeError("boom"), ExitCode.QUERY),
876 ],
877 )
878 def test_exit_code_for(error: BaseException, code: ExitCode) -> None:
879 assert exit_code_for(error) == code
880
881
882 # --- how the command gets built ----------------------------------------------
883
884
885 def test_the_config_is_read_once(
886 hsql: Hsql, duck: list[str], monkeypatch: pytest.MonkeyPatch
887 ) -> None:
888 """Both phases want the profile; only one of them may go to disk for it."""
889 import harlequin.config
890
891 reads: list[object] = []
892 real = harlequin.config.load_profile
893
894 def counting(config_path: Any, profile_name: Any) -> Any:
895 reads.append(config_path)
896 return real(config_path=config_path, profile_name=profile_name)
897
898 monkeypatch.setattr("harlequin.first_pass.load_profile", counting)
899 res = hsql(*duck, "-c", "select 1")
900 assert res.exit_code == ExitCode.OK
901 assert len(reads) == 1
902
903
904 def test_hsql_does_not_claim_dash_h() -> None:
905 """`-h` belongs to `--host`.
906
907 psql spells it that way, and the postgres and mysql adapters both declare
908 it. Taking it for help would silently strip it from them.
909 """
910 cmd = build_cli(["--help"])
911 with click.Context(cmd) as ctx:
912 opts = {opt for param in cmd.get_params(ctx) for opt in param.opts}
913 assert "--help" in opts
914 assert "-h" not in opts
915
916
917 def test_an_adapter_option_cannot_shadow_an_hsql_flag() -> None:
918 from harlequin.adapter import HarlequinAdapter
919 from harlequin.first_pass import attach_adapter_options, command_spellings
920 from harlequin.options import TextOption
921
922 class _Adapter:
923 ADAPTER_OPTIONS = [
924 TextOption(name="collides", description="x", short_decls=["-c"]),
925 TextOption(name="format", description="x"),
926 TextOption(name="fine", description="x", short_decls=["-Z"]),
927 ]
928
929 cmd = build_cli(["--help"])
930 reserved, taken = command_spellings(cmd)
931 attach_adapter_options(
932 cmd,
933 cast("type[HarlequinAdapter]", _Adapter),
934 reserved=reserved,
935 taken=taken,
936 )
937 by_name: dict[str | None, list[click.Parameter]] = {}
938 for param in cmd.params:
939 by_name.setdefault(param.name, []).append(param)
940
941 # the colliding short goes; the option survives under its long spelling
942 (collides,) = by_name["collides"]
943 assert collides.opts == ["--collides"]
944 # an option whose only spelling hsql already owns is dropped whole, so the
945 # command is left with hsql's own --format and no duplicate
946 (fmt,) = by_name["format"]
947 assert fmt.opts == ["--format"]
948 # anything that doesn't collide arrives untouched
949 (fine,) = by_name["fine"]
950 assert set(fine.opts) == {"--fine", "-Z"}
951
952
953 # --- `--config`, the mode that reports on config files -----------------------
954
955
956 @pytest.fixture
957 def config_dirs(
958 tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch
959 ) -> tuple[Path, Path]:
960 """A cwd and a home directory to write config files into, and nothing else.
961
962 Returned nearest first, which is the order the files in them are read, and
963 so the order everything below asserts about.
964 """
965 mock_cwd = tmp_path_factory.mktemp("cwd")
966 mock_home = tmp_path_factory.mktemp("home")
967 monkeypatch.setattr(
968 "harlequin.config._search_directories",
969 lambda: [
970 (mock_cwd, (".harlequin.toml",)),
971 (mock_home, (".harlequin.toml",)),
972 ],
973 )
974 return mock_cwd, mock_home
975
976
977 @pytest.fixture
978 def two_config_files(config_dirs: tuple[Path, Path]) -> tuple[Path, Path]:
979 """A home file and a project file that disagree about one profile.
980
981 The shape every question about the merge is asked in: `shared` is defined
982 twice, `personal` and `project` once each, and the default is the home
983 file's.
984 """
985 cwd, home = config_dirs
986 (home / ".harlequin.toml").write_text(
987 'default_profile = "personal"\n'
988 "[profiles.personal]\n"
989 'adapter = "duckdb"\n'
990 "limit = 200000\n"
991 "[profiles.shared]\n"
992 'adapter = "sqlite"\n'
993 )
994 (cwd / ".harlequin.toml").write_text(
995 "[profiles.shared]\n"
996 'adapter = "duckdb"\n'
997 "[profiles.project]\n"
998 'adapter = "sqlite"\n'
999 )
1000 return cwd / ".harlequin.toml", home / ".harlequin.toml"
1001
1002
1003 def test_config_show_names_the_file_every_value_came_from(
1004 hsql: Hsql, two_config_files: tuple[Path, Path]
1005 ) -> None:
1006 """The single best troubleshooting artifact in the command.
1007
1008 Asserted whole rather than by substring: what makes this worth having is
1009 that a reader can see the merge, so the arrangement is the contract.
1010 """
1011 project, home = two_config_files
1012 res = hsql("--config", "show")
1013 assert res.exit_code == ExitCode.OK
1014 assert res.stdout == (
1015 f'default_profile = "personal" # from {home}\n'
1016 "\n"
1017 f"[profiles.personal] # from {home}\n"
1018 'adapter = "duckdb"\n'
1019 "limit = 200000\n"
1020 "\n"
1021 f"[profiles.project] # from {project}\n"
1022 'adapter = "sqlite"\n'
1023 "\n"
1024 f"[profiles.shared] # from {project}, overriding {home}\n"
1025 'adapter = "duckdb"\n'
1026 )
1027
1028
1029 def test_config_show_writes_toml_a_parser_reads_back(
1030 hsql: Hsql, two_config_files: tuple[Path, Path]
1031 ) -> None:
1032 """What it prints is the language it is about.
1033
1034 A document that says `# from ...` and cannot be parsed would be a report
1035 about TOML rather than TOML, and the whole point of the spelling is that a
1036 reader can paste a table of it into the file they are fixing.
1037 """
1038 if sys.version_info >= (3, 11):
1039 import tomllib
1040 else:
1041 import tomli as tomllib
1042
1043 res = hsql("--config", "show")
1044 assert tomllib.loads(res.stdout) == {
1045 "default_profile": "personal",
1046 "profiles": {
1047 "personal": {"adapter": "duckdb", "limit": 200000},
1048 "project": {"adapter": "sqlite"},
1049 "shared": {"adapter": "duckdb"},
1050 },
1051 }
1052
1053
1054 def test_config_show_writes_every_toml_type_back(
1055 hsql: Hsql, config_dirs: tuple[Path, Path]
1056 ) -> None:
1057 """A profile holds whatever TOML holds, and this has to write all of it."""
1058 if sys.version_info >= (3, 11):
1059 import tomllib
1060 else:
1061 import tomli as tomllib
1062
1063 cwd, _ = config_dirs
1064 written = (
1065 "[profiles.everything]\n"
1066 'text = "a \\"quoted\\" \\u00e9"\n'
1067 "number = 5432\n"
1068 "fraction = 1.5\n"
1069 "flag = true\n"
1070 'list = ["httpfs", "spatial"]\n'
1071 'table = { host = "localhost", port = 5432 }\n'
1072 "moment = 2026-08-18T09:30:00\n"
1073 '"dotted.key" = "quoted"\n'
1074 )
1075 (cwd / ".harlequin.toml").write_text(written, encoding="utf-8")
1076
1077 res = hsql("--config", "show")
1078 assert res.exit_code == ExitCode.OK
1079 # the é survives as itself: a config file is UTF-8, and an escape would be
1080 # something the reader has to decode to recognize their own value
1081 assert "é" in res.stdout
1082 assert tomllib.loads(res.stdout)["profiles"] == tomllib.loads(written)["profiles"]
1083
1084
1085 def test_config_show_json_carries_the_same_provenance(
1086 hsql: Hsql, two_config_files: tuple[Path, Path]
1087 ) -> None:
1088 project, home = two_config_files
1089 res = hsql("--config", "show", "--json")
1090 assert res.exit_code == ExitCode.OK
1091 assert json.loads(res.stdout) == {
1092 "default_profile": {
1093 "value": "personal",
1094 "from": str(home),
1095 "overrode": [],
1096 },
1097 "profiles": {
1098 "personal": {
1099 "value": {"adapter": "duckdb", "limit": 200000},
1100 "from": str(home),
1101 "overrode": [],
1102 },
1103 "project": {
1104 "value": {"adapter": "sqlite"},
1105 "from": str(project),
1106 "overrode": [],
1107 },
1108 "shared": {
1109 "value": {"adapter": "duckdb"},
1110 "from": str(project),
1111 "overrode": [str(home)],
1112 },
1113 },
1114 "keymaps": {},
1115 }
1116
1117
1118 def test_config_show_json_keeps_its_shape_with_nothing_to_report(
1119 hsql: Hsql, config_dirs: tuple[Path, Path]
1120 ) -> None:
1121 """A key nothing defines is null, not a key that is missing.
1122
1123 A caller that has to branch on whether a key is there is a caller writing
1124 the same three lines hsql could have written once.
1125 """
1126 res = hsql("--config", "show", "--json")
1127 assert res.exit_code == ExitCode.OK
1128 assert json.loads(res.stdout) == {
1129 "default_profile": None,
1130 "profiles": {},
1131 "keymaps": {},
1132 }
1133
1134
1135 def test_config_show_says_so_when_there_is_nothing_to_show(
1136 hsql: Hsql, config_dirs: tuple[Path, Path]
1137 ) -> None:
1138 res = hsql("--config", "show")
1139 assert res.exit_code == ExitCode.OK
1140 assert res.stdout == "# No config file defines anything hsql reads.\n"
1141
1142
1143 @pytest.mark.parametrize("argv", [["--csv"], ["--format", "markdown"]])
1144 def test_config_show_notes_a_format_it_cannot_reach(
1145 hsql: Hsql, two_config_files: tuple[Path, Path], argv: list[str]
1146 ) -> None:
1147 """A document is not rows, and silence would read as a format that applied."""
1148 res = hsql("--config", "show", *argv)
1149 assert res.exit_code == ExitCode.OK
1150 assert res.stdout.startswith("default_profile")
1151 assert "had no effect" in res.stderr
1152 assert "--format json" in res.stderr
1153
1154
1155 def test_config_show_writes_nothing_under_format_none(
1156 hsql: Hsql, two_config_files: tuple[Path, Path]
1157 ) -> None:
1158 res = hsql("--config", "show", "--format", "none")
1159 assert res.exit_code == ExitCode.OK
1160 assert res.stdout == ""
1161
1162
1163 def test_config_show_goes_to_the_file_dash_o_names(
1164 hsql: Hsql, two_config_files: tuple[Path, Path], tmp_path: Path
1165 ) -> None:
1166 destination = tmp_path / "effective.toml"
1167 res = hsql("--config", "show", "-o", str(destination))
1168 assert res.exit_code == ExitCode.OK
1169 assert res.stdout == ""
1170 assert destination.read_text(encoding="utf-8").startswith("default_profile")
1171
1172
1173 def test_config_list_profiles_is_rows(
1174 hsql: Hsql, two_config_files: tuple[Path, Path]
1175 ) -> None:
1176 """The question a human asks first: what can I pass to -P.
1177
1178 Sorted by name, and the default is a column rather than a decoration on
1179 one -- a marker inside the name is a name a shell loop would pass back
1180 wrong.
1181 """
1182 res = hsql("--config", "list-profiles")
1183 assert res.exit_code == ExitCode.OK
1184 assert res.stdout == (
1185 " profile | adapter | default\n"
1186 "----------+---------+---------\n"
1187 " personal | duckdb | true\n"
1188 " project | sqlite | false\n"
1189 " shared | duckdb | false\n"
1190 "(3 rows)\n"
1191 )
1192
1193
1194 def test_config_list_profiles_under_the_psql_switches(
1195 hsql: Hsql, two_config_files: tuple[Path, Path]
1196 ) -> None:
1197 """A listing is a result set, so every flag that shapes one reaches it."""
1198 res = hsql("--config", "list-profiles", "-tA")
1199 assert res.exit_code == ExitCode.OK
1200 assert res.stdout == (
1201 "personal|duckdb|true\nproject|sqlite|false\nshared|duckdb|false\n"
1202 )
1203
1204
1205 def test_config_list_profiles_as_csv(
1206 hsql: Hsql, two_config_files: tuple[Path, Path]
1207 ) -> None:
1208 res = hsql("--config", "list-profiles", "--csv", "-t")
1209 assert res.exit_code == ExitCode.OK
1210 assert res.stdout == (
1211 "personal,duckdb,true\nproject,sqlite,false\nshared,duckdb,false\n"
1212 )
1213
1214
1215 def test_config_list_profiles_leaves_an_unnamed_adapter_null(
1216 hsql: Hsql, config_dirs: tuple[Path, Path]
1217 ) -> None:
1218 """It reports what the files say. A profile that names no adapter is one
1219 `-a` still decides, and printing hsql's default here would claim the file
1220 had made a choice it did not make."""
1221 cwd, _ = config_dirs
1222 (cwd / ".harlequin.toml").write_text("[profiles.bare]\nlimit = 10\n")
1223 res = hsql("--config", "list-profiles", "-tA")
1224 assert res.stdout == "bare|NULL|false\n"
1225
1226
1227 def test_config_list_profiles_marks_no_default_when_there_is_none(
1228 hsql: Hsql, config_dirs: tuple[Path, Path]
1229 ) -> None:
1230 cwd, _ = config_dirs
1231 (cwd / ".harlequin.toml").write_text('[profiles.one]\nadapter = "sqlite"\n')
1232 res = hsql("--config", "list-profiles", "-tA")
1233 assert res.exit_code == ExitCode.OK
1234 assert res.stdout == "one|sqlite|false\n"
1235
1236
1237 def test_config_list_profiles_reports_a_default_that_names_nothing(
1238 hsql: Hsql, config_dirs: tuple[Path, Path]
1239 ) -> None:
1240 """Not an error, and not silence.
1241
1242 A `default_profile` naming nothing only stops an invocation that was going
1243 to use it, and this one is not -- but a short list of names is exactly
1244 where the mistake is visible, so it is said on stderr and the list still
1245 prints.
1246 """
1247 cwd, _ = config_dirs
1248 (cwd / ".harlequin.toml").write_text(
1249 'default_profile = "gone"\n[profiles.here]\nadapter = "sqlite"\n'
1250 )
1251 res = hsql("--config", "list-profiles", "-tA")
1252 assert res.exit_code == ExitCode.OK
1253 assert res.stdout == "here|sqlite|false\n"
1254 assert "default_profile is 'gone'" in res.stderr
1255
1256
1257 def test_config_list_profiles_finds_none(
1258 hsql: Hsql, config_dirs: tuple[Path, Path]
1259 ) -> None:
1260 res = hsql("--config", "list-profiles")
1261 assert res.exit_code == ExitCode.OK
1262 assert res.stdout == (
1263 " profile | adapter | default\n---------+---------+---------\n(0 rows)\n"
1264 )
1265
1266
1267 def test_config_show_reads_a_profile_it_was_not_asked_about(
1268 hsql: Hsql, two_config_files: tuple[Path, Path]
1269 ) -> None:
1270 """`-P` names a profile to connect with, and this mode connects with none.
1271
1272 A `-P` that resolves to nothing is a hard error for a run and irrelevant
1273 here, which is the point: the mode that tells you what your profiles are
1274 must not refuse to run because one of them is missing.
1275 """
1276 res = hsql("--config", "list-profiles", "-P", "no-such-profile", "-tA")
1277 assert res.exit_code == ExitCode.OK
1278 assert res.stdout.startswith("personal|")
1279
1280
1281 def test_config_reports_a_file_it_cannot_read(
1282 hsql: Hsql, config_dirs: tuple[Path, Path]
1283 ) -> None:
1284 """`show` reads every file, so a broken one is fatal to it.
1285
1286 `--config validate` is the mode that reports every problem at once; this
1287 one stops at the first, and names the file either way.
1288 """
1289 cwd, _ = config_dirs
1290 (cwd / ".harlequin.toml").write_text("this is not toml\n")
1291 res = hsql("--config", "show")
1292 assert res.exit_code == ExitCode.USAGE
1293 assert res.stdout == ""
1294 assert str(cwd / ".harlequin.toml") in res.stderr
1295
1296
1297 @pytest.mark.parametrize("sql", [["-c", "select 1"], ["-f", "-"]])
1298 def test_config_refuses_to_also_run_sql(
1299 hsql: Hsql, two_config_files: tuple[Path, Path], sql: list[str]
1300 ) -> None:
1301 """Two questions spelled as one invocation, and neither is the answer.
1302
1303 Showing the config and ignoring the SQL would be the worse outcome of the
1304 two: a script that thought it ran a query would carry on believing it.
1305 """
1306 res = hsql("--config", "show", *sql)
1307 assert res.exit_code == ExitCode.USAGE
1308 assert res.stdout == ""
1309 assert "does not run SQL" in res.stderr
1310
1311
1312 def test_an_unknown_config_mode_lists_the_ones_that_work(hsql: Hsql) -> None:
1313 res = hsql("--config", "profiles")
1314 assert res.exit_code == ExitCode.USAGE
1315 for mode in CONFIG_MODES:
1316 assert mode in res.stderr
1317
1318
1319 def test_config_modes_are_what_the_help_offers(hsql: Hsql) -> None:
1320 res = hsql("--help")
1321 assert res.exit_code == ExitCode.OK
1322 for mode in CONFIG_MODES:
1323 assert mode in res.output.replace("\n", "").replace(" ", "")
1324
1325
1326 def test_config_show_writes_a_keymap_as_the_array_it_is(
1327 hsql: Hsql, config_dirs: tuple[Path, Path]
1328 ) -> None:
1329 """A keymap is an array of tables, and its provenance is written once.
1330
1331 The array comes from one file whole, like a profile, so repeating the
1332 comment over every binding in it would say the same thing as many times as
1333 the user has key bindings.
1334 """
1335 cwd, home = config_dirs
1336 (home / ".harlequin.toml").write_text(
1337 "[[keymaps.arrows]]\n"
1338 'keys = "ctrl+j"\n'
1339 'action = "cursor_down"\n'
1340 "[[keymaps.arrows]]\n"
1341 'keys = "ctrl+k"\n'
1342 'action = "cursor_up"\n'
1343 )
1344 res = hsql("--config", "show")
1345 assert res.exit_code == ExitCode.OK
1346 assert res.stdout == (
1347 f"[[keymaps.arrows]] # from {home / '.harlequin.toml'}\n"
1348 'keys = "ctrl+j"\n'
1349 'action = "cursor_down"\n'
1350 "\n"
1351 "[[keymaps.arrows]]\n"
1352 'keys = "ctrl+k"\n'
1353 'action = "cursor_up"\n'
1354 )
1355
1356
1357 # --- `--config validate`, the mode that reports every problem ----------------
1358
1359
1360 def test_config_validate_finds_nothing_wrong_with_a_good_config(
1361 hsql: Hsql, two_config_files: tuple[Path, Path]
1362 ) -> None:
1363 """Zero problems is zero rows, and the code a script actually reads."""
1364 res = hsql("--config", "validate")
1365 assert res.exit_code == ExitCode.OK
1366 assert res.stdout == (
1367 " file | key | problem | line\n------+-----+---------+------\n(0 rows)\n"
1368 )
1369
1370
1371 def test_config_validate_exits_two_for_a_config_it_found_a_problem_in(
1372 hsql: Hsql, config_dirs: tuple[Path, Path]
1373 ) -> None:
1374 """The whole mode, for a caller that never reads the rows.
1375
1376 `--format none` is the spelling that says so out loud: no stdout at all,
1377 and the answer in the exit code.
1378 """
1379 cwd, _ = config_dirs
1380 (cwd / ".harlequin.toml").write_text(
1381 '[profiles.prod]\nadapter = "duckdb"\nreed_only = true\n'
1382 )
1383 res = hsql("--config", "validate", "--format", "none")
1384 assert res.exit_code == ExitCode.USAGE
1385 assert res.stdout == ""
1386
1387
1388 def test_config_validate_names_the_file_the_key_and_the_option(
1389 hsql: Hsql, config_dirs: tuple[Path, Path]
1390 ) -> None:
1391 """Pass 2, which is the surface nothing else in the stack validates.
1392
1393 `reed_only = true` reaches the adapter's constructor and is dropped there
1394 in silence, leaving a caller who believes they are connected read-only.
1395 """
1396 cwd, _ = config_dirs
1397 (cwd / ".harlequin.toml").write_text(
1398 '[profiles.prod]\nadapter = "duckdb"\nreed_only = true\n'
1399 )
1400 res = hsql("--config", "validate", "-tA")
1401 assert res.exit_code == ExitCode.USAGE
1402 file, key, problem, line = res.stdout.strip().split("|")
1403 assert file == str(cwd / ".harlequin.toml")
1404 assert key == "profiles.prod.reed_only"
1405 assert "duckdb" in problem
1406 assert "read_only" in problem # the spelling it was probably meant to be
1407 assert line == "NULL"
1408
1409
1410 def test_config_validate_reports_every_file_and_keeps_reading(
1411 hsql: Hsql, config_dirs: tuple[Path, Path]
1412 ) -> None:
1413 """The mode's whole reason to exist, in the shape it is worst at.
1414
1415 A file it cannot parse stops `show` dead. Here it is one row, and the file
1416 behind it is read, validated and reported on anyway -- which is what the
1417 per-file validation in front of the merge buys.
1418 """
1419 cwd, home = config_dirs
1420 (cwd / ".harlequin.toml").write_text("this is not toml\n")
1421 (home / ".harlequin.toml").write_text(
1422 '[profiles.prod]\nadapter = "sqlite"\nreed_only = true\n'
1423 )
1424 res = hsql("--config", "validate", "-tA")
1425 assert res.exit_code == ExitCode.USAGE
1426 first, second = res.stdout.splitlines()
1427 assert first.startswith(str(cwd / ".harlequin.toml"))
1428 assert second.startswith(str(home / ".harlequin.toml"))
1429
1430
1431 def test_config_validate_names_the_line_when_the_parser_named_one(
1432 hsql: Hsql, config_dirs: tuple[Path, Path]
1433 ) -> None:
1434 """Where the parser gives a position, and nowhere else.
1435
1436 A key we merely dislike has no position anywhere, and a number that was not
1437 read out of a parser would send a reader to a line with nothing on it.
1438 """
1439 cwd, _ = config_dirs
1440 (cwd / ".harlequin.toml").write_text('[profiles.prod]\nadapter = "duckdb"\noops\n')
1441 res = hsql("--config", "validate", "-tA")
1442 assert res.exit_code == ExitCode.USAGE
1443 file, key, _, line = res.stdout.strip().split("|")
1444 assert file == str(cwd / ".harlequin.toml")
1445 assert key == "NULL" # the problem is the file, not something in it
1446 assert line == "3"
1447
1448
1449 def test_config_validate_reports_a_profile_the_merge_hides(
1450 hsql: Hsql, config_dirs: tuple[Path, Path]
1451 ) -> None:
1452 """One entry per file per problem, which is what validating first buys.
1453
1454 The nearer file supplies `shared` whole, so no invocation runs the home
1455 file's copy of it -- and its author will still open that file to fix it.
1456 """
1457 cwd, home = config_dirs
1458 (home / ".harlequin.toml").write_text("[profiles.shared]\nreed_only = true\n")
1459 (cwd / ".harlequin.toml").write_text("[profiles.shared]\nread_only = true\n")
1460 res = hsql("--config", "validate", "-tA")
1461 assert res.exit_code == ExitCode.USAGE
1462 assert res.stdout.startswith(
1463 f"{home / '.harlequin.toml'}|profiles.shared.reed_only"
1464 )
1465
1466
1467 def test_config_validate_reports_a_default_that_names_nothing(
1468 hsql: Hsql, config_dirs: tuple[Path, Path]
1469 ) -> None:
1470 """Where `list-profiles` notes it, this one fails on it.
1471
1472 Nothing about the key is more wrong here -- it is the same broken default.
1473 The difference is what each mode was asked: one for a list of names, and
1474 this one for whether the config is any good.
1475 """
1476 cwd, _ = config_dirs
1477 (cwd / ".harlequin.toml").write_text(
1478 'default_profile = "gone"\n[profiles.here]\nadapter = "sqlite"\n'
1479 )
1480 res = hsql("--config", "validate", "-tA")
1481 assert res.exit_code == ExitCode.USAGE
1482 file, key, problem, _ = res.stdout.strip().split("|")
1483 assert file == str(cwd / ".harlequin.toml")
1484 assert key == "default_profile"
1485 assert "gone" in problem
1486
1487
1488 def test_config_validate_accepts_a_profile_written_for_the_ide(
1489 hsql: Hsql, config_dirs: tuple[Path, Path]
1490 ) -> None:
1491 """Valid is a union of three sets, and getting it wrong breaks working configs.
1492
1493 One profile serves both commands, so the IDE's keys are as legal here as
1494 hsql's own and the adapter's -- and a value may arrive uncast, because the
1495 adapter contract says it may: `port = 5432` and `port = "5432"` are the
1496 same option written two ways a TOML file invites.
1497 """
1498 cwd, _ = config_dirs
1499 (cwd / ".harlequin.toml").write_text(
1500 "[profiles.ide]\n"
1501 'adapter = "sqlite"\n' # the adapter's own
1502 "read_only = true\n"
1503 "limit = 100\n" # a key both commands read
1504 'theme = "nord"\n' # a key only the IDE reads
1505 'keymap_name = ["vscode"]\n'
1506 "[profiles.uncast]\n"
1507 'adapter = "postgres"\n'
1508 "port = 5432\n"
1509 )
1510 res = hsql("--config", "validate", "-tA")
1511 assert res.exit_code == ExitCode.OK
1512 assert res.stdout == ""
1513
1514
1515 def test_config_validate_reports_an_adapter_nothing_installs(
1516 hsql: Hsql, config_dirs: tuple[Path, Path]
1517 ) -> None:
1518 """A profile whose adapter cannot be loaded is one profile's problem.
1519
1520 It cannot be checked any further -- there are no declared options to check
1521 it against -- and the file's other profiles still can be.
1522 """
1523 cwd, _ = config_dirs
1524 (cwd / ".harlequin.toml").write_text(
1525 '[profiles.gone]\nadapter = "no-such-adapter"\n'
1526 '[profiles.fine]\nadapter = "sqlite"\nread_only = true\n'
1527 )
1528 res = hsql("--config", "validate", "-tA")
1529 assert res.exit_code == ExitCode.USAGE
1530 (row,) = res.stdout.splitlines()
1531 assert row.split("|")[1] == "profiles.gone.adapter"
1532 assert "no-such-adapter" in row
1533
1534
1535 def test_config_validate_reports_a_keymap_the_ide_would_refuse(
1536 hsql: Hsql, config_dirs: tuple[Path, Path]
1537 ) -> None:
1538 """A keymap is checked here rather than when the IDE next starts."""
1539 cwd, _ = config_dirs
1540 (cwd / ".harlequin.toml").write_text(
1541 '[[keymaps.mine]]\nkeys = "ctrl+j"\naction = "cursor_down"\noops = 1\n'
1542 )
1543 res = hsql("--config", "validate", "-tA")
1544 assert res.exit_code == ExitCode.USAGE
1545 assert res.stdout.split("|")[1] == "keymaps.mine"
1546
1547
1548 def test_config_validate_writes_one_line_per_problem(
1549 hsql: Hsql, config_dirs: tuple[Path, Path]
1550 ) -> None:
1551 """A problem is a row, and a row is a line.
1552
1553 Some of these messages are written over two lines when they are raised at a
1554 caller; folded into a cell they would arrive as two rows in every format
1555 that does not quote its cells.
1556 """
1557 cwd, _ = config_dirs
1558 (cwd / ".harlequin.toml").write_text(
1559 '[profiles.prod]\nadapter = "sqlite"\nmode = "reed-only"\n'
1560 )
1561 res = hsql("--config", "validate", "-tA")
1562 assert res.exit_code == ExitCode.USAGE
1563 (row,) = res.stdout.splitlines()
1564 assert "Allowed values" in row
1565
1566
1567 def test_config_validate_is_json_for_a_caller(
1568 hsql: Hsql, config_dirs: tuple[Path, Path]
1569 ) -> None:
1570 """Four facts per problem, under the same --json as everywhere else."""
1571 cwd, _ = config_dirs
1572 (cwd / ".harlequin.toml").write_text(
1573 '[profiles.prod]\nadapter = "duckdb"\nreed_only = true\n'
1574 )
1575 res = hsql("--config", "validate", "--json")
1576 assert res.exit_code == ExitCode.USAGE
1577 (problem,) = json.loads(res.stdout)
1578 assert problem["file"] == str(cwd / ".harlequin.toml")
1579 assert problem["key"] == "profiles.prod.reed_only"
1580 assert problem["line"] is None
1581 assert "duckdb" in problem["problem"]
1582
1583
1584 def test_config_validate_says_when_there_was_nothing_to_check(
1585 hsql: Hsql, config_dirs: tuple[Path, Path]
1586 ) -> None:
1587 """A clean config and no config at all read the same on stdout.
1588
1589 They are not the same answer, and the one that found nothing to check is
1590 the one a caller would otherwise mistake for a passing check.
1591 """
1592 res = hsql("--config", "validate")
1593 assert res.exit_code == ExitCode.OK
1594 assert "No config file defines anything" in res.stderr
1595
1596
1597 def test_config_validate_does_not_connect(
1598 hsql: Hsql, config_dirs: tuple[Path, Path]
1599 ) -> None:
1600 """It reads a declaration, not a database.
1601
1602 A profile pointing at a file that is not there is exactly the config a
1603 caller runs this mode on, and needing the database to check the config
1604 would make the mode useless where it is most wanted.
1605 """
1606 cwd, _ = config_dirs
1607 (cwd / ".harlequin.toml").write_text(
1608 '[profiles.prod]\nadapter = "sqlite"\nconn_str = ["/no/such/dir/db.sqlite"]\n'
1609 )
1610 res = hsql("--config", "validate", "-tA")
1611 assert res.exit_code == ExitCode.OK
1612 assert res.stdout == ""
1613
1614
1615 # --- `--config schema`, the mode that reports what may be in a config file ---
1616
1617
1618 def schema_of(res: Result) -> dict[str, Any]:
1619 assert res.exit_code == ExitCode.OK
1620 return cast("dict[str, Any]", json.loads(res.stdout))
1621
1622
1623 def test_config_schema_is_a_json_schema(hsql: Hsql) -> None:
1624 schema = schema_of(hsql("--config", "schema"))
1625 assert schema["$schema"] == "https://json-schema.org/draft/2020-12/schema"
1626 assert set(schema["properties"]) == {"default_profile", "profiles", "keymaps"}
1627 assert schema["$defs"]["profile"]["properties"]["limit"]["type"] == "integer"
1628
1629
1630 def test_config_schema_describes_the_adapters_installed_here(hsql: Hsql) -> None:
1631 """The reason to generate it rather than ship one: it knows what is here."""
1632 schema = schema_of(hsql("--config", "schema"))
1633 installed = schema["$defs"]["profile"]["properties"]["adapter"]["enum"]
1634 assert {"duckdb", "sqlite"} <= set(installed)
1635 for name in installed:
1636 assert f"{name}_options" in schema["$defs"]
1637
1638
1639 def test_config_schema_describes_an_adapters_own_options(hsql: Hsql) -> None:
1640 options = schema_of(hsql("--config", "schema"))["$defs"]["duckdb_options"]
1641 assert options["properties"]["no_init"]["type"] == "boolean"
1642 assert options["properties"]["extension"]["type"] == "array"
1643
1644
1645 def test_config_schema_does_not_claim_the_published_id(hsql: Hsql) -> None:
1646 """The document published at that URL is the one that names no adapter."""
1647 assert "$id" not in schema_of(hsql("--config", "schema"))
1648
1649
1650 def test_config_schema_reads_no_config_file(
1651 hsql: Hsql, config_dirs: tuple[Path, Path]
1652 ) -> None:
1653 """It describes what a config file may say, not what one says.
1654
1655 So it answers over a file that cannot be parsed -- which is a config a
1656 caller might well be reaching for a schema to fix.
1657 """
1658 cwd, _ = config_dirs
1659 (cwd / ".harlequin.toml").write_text("[profiles.prod\nadapter = 'duckdb'\n")
1660 assert schema_of(hsql("--config", "schema"))["title"] == "Harlequin config"
1661
1662
1663 def test_config_schema_does_not_connect(hsql: Hsql) -> None:
1664 res = hsql("--config", "schema", ":memory:")
1665 assert res.exit_code == ExitCode.OK
1666 assert json.loads(res.stdout)
1667
1668
1669 def test_config_schema_does_not_run_sql(hsql: Hsql) -> None:
1670 res = hsql("--config", "schema", ":memory:", "-c", "select 1")
1671 assert res.exit_code == ExitCode.USAGE
1672 assert "does not run SQL" in res.stderr
1673
1674
1675 def test_config_schema_writes_nothing_under_format_none(hsql: Hsql) -> None:
1676 res = hsql("--config", "schema", "--format", "none")
1677 assert res.exit_code == ExitCode.OK
1678 assert res.stdout == ""
1679
1680
1681 @pytest.mark.parametrize("argv", [["--csv"], ["--format", "markdown"]])
1682 def test_config_schema_notes_a_format_it_cannot_reach(
1683 hsql: Hsql, argv: list[str]
1684 ) -> None:
1685 res = hsql("--config", "schema", *argv)
1686 assert res.exit_code == ExitCode.OK
1687 assert json.loads(res.stdout)
1688 assert "--config schema" in res.stderr
1689
1690
1691 def test_config_schema_json_is_not_a_format_it_declines(hsql: Hsql) -> None:
1692 res = hsql("--config", "schema", "--json")
1693 assert res.exit_code == ExitCode.OK
1694 assert res.stderr == ""
1695
1696
1697 def test_config_schema_goes_to_the_file_dash_o_names(
1698 hsql: Hsql, tmp_path: Path
1699 ) -> None:
1700 destination = tmp_path / "config-schema.json"
1701 res = hsql("--config", "schema", "-o", str(destination))
1702 assert res.exit_code == ExitCode.OK
1703 assert res.stdout == ""
1704 assert json.loads(destination.read_text())["title"] == "Harlequin config"
1705
1706
1707 # --- `--config init`, the mode that writes one -------------------------------
1708
1709
1710 @pytest.fixture
1711 def init_dirs(
1712 config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch
1713 ) -> tuple[Path, Path]:
1714 """`config_dirs`, with the mock cwd as the process's working directory too.
1715
1716 With no config file anywhere, `--config init` writes one beside the project
1717 it is configuring, and that fallback is `Path.cwd()` -- which patching the
1718 search path does not reach.
1719 """
1720 monkeypatch.chdir(config_dirs[0])
1721 return config_dirs
1722
1723
1724 def written(path: Path) -> dict[str, Any]:
1725 """A config file as the loader reads it, to assert on what init wrote."""
1726 from harlequin.config import ConfigFile
1727
1728 return ConfigFile(path).relevant_config
1729
1730
1731 def test_config_init_writes_a_profile_where_there_was_no_config_file(
1732 hsql: Hsql, init_dirs: tuple[Path, Path]
1733 ) -> None:
1734 """The first config file a caller has, in the directory they are in.
1735
1736 Not the home directory: a caller who has said nothing about where their
1737 config lives gets it beside the project they were configuring, which is
1738 also the file the next command discovers first.
1739 """
1740 cwd, home = init_dirs
1741 res = hsql("--config", "init", "-P", "prod", "-a", "sqlite", "./my.db")
1742 assert res.exit_code == ExitCode.OK
1743 assert res.stdout == ""
1744 assert not (home / ".harlequin.toml").exists()
1745 assert written(cwd / ".harlequin.toml") == {
1746 "profiles": {"prod": {"adapter": "sqlite", "conn_str": ["./my.db"]}}
1747 }
1748
1749
1750 def test_config_init_says_what_it_wrote_and_where(
1751 hsql: Hsql, init_dirs: tuple[Path, Path]
1752 ) -> None:
1753 """A mode that writes a file produces no data, so this is the whole answer."""
1754 cwd, _ = init_dirs
1755 res = hsql("--config", "init", "-P", "prod")
1756 assert res.exit_code == ExitCode.OK
1757 assert "prod" in res.stderr
1758 assert str(cwd / ".harlequin.toml") in res.stderr
1759
1760
1761 def test_config_init_writes_what_was_typed_and_nothing_else(
1762 hsql: Hsql, init_dirs: tuple[Path, Path]
1763 ) -> None:
1764 """An option left at its default carries no intent, so it is not a key.
1765
1766 The same rule `merge_profile_with_cli()` reads the other way round: a
1767 profile full of the command's own defaults would pin every one of them
1768 against the day one changes.
1769 """
1770 cwd, _ = init_dirs
1771 res = hsql("--config", "init", "-P", "prod", "--limit", "10")
1772 assert res.exit_code == ExitCode.OK
1773 profile = written(cwd / ".harlequin.toml")["profiles"]["prod"]
1774 assert profile == {"adapter": "duckdb", "limit": 10}
1775
1776
1777 def test_config_init_writes_an_adapters_own_options(
1778 hsql: Hsql, init_dirs: tuple[Path, Path]
1779 ) -> None:
1780 """The half of a profile only the adapter declares.
1781
1782 Which is why this is the one mode that imports an adapter to write a file:
1783 `--no-init` is not a flag hsql has until sqlite's options are on it.
1784 """
1785 cwd, _ = init_dirs
1786 res = hsql("--config", "init", "-P", "prod", "-a", "sqlite", "--no-init")
1787 assert res.exit_code == ExitCode.OK
1788 profile = written(cwd / ".harlequin.toml")["profiles"]["prod"]
1789 assert profile == {"adapter": "sqlite", "no_init": True}
1790
1791
1792 def test_config_init_writes_a_shorthand_as_the_format_it_stands_for(
1793 hsql: Hsql, init_dirs: tuple[Path, Path]
1794 ) -> None:
1795 """`--csv` is a way of spelling `--format csv`, and a profile has the key."""
1796 cwd, _ = init_dirs
1797 res = hsql("--config", "init", "-P", "prod", "--csv")
1798 assert res.exit_code == ExitCode.OK
1799 profile = written(cwd / ".harlequin.toml")["profiles"]["prod"]
1800 assert profile == {"adapter": "duckdb", "format": "csv"}
1801
1802
1803 def test_config_init_names_the_adapter_even_when_nothing_did(
1804 hsql: Hsql, init_dirs: tuple[Path, Path]
1805 ) -> None:
1806 """A profile that names no adapter is one the default could move under."""
1807 cwd, _ = init_dirs
1808 res = hsql("--config", "init", "-P", "prod")
1809 assert res.exit_code == ExitCode.OK
1810 assert written(cwd / ".harlequin.toml")["profiles"]["prod"]["adapter"] == "duckdb"
1811
1812
1813 def test_config_init_keeps_everything_it_was_not_asked_to_write(
1814 hsql: Hsql, init_dirs: tuple[Path, Path]
1815 ) -> None:
1816 """The reason it writes through tomlkit rather than dumping a document.
1817
1818 A caller's comments, key order and the profiles beside the one being
1819 written all survive, because a config file is a file a person wrote.
1820 """
1821 cwd, _ = init_dirs
1822 path = cwd / ".harlequin.toml"
1823 path.write_text(
1824 'default_profile = "dev"\n'
1825 "\n"
1826 "# the one I use every day\n"
1827 "[profiles.dev]\n"
1828 'adapter = "duckdb"\n'
1829 "# a big limit, because the laptop can take it\n"
1830 "limit = 500000\n"
1831 )
1832 res = hsql("--config", "init", "-P", "prod", "-a", "sqlite")
1833 assert res.exit_code == ExitCode.OK
1834
1835 after = path.read_text()
1836 assert "# the one I use every day" in after
1837 assert "# a big limit, because the laptop can take it" in after
1838 assert written(path) == {
1839 "default_profile": "dev",
1840 "profiles": {
1841 "dev": {"adapter": "duckdb", "limit": 500000},
1842 "prod": {"adapter": "sqlite"},
1843 },
1844 }
1845
1846
1847 def test_config_init_replaces_the_profile_it_names(
1848 hsql: Hsql, init_dirs: tuple[Path, Path]
1849 ) -> None:
1850 """A profile is written whole, and says so.
1851
1852 The alternative -- merging into what is there -- leaves a caller unable to
1853 remove a key without editing the file by hand, and unable to tell from the
1854 command what the profile now says.
1855 """
1856 cwd, _ = init_dirs
1857 path = cwd / ".harlequin.toml"
1858 path.write_text('[profiles.prod]\nadapter = "sqlite"\nread_only = true\n')
1859 res = hsql("--config", "init", "-P", "prod", "-a", "sqlite")
1860 assert res.exit_code == ExitCode.OK
1861 assert "replaced" in res.stderr
1862 assert written(path)["profiles"]["prod"] == {"adapter": "sqlite"}
1863
1864
1865 def test_config_init_writes_the_file_config_path_names(
1866 hsql: Hsql, init_dirs: tuple[Path, Path], tmp_path: Path
1867 ) -> None:
1868 """A path that is not there yet, which is the file this mode exists to make."""
1869 cwd, _ = init_dirs
1870 destination = tmp_path / "nested" / "harlequin.toml"
1871 res = hsql("--config", "init", "-P", "prod", "--config-path", str(destination))
1872 assert res.exit_code == ExitCode.OK
1873 assert written(destination)["profiles"]["prod"] == {"adapter": "duckdb"}
1874 assert not (cwd / ".harlequin.toml").exists()
1875
1876
1877 def test_config_init_writes_the_nearest_config_file_that_exists(
1878 hsql: Hsql, two_config_files: tuple[Path, Path]
1879 ) -> None:
1880 """Where the wizard starts, for the same reason: it is the file that wins."""
1881 project, home = two_config_files
1882 before = home.read_text()
1883 res = hsql("--config", "init", "-P", "new", "-a", "sqlite")
1884 assert res.exit_code == ExitCode.OK
1885 assert "new" in written(project)["profiles"]
1886 assert home.read_text() == before
1887
1888
1889 def test_config_init_reads_no_profile_at_all(
1890 hsql: Hsql, init_dirs: tuple[Path, Path]
1891 ) -> None:
1892 """The profile `-P` names is the one being written, not one to run under.
1893
1894 So a name no file defines is the point rather than an error -- and a config
1895 that would refuse a run for a `default_profile` naming nothing still gets
1896 written to.
1897 """
1898 cwd, _ = init_dirs
1899 path = cwd / ".harlequin.toml"
1900 path.write_text('default_profile = "gone"\n')
1901 res = hsql("--config", "init", "-P", "prod", "-a", "sqlite")
1902 assert res.exit_code == ExitCode.OK
1903 assert written(path)["profiles"]["prod"] == {"adapter": "sqlite"}
1904
1905
1906 def test_config_init_writes_a_profile_the_next_invocation_runs_under(
1907 hsql: Hsql, init_dirs: tuple[Path, Path]
1908 ) -> None:
1909 """The whole of what this mode is for, in two invocations.
1910
1911 Nothing else asserts that what init writes is what the run path reads: the
1912 keys are hsql's own spellings on the way in and a profile's on the way out,
1913 and this is where those two agree.
1914 """
1915 res = hsql("--config", "init", "-P", "lite", "-a", "sqlite", ":memory:", "-tA")
1916 assert res.exit_code == ExitCode.OK
1917
1918 res = hsql("-P", "lite", "-c", "select 42")
1919 assert res.exit_code == ExitCode.OK
1920 assert res.stdout == "42\n"
1921
1922
1923 def test_config_init_needs_a_name_for_the_profile_it_writes(hsql: Hsql) -> None:
1924 res = hsql("--config", "init")
1925 assert res.exit_code == ExitCode.USAGE
1926 assert "-P" in res.stderr
1927
1928
1929 def test_config_init_refuses_the_name_that_means_no_profile(hsql: Hsql) -> None:
1930 """`-P None` asks for Harlequin's defaults, so it names nothing to write."""
1931 res = hsql("--config", "init", "-P", "None")
1932 assert res.exit_code == ExitCode.USAGE
1933 assert "None" in res.stderr
1934
1935
1936 def test_config_init_refuses_a_destination_that_is_not_toml(
1937 hsql: Hsql, tmp_path: Path
1938 ) -> None:
1939 destination = tmp_path / "harlequin.ini"
1940 res = hsql("--config", "init", "-P", "prod", "--config-path", str(destination))
1941 assert res.exit_code == ExitCode.USAGE
1942 assert not destination.exists()
1943
1944
1945 def test_config_init_refuses_a_file_it_cannot_parse(
1946 hsql: Hsql, init_dirs: tuple[Path, Path]
1947 ) -> None:
1948 """Half-understanding a file is the one way this could destroy one."""
1949 cwd, _ = init_dirs
1950 path = cwd / ".harlequin.toml"
1951 path.write_text("[profiles.prod\nadapter = 'duckdb'\n")
1952 res = hsql("--config", "init", "-P", "other")
1953 assert res.exit_code == ExitCode.USAGE
1954 assert path.read_text() == "[profiles.prod\nadapter = 'duckdb'\n"
1955
1956
1957 def test_config_init_refuses_a_file_whose_profiles_are_not_profiles(
1958 hsql: Hsql, init_dirs: tuple[Path, Path]
1959 ) -> None:
1960 """The write path reads a file raw, so this is the shape it cannot assume."""
1961 cwd, _ = init_dirs
1962 path = cwd / ".harlequin.toml"
1963 path.write_text("profiles = 3\n")
1964 res = hsql("--config", "init", "-P", "prod")
1965 assert res.exit_code == ExitCode.USAGE
1966 assert path.read_text() == "profiles = 3\n"
1967
1968
1969 def test_config_init_does_not_run_sql(hsql: Hsql, init_dirs: tuple[Path, Path]) -> None:
1970 cwd, _ = init_dirs
1971 res = hsql("--config", "init", "-P", "prod", "-c", "select 1")
1972 assert res.exit_code == ExitCode.USAGE
1973 assert "does not run SQL" in res.stderr
1974 assert not (cwd / ".harlequin.toml").exists()
1975
1976
1977 # --- `--spec`, the mode that reports on the command itself -------------------
1978
1979
1980 def spec_of(res: Result) -> dict[str, Any]:
1981 assert res.exit_code == ExitCode.OK
1982 return cast("dict[str, Any]", json.loads(res.stdout))
1983
1984
1985 def option_named(spec: dict[str, Any], name: str) -> dict[str, Any]:
1986 (option,) = [o for o in spec["options"] if o["name"] == name]
1987 return cast("dict[str, Any]", option)
1988
1989
1990 def test_spec_is_json(hsql: Hsql) -> None:
1991 spec = spec_of(hsql("--spec"))
1992 assert spec["program"] == "hsql"
1993 assert spec["version"]
1994 assert spec["options"]
1995 assert spec["adapters"]
1996
1997
1998 def test_spec_describes_an_option_a_caller_would_otherwise_guess_at(
1999 hsql: Hsql,
2000 ) -> None:
2001 """What `--help` says in prose, as the four facts a caller needs.
2002
2003 Whether it takes a value, what kind, what happens without it, and how to
2004 spell it -- an agent that reads this does not have to try `--limit` twice
2005 to find out it is not a flag.
2006 """
2007 limit = option_named(spec_of(hsql("--spec")), "limit")
2008 assert limit["decls"] == ["--limit"]
2009 assert limit["type"] == "integer"
2010 assert limit["default"] == 500
2011 assert limit["is_flag"] is False
2012 assert limit["multiple"] is False
2013 assert limit["choices"] is None
2014 assert "rows fetched" in limit["help"]
2015
2016
2017 def test_spec_names_the_values_a_choice_takes(hsql: Hsql) -> None:
2018 """The list `--format` will accept, so nobody has to parse it out of the
2019 epilog."""
2020 from harlequin.hsql import output
2021
2022 fmt = option_named(spec_of(hsql("--spec")), "format")
2023 assert fmt["type"] == "choice"
2024 assert fmt["choices"] == list(output.format_names())
2025 assert fmt["default"] == "table"
2026
2027
2028 def test_spec_reports_every_option_in_one_vocabulary(hsql: Hsql) -> None:
2029 """Which is the point of the document: `float range` and `file` are click's
2030 own words for a number and a path, and a caller reading a spec should not
2031 have to learn click to know which is which."""
2032 from harlequin.hsql.modes.spec import TYPES
2033
2034 spec = spec_of(hsql("--spec"))
2035 reported = {option["type"] for option in spec["options"]}
2036 reported |= {argument["type"] for argument in spec["arguments"]}
2037 reported |= {
2038 option["type"]
2039 for adapter in spec["adapters"].values()
2040 for option in adapter["options"]
2041 }
2042 assert reported <= set(TYPES.values())
2043
2044
2045 def test_spec_reports_the_types_behind_seconds_and_a_config_path(
2046 hsql: Hsql,
2047 ) -> None:
2048 spec = spec_of(hsql("--spec"))
2049 assert option_named(spec, "timeout")["type"] == "number"
2050 assert option_named(spec, "config_path")["type"] == "path"
2051
2052
2053 def test_spec_reports_no_default_as_null(hsql: Hsql) -> None:
2054 """An option with no default has none, spelled the way JSON spells nothing.
2055
2056 click holds "no default" as a sentinel object, and a document that let one
2057 through would say `--profile` defaults to the string `Sentinel.UNSET`.
2058 """
2059 spec = spec_of(hsql("--spec"))
2060 assert option_named(spec, "profile")["default"] is None
2061 assert option_named(spec, "display_rows")["default"] is None
2062 for option in spec["options"]:
2063 assert option["default"] is None or isinstance(
2064 option["default"], (str, int, float, bool, list)
2065 )
2066
2067
2068 def test_spec_reports_every_spelling_of_an_option(hsql: Hsql) -> None:
2069 tuples_only = option_named(spec_of(hsql("--spec")), "tuples_only")
2070 assert sorted(tuples_only["decls"]) == ["--tuples-only", "-t"]
2071 assert tuples_only["is_flag"] is True
2072 assert tuples_only["default"] is False
2073
2074
2075 def test_spec_reports_a_repeatable_option_as_one(hsql: Hsql) -> None:
2076 assert option_named(spec_of(hsql("--spec")), "command")["multiple"] is True
2077
2078
2079 def test_spec_reports_an_environment_variable(hsql: Hsql) -> None:
2080 """A flag that reads the environment reads it whether or not it was typed,
2081 which makes it exactly the kind of thing a caller wants told rather than
2082 discovered."""
2083 config_path = option_named(spec_of(hsql("--spec")), "config_path")
2084 assert config_path["envvar"] == "HARLEQUIN_CONFIG_PATH"
2085
2086
2087 def test_spec_reports_an_envvar_for_every_option_that_reads_one(hsql: Hsql) -> None:
2088 """Null for the rest, because there is nothing behind them to report.
2089
2090 hsql declares one `envvar=` and sets no `auto_envvar_prefix`, so click
2091 derives nothing: `HSQL_LIMIT` is not read, and a spec that implied it was
2092 would be worse than one that says null. This is the assertion that fails if
2093 a prefix is ever set, or an option grows an `envvar=` this does not carry.
2094 """
2095 spec = spec_of(hsql("--spec"))
2096 named = {o["name"]: o["envvar"] for o in spec["options"] if o["envvar"]}
2097 assert named == {"config_path": "HARLEQUIN_CONFIG_PATH"}
2098 # `to_click()` passes no `envvar=`, so an adapter option cannot have one
2099 for adapter in spec["adapters"].values():
2100 assert all(o["envvar"] is None for o in adapter["options"])
2101
2102
2103 def test_hsql_reads_no_environment_variable_it_did_not_declare(
2104 hsql: Hsql, monkeypatch: pytest.MonkeyPatch
2105 ) -> None:
2106 """The other half: click reads a variable only where one was declared.
2107
2108 Setting `auto_envvar_prefix` would make every flag configurable through the
2109 environment, which is a surface `--spec` would then have to report -- so
2110 assert the surface is the one the document describes.
2111 """
2112 monkeypatch.setenv("HSQL_LIMIT", "3")
2113 monkeypatch.setenv("HARLEQUIN_LIMIT", "3")
2114 res = hsql("-a", "duckdb", "--no-init", ":memory:", "-tA", "-c", TEN_ROWS)
2115 assert res.exit_code == ExitCode.OK
2116 assert len(res.stdout.splitlines()) == 10
2117
2118
2119 def test_spec_names_the_positional(hsql: Hsql) -> None:
2120 """`CONN_STR` is where the database goes, and it has no flag to find it by.
2121
2122 `nargs` of -1 is the half a caller cannot see any other way: one connection
2123 string or five are both this argument.
2124 """
2125 (conn_str,) = spec_of(hsql("--spec"))["arguments"]
2126 assert conn_str["name"] == "conn_str"
2127 assert conn_str["metavar"] == "CONN_STR"
2128 assert conn_str["nargs"] == -1
2129 assert conn_str["required"] is False
2130
2131
2132 def test_spec_covers_every_installed_adapter(hsql: Hsql) -> None:
2133 from harlequin.plugins import adapter_names
2134
2135 spec = spec_of(hsql("--spec"))
2136 assert sorted(spec["adapters"]) == sorted(adapter_names())
2137 for adapter in spec["adapters"].values():
2138 assert adapter["error"] is None
2139 assert adapter["options"]
2140 assert adapter["version"]
2141
2142
2143 def test_spec_reports_an_adapter_option_the_way_it_is_passed(hsql: Hsql) -> None:
2144 """The two spellings an adapter option has, and both are needed.
2145
2146 `--no-init` is what a command line takes; `no_init` is what a profile
2147 writes, and what the adapter's constructor is handed. A caller that had
2148 only one of them would write the other wrong.
2149 """
2150 duckdb = spec_of(hsql("--spec"))["adapters"]["duckdb"]
2151 (no_init,) = [o for o in duckdb["options"] if o["name"] == "no_init"]
2152 assert no_init["decls"] == ["--no-init"]
2153 assert no_init["type"] == "boolean"
2154 assert no_init["is_flag"] is True
2155 assert no_init["default"] is False
2156 assert no_init["help"]
2157
2158
2159 def test_spec_reports_an_adapters_repeatable_and_chosen_options(hsql: Hsql) -> None:
2160 """One option of each shape, named off the lists both adapters always declare.
2161
2162 sqlite's `--extension` and `--isolation-level` are appended only where the
2163 interpreter's sqlite3 supports them, so neither is a name a test may assume
2164 -- duckdb's `--extension` is in its list unconditionally, and is the
2165 repeatable one here for that reason.
2166 """
2167 spec = spec_of(hsql("--spec"))
2168 duckdb = {o["name"]: o for o in spec["adapters"]["duckdb"]["options"]}
2169 sqlite = {o["name"]: o for o in spec["adapters"]["sqlite"]["options"]}
2170 assert duckdb["extension"]["multiple"] is True
2171 assert sqlite["mode"]["type"] == "choice"
2172 assert sqlite["mode"]["choices"]
2173 assert sqlite["init_path"]["type"] == "path"
2174
2175
2176 @pytest.mark.parametrize("name", ["duckdb", "sqlite"])
2177 def test_spec_reports_what_the_adapter_declares_now(hsql: Hsql, name: str) -> None:
2178 """The document is built from the declarations, not from a list of names.
2179
2180 An adapter may declare a different set on a different interpreter -- sqlite
2181 appends `--extension` only where `enable_load_extension` exists, which is
2182 not on macOS -- so what `--spec` reports has to follow that, and a test that
2183 pins names cannot tell the difference between the two.
2184 """
2185 from harlequin.config import sluggify_option_name
2186 from harlequin.plugins import load_adapter
2187
2188 declared = {
2189 sluggify_option_name(option.name)
2190 for option in load_adapter(name).ADAPTER_OPTIONS or []
2191 }
2192 reported = {
2193 o["name"]
2194 for o in spec_of(hsql("--spec", "-a", name))["adapters"][name]["options"]
2195 }
2196 # equal today, because neither in-tree adapter declares a spelling hsql's
2197 # own flags take; a name that goes missing here is one hsql has claimed
2198 assert reported == declared
2199
2200
2201 def test_spec_narrows_to_one_adapter(hsql: Hsql) -> None:
2202 """`-a` is the only thing that changes the document, and it changes one
2203 half of it: hsql's own options are hsql's own whatever adapter is named."""
2204 everything = spec_of(hsql("--spec"))
2205 one = spec_of(hsql("--spec", "-a", "sqlite"))
2206 assert list(one["adapters"]) == ["sqlite"]
2207 assert one["adapters"]["sqlite"] == everything["adapters"]["sqlite"]
2208 assert one["options"] == everything["options"]
2209
2210
2211 def test_spec_says_what_it_does_not_cover(hsql: Hsql) -> None:
2212 """It cannot describe the IDE's flags -- reading them means importing the
2213 command that builds them, which hsql may not do -- so it says where it
2214 stops rather than reading as an exhaustive list that is not one."""
2215 scope = spec_of(hsql("--spec"))["scope"]
2216 assert "harlequin" in scope
2217 assert "not here" in scope
2218
2219
2220 def test_spec_options_are_sorted_by_name(hsql: Hsql) -> None:
2221 """A document a caller diffs between two machines, or two releases."""
2222 spec = spec_of(hsql("--spec"))
2223 assert [o["name"] for o in spec["options"]] == sorted(
2224 o["name"] for o in spec["options"]
2225 )
2226 for adapter in spec["adapters"].values():
2227 assert [o["name"] for o in adapter["options"]] == sorted(
2228 o["name"] for o in adapter["options"]
2229 )
2230
2231
2232 def test_spec_does_not_run_sql(hsql: Hsql) -> None:
2233 res = hsql("--spec", ":memory:", "-c", "select 1")
2234 assert res.exit_code == ExitCode.USAGE
2235 assert res.stdout == ""
2236 assert "does not run SQL" in res.stderr
2237
2238
2239 def test_spec_carries_no_adapters_options(hsql: Hsql) -> None:
2240 """It describes the connection options rather than accepting them.
2241
2242 A mode that connects to nothing has nothing to do with `--no-init`, and
2243 taking it would be a flag that silently did nothing.
2244 """
2245 res = hsql("--spec", "-a", "duckdb", "--no-init")
2246 assert res.exit_code == ExitCode.USAGE
2247 assert "--no-init" in res.stderr
2248
2249
2250 def test_two_modes_is_a_usage_error_naming_both(hsql: Hsql) -> None:
2251 """Modes are options, so nothing about the parse stops a caller passing two
2252 -- and two questions in one invocation have no answer that is not a guess
2253 about which was meant."""
2254 res = hsql("--spec", "--config", "show")
2255 assert res.exit_code == ExitCode.USAGE
2256 assert res.stdout == ""
2257 assert "--config show" in res.stderr
2258 assert "--spec" in res.stderr
2259
2260
2261 def test_spec_writes_nothing_under_format_none(hsql: Hsql) -> None:
2262 res = hsql("--spec", "--format", "none")
2263 assert res.exit_code == ExitCode.OK
2264 assert res.stdout == ""
2265
2266
2267 @pytest.mark.parametrize("argv", [["--csv"], ["--format", "markdown"]])
2268 def test_spec_notes_a_format_it_cannot_reach(hsql: Hsql, argv: list[str]) -> None:
2269 """A document is not rows, and silence would read as a format that applied."""
2270 res = hsql("--spec", *argv)
2271 assert res.exit_code == ExitCode.OK
2272 assert json.loads(res.stdout)["program"] == "hsql"
2273 assert "had no effect" in res.stderr
2274 assert "--format json" in res.stderr
2275
2276
2277 def test_spec_json_is_not_a_format_it_declines(hsql: Hsql) -> None:
2278 res = hsql("--spec", "--json")
2279 assert res.exit_code == ExitCode.OK
2280 assert json.loads(res.stdout)["program"] == "hsql"
2281 assert res.stderr == ""
2282
2283
2284 def test_spec_goes_to_the_file_dash_o_names(hsql: Hsql, tmp_path: Path) -> None:
2285 destination = tmp_path / "spec.json"
2286 res = hsql("--spec", "-o", str(destination))
2287 assert res.exit_code == ExitCode.OK
2288 assert res.stdout == ""
2289 assert json.loads(destination.read_text(encoding="utf-8"))["program"] == "hsql"
2290
2291
2292 def test_spec_answers_over_a_config_it_could_not_read(
2293 hsql: Hsql, config_dirs: tuple[Path, Path]
2294 ) -> None:
2295 """The mode that describes the command does not depend on the config.
2296
2297 A caller whose config file is broken is one of the callers most likely to
2298 be reading this, and a spec that refused over a file it never needed would
2299 be useless exactly there.
2300 """
2301 cwd, _ = config_dirs
2302 (cwd / ".harlequin.toml").write_text("this is not toml\n")
2303 assert spec_of(hsql("--spec"))["program"] == "hsql"
2304
2305
2306 def test_spec_ignores_a_profile_that_is_not_there(
2307 hsql: Hsql, config_dirs: tuple[Path, Path]
2308 ) -> None:
2309 """`-P` names a profile to connect with, and this mode connects with none."""
2310 assert spec_of(hsql("--spec", "-P", "no-such-profile"))["program"] == "hsql"
2311
2312
2313 def test_spec_reports_an_adapter_it_could_not_import(
2314 hsql: Hsql, monkeypatch: pytest.MonkeyPatch
2315 ) -> None:
2316 """An adapter that is installed and will not import is a fact about the
2317 installation, not a reason to answer nothing about the rest of it."""
2318 from harlequin.exception import HarlequinConfigError
2319 from harlequin.plugins import load_adapter as real_load_adapter
2320
2321 def fake_load_adapter(name: str) -> Any:
2322 if name == "duckdb":
2323 raise HarlequinConfigError("No module named 'duckdb'", title="nope")
2324 return real_load_adapter(name)
2325
2326 monkeypatch.setattr("harlequin.plugins.load_adapter", fake_load_adapter)
2327 res = hsql("--spec")
2328 spec = spec_of(res)
2329 assert spec["adapters"]["duckdb"]["options"] is None
2330 assert "duckdb" in spec["adapters"]["duckdb"]["error"]
2331 assert spec["adapters"]["sqlite"]["options"]
2332 assert "could not be imported" in res.stderr
2333
2334
2335 @pytest.mark.parametrize("argv", [["--help"], ["--help", "-a", "duckdb"]])
2336 def test_the_help_points_at_the_machine_readable_one(
2337 hsql: Hsql, argv: list[str]
2338 ) -> None:
2339 """`--help` names adapters and `--spec` fills their options in.
2340
2341 That is the trade the epilog makes -- a list of names rather than four
2342 option tables -- so the end of the help is where a reader who wanted the
2343 tables should be told where they are. Both spellings of the help say it:
2344 `-a duckdb` answers for one adapter, and the JSON is still how you get all
2345 of them.
2346 """
2347 res = hsql(*argv)
2348 assert res.exit_code == ExitCode.OK
2349 assert f"{PROGRAM} --spec" in res.output
2350 assert "Machine-readable:" in res.output
2351
2352
2353 def test_spec_is_in_the_help(hsql: Hsql) -> None:
2354 res = hsql("--help")
2355 assert res.exit_code == ExitCode.OK
2356 assert "--spec" in res.output
2357
2358
2359 def test_spec_lists_the_flag_that_would_have_shown_the_help(hsql: Hsql) -> None:
2360 """click keeps `--help` out of a command's params and adds it at parse
2361 time, so a document built from the params alone would omit the one flag
2362 every caller already knows."""
2363 assert option_named(spec_of(hsql("--spec")), "help")["decls"] == ["--help"]
2364
2365
2366 def test_spec_drops_a_spelling_an_hsql_flag_already_owns(
2367 hsql: Hsql, monkeypatch: pytest.MonkeyPatch
2368 ) -> None:
2369 """It reports the surface a caller can type, not the one an adapter wanted.
2370
2371 hsql's own flags win a collision (`_attach_adapter_options`), so an adapter
2372 option declaring `-c` does not get it — and a spec that listed it anyway
2373 would send a caller to write `hsql -c` and mean something else.
2374 """
2375 from harlequin.options import FlagOption, TextOption
2376 from harlequin.plugins import load_adapter as real_load_adapter
2377
2378 shadowed = TextOption(name="command", description="Shadowed by hsql's -c.")
2379 partly = FlagOption(
2380 name="cautious", description="Keeps its long name.", short_decls=["-c", "-w"]
2381 )
2382
2383 def fake_load_adapter(name: str) -> Any:
2384 adapter = real_load_adapter(name)
2385 if name != "sqlite":
2386 return adapter
2387 return type("Faked", (adapter,), {"ADAPTER_OPTIONS": [shadowed, partly]})
2388
2389 monkeypatch.setattr("harlequin.plugins.load_adapter", fake_load_adapter)
2390 options = spec_of(hsql("--spec", "-a", "sqlite"))["adapters"]["sqlite"]["options"]
2391 # `command` is gone whole: hsql already has a parameter by that name
2392 assert [o["name"] for o in options] == ["cautious"]
2393 # and `-c` is gone from the one that kept its other spellings
2394 assert options[0]["decls"] == ["--cautious", "-w"]
2395
2396
2397 # --- `--info`, the mode that reports on the installation ---------------------
2398
2399
2400 def info_of(res: Result) -> dict[str, Any]:
2401 assert res.exit_code == ExitCode.OK
2402 return cast("dict[str, Any]", json.loads(res.stdout))
2403
2404
2405 def test_info_is_json(hsql: Hsql) -> None:
2406 info = info_of(hsql("--info"))
2407 assert info["program"] == "hsql"
2408 assert info["version"]
2409 assert info["python"]["version"]
2410 assert info["python"]["implementation"]
2411 assert info["python"]["executable"]
2412 assert info["platform"]["system"]
2413 assert info["adapters"]
2414
2415
2416 def test_info_reports_the_interpreter_it_is_running_under(hsql: Hsql) -> None:
2417 """The half of a bug report nobody remembers to include."""
2418 import platform
2419
2420 info = info_of(hsql("--info"))
2421 assert info["python"]["version"] == platform.python_version()
2422 assert info["python"]["executable"] == sys.executable
2423 assert info["platform"]["machine"] == platform.machine()
2424
2425
2426 def test_info_lists_config_files_in_precedence_order(
2427 hsql: Hsql, two_config_files: tuple[Path, Path]
2428 ) -> None:
2429 """Nearest first, which is the order that decides which file wins."""
2430 project, home = two_config_files
2431 info = info_of(hsql("--info"))
2432 assert info["config"] == {
2433 "path": None,
2434 "files": [str(project), str(home)],
2435 }
2436
2437
2438 def test_info_lists_no_config_files_when_there_are_none(
2439 hsql: Hsql, config_dirs: tuple[Path, Path]
2440 ) -> None:
2441 assert info_of(hsql("--info"))["config"]["files"] == []
2442
2443
2444 def test_info_names_the_file_config_path_pointed_at(hsql: Hsql, tmp_path: Path) -> None:
2445 """An explicit file is the only one read, and it is the one to report."""
2446 path = tmp_path / "explicit.toml"
2447 path.write_text('[profiles.here]\nadapter = "sqlite"\n')
2448 config = info_of(hsql("--info", "--config-path", str(path)))["config"]
2449 assert config["path"] == str(path)
2450 assert config["files"] == [str(path)]
2451
2452
2453 def test_info_names_the_active_profile_and_what_chose_the_adapter(
2454 hsql: Hsql, two_config_files: tuple[Path, Path]
2455 ) -> None:
2456 """Which profile a run would use, and why it would connect where it does."""
2457 info = info_of(hsql("--info"))
2458 assert info["profile"] == {
2459 "name": "personal",
2460 "options": {"adapter": "duckdb", "limit": 200000},
2461 "error": None,
2462 }
2463 assert info["adapter"] == {"name": "duckdb", "from": "profile"}
2464
2465
2466 def test_info_reports_the_profile_dash_p_asked_for(
2467 hsql: Hsql, two_config_files: tuple[Path, Path]
2468 ) -> None:
2469 info = info_of(hsql("--info", "-P", "project"))
2470 assert info["profile"]["name"] == "project"
2471 assert info["adapter"] == {"name": "sqlite", "from": "profile"}
2472
2473
2474 def test_info_says_dash_a_beat_the_profile(
2475 hsql: Hsql, two_config_files: tuple[Path, Path]
2476 ) -> None:
2477 """`-a` wins over the profile, and a report that did not say so would send
2478 a reader to the wrong file to change it."""
2479 assert info_of(hsql("--info", "-a", "sqlite"))["adapter"] == {
2480 "name": "sqlite",
2481 "from": "-a",
2482 }
2483
2484
2485 def test_info_falls_back_to_the_default_adapter(
2486 hsql: Hsql, config_dirs: tuple[Path, Path]
2487 ) -> None:
2488 from harlequin.config import DEFAULT_ADAPTER
2489
2490 assert info_of(hsql("--info"))["adapter"] == {
2491 "name": DEFAULT_ADAPTER,
2492 "from": "default",
2493 }
2494
2495
2496 def test_info_reports_a_profile_no_file_defines(
2497 hsql: Hsql, two_config_files: tuple[Path, Path]
2498 ) -> None:
2499 """A `-P` typo is what this mode is most often run to find, so it is an
2500 answer rather than a refusal -- and the answer a run would have refused
2501 with."""
2502 info = info_of(hsql("--info", "-P", "prod"))
2503 assert info["profile"]["name"] == "prod"
2504 assert info["profile"]["options"] is None
2505 assert "prod" in info["profile"]["error"]
2506 # the same message a run gives, because it comes from the same resolution
2507 res = hsql("-P", "prod", "-c", "select 1")
2508 assert res.exit_code == ExitCode.USAGE
2509 assert info["profile"]["error"] in res.stderr
2510
2511
2512 def test_info_reports_a_default_profile_that_names_nothing(
2513 hsql: Hsql, config_dirs: tuple[Path, Path]
2514 ) -> None:
2515 cwd, _ = config_dirs
2516 (cwd / ".harlequin.toml").write_text(
2517 'default_profile = "gone"\n[profiles.here]\nadapter = "sqlite"\n'
2518 )
2519 info = info_of(hsql("--info"))
2520 assert info["profile"]["options"] is None
2521 assert "default_profile" in info["profile"]["error"]
2522 assert "gone" in info["profile"]["error"]
2523
2524
2525 def test_info_reads_no_further_than_a_run_would(
2526 hsql: Hsql, config_dirs: tuple[Path, Path]
2527 ) -> None:
2528 """It reports the profile a run would use, so it stops where a run stops.
2529
2530 A file behind the one that defines the profile is never opened, so its
2531 contents cannot turn this into a report about a problem no run would meet.
2532 `--config validate` is the mode that reads every file.
2533 """
2534 cwd, home = config_dirs
2535 (cwd / ".harlequin.toml").write_text(
2536 'default_profile = "near"\n[profiles.near]\nadapter = "sqlite"\n'
2537 )
2538 (home / ".harlequin.toml").write_text("this is not toml\n")
2539
2540 info = info_of(hsql("--info"))
2541 assert info["profile"] == {
2542 "name": "near",
2543 "options": {"adapter": "sqlite"},
2544 "error": None,
2545 }
2546 # discovery still names it: it is a file on disk that a run may yet read
2547 assert info["config"]["files"] == [
2548 str(cwd / ".harlequin.toml"),
2549 str(home / ".harlequin.toml"),
2550 ]
2551
2552
2553 def test_info_reports_the_profile_named_none_as_the_defaults(
2554 hsql: Hsql, two_config_files: tuple[Path, Path]
2555 ) -> None:
2556 info = info_of(hsql("--info", "-P", "None"))
2557 assert info["profile"] == {"name": "None", "options": {}, "error": None}
2558
2559
2560 def test_info_answers_over_a_config_it_could_not_read(
2561 hsql: Hsql, config_dirs: tuple[Path, Path]
2562 ) -> None:
2563 """A caller whose config file is broken is the caller most likely to be
2564 running this, so the parse error is part of the answer."""
2565 cwd, _ = config_dirs
2566 (cwd / ".harlequin.toml").write_text("this is not toml\n")
2567 info = info_of(hsql("--info"))
2568 assert info["config"]["files"] == [str(cwd / ".harlequin.toml")]
2569 assert info["profile"]["options"] is None
2570 assert "line 1" in info["profile"]["error"]
2571 assert info["adapters"]
2572
2573
2574 def test_info_reports_declared_capabilities_for_every_installed_adapter(
2575 hsql: Hsql,
2576 ) -> None:
2577 from importlib.metadata import version
2578
2579 from harlequin.plugins import adapter_names
2580
2581 info = info_of(hsql("--info"))
2582 assert sorted(info["adapters"]) == sorted(adapter_names())
2583 for entry in info["adapters"].values():
2584 assert entry["error"] is None
2585 assert entry["capabilities"]["implements_cancel"] in (True, False)
2586 duckdb = info["adapters"]["duckdb"]
2587 assert duckdb["distribution"] == "harlequin"
2588 assert duckdb["version"] == version("harlequin")
2589
2590
2591 def test_info_reads_the_capability_names_off_the_contract(hsql: Hsql) -> None:
2592 """A capability added to `HarlequinAdapter` is reported without this mode
2593 keeping a second list of them."""
2594 from harlequin.adapter import HarlequinAdapter
2595
2596 declared = sorted(
2597 name.lower()
2598 for name in vars(HarlequinAdapter)
2599 if name.startswith("IMPLEMENTS_")
2600 )
2601 assert declared # the contract declares at least one
2602 capabilities = info_of(hsql("--info"))["adapters"]["duckdb"]["capabilities"]
2603 assert sorted(capabilities) == declared
2604
2605
2606 def test_info_narrows_to_one_adapter(hsql: Hsql) -> None:
2607 assert list(info_of(hsql("--info", "-a", "sqlite"))["adapters"]) == ["sqlite"]
2608
2609
2610 def test_info_reports_an_adapter_it_could_not_import_as_unknown(
2611 hsql: Hsql, monkeypatch: pytest.MonkeyPatch
2612 ) -> None:
2613 """Never `false`: guessing false about what an adapter implements is the
2614 direction that gets someone hurt."""
2615 from harlequin.plugins import load_adapter as real_load_adapter
2616
2617 def fake_load_adapter(name: str) -> Any:
2618 if name == "duckdb":
2619 raise HarlequinConfigError("No module named 'duckdb'", title="nope")
2620 return real_load_adapter(name)
2621
2622 monkeypatch.setattr("harlequin.plugins.load_adapter", fake_load_adapter)
2623 res = hsql("--info")
2624 info = info_of(res)
2625 assert info["adapters"]["duckdb"]["capabilities"] == "unknown"
2626 assert "duckdb" in info["adapters"]["duckdb"]["error"]
2627 # and the rest of the installation is still reported
2628 assert info["adapters"]["sqlite"]["capabilities"]["implements_cancel"] is True
2629 assert "could not be imported" in res.stderr
2630
2631
2632 def test_info_opens_no_connection(hsql: Hsql, monkeypatch: pytest.MonkeyPatch) -> None:
2633 """The design decision this mode exists on: the diagnostic a caller runs
2634 when the database is unreachable must not itself require the database."""
2635 from harlequin.plugins import load_adapter as real_load_adapter
2636
2637 def refuse(self: Any) -> Any:
2638 raise AssertionError("--info opened a connection")
2639
2640 def fake_load_adapter(name: str) -> Any:
2641 return type("Faked", (real_load_adapter(name),), {"connect": refuse})
2642
2643 monkeypatch.setattr("harlequin.plugins.load_adapter", fake_load_adapter)
2644 assert info_of(hsql("--info"))["adapters"]["duckdb"]["capabilities"]
2645
2646
2647 def test_info_does_not_run_sql(hsql: Hsql) -> None:
2648 res = hsql("--info", ":memory:", "-c", "select 1")
2649 assert res.exit_code == ExitCode.USAGE
2650 assert res.stdout == ""
2651 assert "does not run SQL" in res.stderr
2652
2653
2654 def test_info_carries_no_adapters_options(hsql: Hsql) -> None:
2655 """It reports what an adapter declares rather than taking its options."""
2656 res = hsql("--info", "-a", "duckdb", "--no-init")
2657 assert res.exit_code == ExitCode.USAGE
2658 assert "--no-init" in res.stderr
2659
2660
2661 @pytest.mark.parametrize("other", [["--spec"], ["--config", "show"]])
2662 def test_info_beside_another_mode_is_a_usage_error(
2663 hsql: Hsql, other: list[str]
2664 ) -> None:
2665 res = hsql("--info", *other)
2666 assert res.exit_code == ExitCode.USAGE
2667 assert res.stdout == ""
2668 assert "--info" in res.stderr
2669
2670
2671 def test_info_writes_nothing_under_format_none(hsql: Hsql) -> None:
2672 res = hsql("--info", "--format", "none")
2673 assert res.exit_code == ExitCode.OK
2674 assert res.stdout == ""
2675
2676
2677 @pytest.mark.parametrize("argv", [["--csv"], ["--format", "markdown"]])
2678 def test_info_notes_a_format_it_cannot_reach(hsql: Hsql, argv: list[str]) -> None:
2679 res = hsql("--info", *argv)
2680 assert res.exit_code == ExitCode.OK
2681 assert json.loads(res.stdout)["program"] == "hsql"
2682 assert "had no effect" in res.stderr
2683 assert "--format json" in res.stderr
2684
2685
2686 def test_info_json_is_not_a_format_it_declines(hsql: Hsql) -> None:
2687 res = hsql("--info", "--json")
2688 assert res.exit_code == ExitCode.OK
2689 assert json.loads(res.stdout)["program"] == "hsql"
2690 assert res.stderr == ""
2691
2692
2693 def test_info_goes_to_the_file_dash_o_names(hsql: Hsql, tmp_path: Path) -> None:
2694 destination = tmp_path / "info.json"
2695 res = hsql("--info", "-o", str(destination))
2696 assert res.exit_code == ExitCode.OK
2697 assert res.stdout == ""
2698 assert json.loads(destination.read_text(encoding="utf-8"))["program"] == "hsql"
2699
2700
2701 def test_info_is_in_the_help(hsql: Hsql) -> None:
2702 res = hsql("--help")
2703 assert res.exit_code == ExitCode.OK
2704 assert "--info" in res.output
2705 assert f"{PROGRAM} --info" in res.output
2706
2707
2708 # --- `--catalog`, the mode that lists one level of the catalog ----------------
2709
2710 CATALOG_DDL = (
2711 "create schema analytics; "
2712 "create table analytics.orders "
2713 "(id bigint, customer_id bigint, total decimal(18,2)); "
2714 "create view analytics.order_summary as select 1 as n; "
2715 'create schema "empty schema"; '
2716 'create schema "my.schema"; '
2717 'create table "my.schema"."t" (n bigint); '
2718 "create schema \u5206\u6790"
2719 )
2720 """Two levels below the database, a node with no children, and two labels a path
2721 cannot spell without quoting one and measuring the other in terminal cells."""
2722
2723
2724 def cells(stdout: str) -> list[list[str]]:
2725 """One `-tA` listing, as rows of cells."""
2726 return [row.split("|") for row in stdout.splitlines()]
2727
2728
2729 def path_of(stdout: str, name: str) -> str:
2730 """The path cell of the row named `name`, which lists that item's children."""
2731 return next(row[0] for row in cells(stdout) if row[1] == name)
2732
2733
2734 @pytest.fixture
2735 def catalog_db(hsql: Hsql, tmp_path: Path) -> list[str]:
2736 """The arguments that reach a DuckDB file with a known catalog in it."""
2737 argv = ["-a", "duckdb", "--no-init", str(tmp_path / "cat.db")]
2738 res = hsql(*argv, "--format", "none", "-c", CATALOG_DDL)
2739 assert res.exit_code == ExitCode.OK
2740 return argv
2741
2742
2743 def test_catalog_lists_the_top_level(hsql: Hsql, catalog_db: list[str]) -> None:
2744 res = hsql(*catalog_db, "--catalog", "-tA")
2745 assert res.exit_code == ExitCode.OK
2746 assert res.stdout == 'cat|cat|"cat"|database|db\n'
2747
2748
2749 def test_catalog_lists_one_level_below_path(hsql: Hsql, catalog_db: list[str]) -> None:
2750 res = hsql(*catalog_db, "--catalog", "--path", "cat", "-tA")
2751 assert res.exit_code == ExitCode.OK
2752 assert [row[1] for row in cells(res.stdout)] == [
2753 "analytics",
2754 "empty schema",
2755 "main",
2756 "my.schema",
2757 "\u5206\u6790",
2758 ]
2759
2760
2761 def test_catalog_describes_a_relation_by_listing_it(
2762 hsql: Hsql, catalog_db: list[str]
2763 ) -> None:
2764 """There is no second mode for describing: a relation's children are its
2765 columns, with their types and their quoted identifiers."""
2766 res = hsql(*catalog_db, "--catalog", "--path", "cat.analytics.orders", "-tA")
2767 assert res.exit_code == ExitCode.OK
2768 assert cells(res.stdout) == [
2769 [
2770 "cat.analytics.orders.customer_id",
2771 "customer_id",
2772 '"customer_id"',
2773 "BIGINT",
2774 "##",
2775 ],
2776 ["cat.analytics.orders.id", "id", '"id"', "BIGINT", "##"],
2777 ["cat.analytics.orders.total", "total", '"total"', "DECIMAL(18,2)", "#.#"],
2778 ]
2779
2780
2781 def test_every_level_reports_the_type_its_database_calls_it(
2782 hsql: Hsql, catalog_db: list[str]
2783 ) -> None:
2784 """`type` is the adapter's own vocabulary, not one core invented for it."""
2785 res = hsql(*catalog_db, "--catalog", "--path", "cat.analytics", "-tA")
2786 assert res.exit_code == ExitCode.OK
2787 assert [(row[1], row[3]) for row in cells(res.stdout)] == [
2788 ("order_summary", "VIEW"),
2789 ("orders", "BASE TABLE"),
2790 ]
2791
2792 res = hsql(*catalog_db, "--catalog", "--path", "cat", "-tA")
2793 assert res.exit_code == ExitCode.OK
2794 assert {row[3] for row in cells(res.stdout)} == {"schema"}
2795
2796
2797 def test_an_item_with_no_type_keeps_its_short_label(tmp_path: Path) -> None:
2798 """The degradation path, which no in-tree adapter takes: `type` is beside
2799 `type_label` rather than instead of it, so a listing still says what these
2800 things are."""
2801 from harlequin.adapter import HarlequinConnection
2802 from harlequin.catalog import Catalog, CatalogItem
2803 from harlequin.hsql.modes import catalog as catalog_mode
2804 from harlequin.layout import LayoutOptions
2805 from harlequin.navigate import CatalogPath
2806
2807 class UntypedConnection:
2808 def get_catalog(self) -> Catalog:
2809 return Catalog(
2810 items=[
2811 CatalogItem(
2812 qualified_identifier='"t"',
2813 query_name='"t"',
2814 label="t",
2815 type_label="t",
2816 )
2817 ]
2818 )
2819
2820 destination = tmp_path / "listing.csv"
2821 with destination.open("wb") as out:
2822 catalog_mode.report(
2823 out,
2824 connection=cast("HarlequinConnection", UntypedConnection()),
2825 path=CatalogPath(),
2826 format_name="csv",
2827 layout_options=LayoutOptions(),
2828 file_options={},
2829 )
2830 assert destination.read_text(encoding="utf-8").splitlines() == [
2831 "path,name,query_name,type,type_label",
2832 't,t,"""t""",,t',
2833 ]
2834
2835
2836 @pytest.mark.parametrize(
2837 ("adapter", "levels", "type_names"),
2838 [
2839 ("duckdb", ["main", "t"], ["BIGINT", "VARCHAR"]),
2840 ("sqlite", ["t"], ["bigint", "varchar"]),
2841 ],
2842 )
2843 def test_type_answers_for_every_bundled_adapter(
2844 hsql: Hsql,
2845 tmp_path: Path,
2846 adapter: str,
2847 levels: list[str],
2848 type_names: list[str],
2849 ) -> None:
2850 """Both in-tree adapters populate it, out of introspection they already do.
2851
2852 Each spells a type its own way, which is the point of carrying the
2853 database's own name for it rather than a normalized one.
2854 """
2855 argv = ["-a", adapter, "--no-init", str(tmp_path / f"{adapter}.db")]
2856 res = hsql(*argv, "--format", "none", "-c", "create table t (n bigint, s varchar)")
2857 assert res.exit_code == ExitCode.OK, res.stderr
2858
2859 res = hsql(*argv, "--catalog", "-tA")
2860 assert res.exit_code == ExitCode.OK
2861 database_path = cells(res.stdout)[0][0]
2862
2863 res = hsql(*argv, "--catalog", "--path", ".".join([database_path, *levels]), "-tA")
2864 assert res.exit_code == ExitCode.OK, res.stderr
2865 assert [(row[1], row[3]) for row in cells(res.stdout)] == [
2866 ("n", type_names[0]),
2867 ("s", type_names[1]),
2868 ]
2869
2870
2871 def test_the_path_column_is_what_lists_that_items_children(
2872 hsql: Hsql, catalog_db: list[str]
2873 ) -> None:
2874 """Walking a catalog is copying a cell out of the last answer.
2875
2876 A path an agent has to spell for itself is one it will spell wrong for a
2877 label with a dot in it, which is the case this walks through.
2878 """
2879 path = ""
2880 for name in ("cat", "my.schema", "t"):
2881 argv = ["--catalog", *(["--path", path] if path else [])]
2882 res = hsql(*catalog_db, *argv, "-tA")
2883 assert res.exit_code == ExitCode.OK, res.stderr
2884 path = path_of(res.stdout, name)
2885 assert path == 'cat."my.schema".t'
2886
2887 res = hsql(*catalog_db, "--catalog", "--path", path, "-tA")
2888 assert res.exit_code == ExitCode.OK
2889 assert [row[1] for row in cells(res.stdout)] == ["n"]
2890
2891
2892 def test_catalog_measures_a_label_in_terminal_cells(
2893 hsql: Hsql, catalog_db: list[str]
2894 ) -> None:
2895 """A listing is laid out like any other result set: two ideographs are four
2896 cells, where `len()` would call them two."""
2897 res = hsql(*catalog_db, "--catalog", "--path", "cat")
2898 assert res.exit_code == ExitCode.OK
2899 # the path column is as wide as `cat.empty schema` and the name column as
2900 # wide as `empty schema`; measured with len() these would be two cells short
2901 assert " cat.\u5206\u6790 | \u5206\u6790 |" in res.stdout
2902
2903
2904 def test_catalog_query_name_is_the_adapters_own_quoting(
2905 hsql: Hsql, catalog_db: list[str]
2906 ) -> None:
2907 """The reason it is a column: the agent never guesses at a spelling."""
2908 res = hsql(*catalog_db, "--catalog", "--path", "cat.analytics", "-tA")
2909 assert res.exit_code == ExitCode.OK
2910 assert '"analytics"."orders"' in res.stdout
2911
2912
2913 def test_a_trailing_wildcard_filters_one_level(
2914 hsql: Hsql, catalog_db: list[str]
2915 ) -> None:
2916 res = hsql(*catalog_db, "--catalog", "--path", "cat.analytics.order_s*", "-tA")
2917 assert res.exit_code == ExitCode.OK
2918 assert [row[1] for row in cells(res.stdout)] == ["order_summary"]
2919
2920
2921 def test_an_interior_wildcard_is_a_usage_error(
2922 hsql: Hsql, catalog_db: list[str]
2923 ) -> None:
2924 """It cannot be answered in one round trip, so it is refused rather than
2925 quietly walked."""
2926 res = hsql(*catalog_db, "--catalog", "--path", "cat.*.orders")
2927 assert res.exit_code == ExitCode.USAGE
2928 assert res.stdout == ""
2929 assert "wildcard" in res.stderr
2930
2931
2932 def test_a_path_that_names_nothing_says_what_is_there(
2933 hsql: Hsql, catalog_db: list[str]
2934 ) -> None:
2935 res = hsql(*catalog_db, "--catalog", "--path", "cat.analytic")
2936 assert res.exit_code == ExitCode.USAGE
2937 assert res.stdout == ""
2938 assert "Did you mean analytics?" in res.stderr
2939
2940
2941 def test_a_node_with_no_children_is_zero_rows(
2942 hsql: Hsql, catalog_db: list[str]
2943 ) -> None:
2944 """Not an error: an empty schema is an answer, and the footer says so."""
2945 res = hsql(*catalog_db, "--catalog", "--path", 'cat."empty schema"')
2946 assert res.exit_code == ExitCode.OK
2947 assert res.stdout.endswith("(0 rows)\n")
2948
2949
2950 def test_catalog_takes_every_format_a_result_set_does(
2951 hsql: Hsql, catalog_db: list[str]
2952 ) -> None:
2953 """A listing is rows, so it inherits the output layer rather than adding one."""
2954 res = hsql(*catalog_db, "--catalog", "--path", "cat.analytics", "--csv")
2955 assert res.exit_code == ExitCode.OK
2956 assert res.stdout.splitlines()[0] == "path,name,query_name,type,type_label"
2957
2958 res = hsql(*catalog_db, "--catalog", "--path", "cat.analytics", "--json")
2959 assert res.exit_code == ExitCode.OK
2960 assert [row["name"] for row in json.loads(res.stdout)] == [
2961 "order_summary",
2962 "orders",
2963 ]
2964
2965
2966 def test_catalog_goes_to_the_file_dash_o_names(
2967 hsql: Hsql, catalog_db: list[str], tmp_path: Path
2968 ) -> None:
2969 destination = tmp_path / "catalog.csv"
2970 res = hsql(*catalog_db, "--catalog", "-o", str(destination), "--csv")
2971 assert res.exit_code == ExitCode.OK
2972 assert res.stdout == ""
2973 assert destination.read_text(encoding="utf-8").splitlines()[1].startswith("cat,cat")
2974
2975
2976 def test_catalog_writes_nothing_under_format_none(
2977 hsql: Hsql, catalog_db: list[str]
2978 ) -> None:
2979 res = hsql(*catalog_db, "--catalog", "--format", "none")
2980 assert res.exit_code == ExitCode.OK
2981 assert res.stdout == ""
2982
2983
2984 def test_display_rows_caps_a_listing(hsql: Hsql, catalog_db: list[str]) -> None:
2985 """A listing with four hundred rows in it is a display problem, and the
2986 layouts already solved it."""
2987 res = hsql(*catalog_db, "--catalog", "--path", "cat", "--display-rows", "2")
2988 assert res.exit_code == ExitCode.OK
2989 assert res.stdout.endswith("(2 of 5 rows)\n")
2990
2991
2992 def test_display_rows_says_on_stderr_what_the_footer_cannot(
2993 hsql: Hsql, catalog_db: list[str]
2994 ) -> None:
2995 res = hsql(*catalog_db, "--catalog", "--path", "cat", "--display-rows", "2", "-t")
2996 assert res.exit_code == ExitCode.OK
2997 assert len(res.stdout.splitlines()) == 2
2998 assert "printed 2 of 5 rows" in res.stderr
2999
3000
3001 def test_limit_says_it_did_not_reach_the_listing(
3002 hsql: Hsql, catalog_db: list[str]
3003 ) -> None:
3004 """It is the hard fetch limit, and a listing is however many objects the
3005 adapter reported. Silence would read as a limit that was applied."""
3006 res = hsql(*catalog_db, "--catalog", "--path", "cat", "--limit", "1", "-tA")
3007 assert res.exit_code == ExitCode.OK
3008 assert len(res.stdout.splitlines()) == 5
3009 assert "--limit" in res.stderr and "no effect" in res.stderr
3010
3011
3012 def test_limit_left_at_its_default_says_nothing(
3013 hsql: Hsql, catalog_db: list[str]
3014 ) -> None:
3015 res = hsql(*catalog_db, "--catalog", "-tA")
3016 assert res.exit_code == ExitCode.OK
3017 assert res.stderr == ""
3018
3019
3020 def test_catalog_does_not_run_sql(hsql: Hsql, catalog_db: list[str]) -> None:
3021 res = hsql(*catalog_db, "--catalog", "-c", "select 1")
3022 assert res.exit_code == ExitCode.USAGE
3023 assert res.stdout == ""
3024 assert "does not run SQL" in res.stderr
3025
3026
3027 @pytest.mark.parametrize("other", [["--info"], ["--spec"], ["--config", "show"]])
3028 def test_catalog_beside_another_mode_is_a_usage_error(
3029 hsql: Hsql, other: list[str]
3030 ) -> None:
3031 res = hsql("--catalog", *other)
3032 assert res.exit_code == ExitCode.USAGE
3033 assert res.stdout == ""
3034 assert "--catalog" in res.stderr
3035
3036
3037 def test_path_without_catalog_is_a_usage_error(hsql: Hsql, duck: list[str]) -> None:
3038 """A flag that silently did nothing is the thing this command does not have."""
3039 res = hsql(*duck, "--path", "main", "-c", "select 1")
3040 assert res.exit_code == ExitCode.USAGE
3041 assert res.stdout == ""
3042 assert "--path must be used with --catalog" in res.stderr
3043
3044
3045 def test_catalog_carries_the_adapters_options(
3046 hsql: Hsql, catalog_db: list[str]
3047 ) -> None:
3048 """It connects, so unlike the other modes it takes what a connection takes.
3049
3050 `--force-install-extensions` because it reaches the adapter and changes
3051 nothing on the way: with no `--extension` beside it there is nothing to
3052 install.
3053 """
3054 res = hsql(*catalog_db, "--catalog", "--force-install-extensions", "-tA")
3055 assert res.exit_code == ExitCode.OK
3056 assert res.stdout == 'cat|cat|"cat"|database|db\n'
3057
3058
3059 def test_catalog_reads_the_profile_a_run_would(
3060 hsql: Hsql, catalog_db: list[str], tmp_path: Path
3061 ) -> None:
3062 """It connects like a run, so it is configured like one."""
3063 config_file = tmp_path / "profile.toml"
3064 # json.dumps, not an f-string: TOML reads a backslash in a basic string as
3065 # an escape, so a Windows path would be a parse error rather than a path.
3066 config_file.write_text(
3067 f'[profiles.cat]\nadapter = "duckdb"\n'
3068 f"conn_str = [{json.dumps(catalog_db[-1])}]\n"
3069 "no_init = true\n"
3070 )
3071 res = hsql("--config-path", str(config_file), "-P", "cat", "--catalog", "-tA")
3072 assert res.exit_code == ExitCode.OK
3073 assert res.stdout == 'cat|cat|"cat"|database|db\n'
3074
3075
3076 def test_catalog_answers_for_every_bundled_adapter(
3077 hsql: Hsql, both_adapters: list[str]
3078 ) -> None:
3079 """Every adapter names its levels differently, and every one has a top."""
3080 res = hsql(*both_adapters, "--catalog", "-tA")
3081 assert res.exit_code == ExitCode.OK
3082 assert [row[4] for row in cells(res.stdout)] == ["db"]
3083
3084
3085 def test_catalog_is_in_the_help(hsql: Hsql) -> None:
3086 res = hsql("--help")
3087 assert res.exit_code == ExitCode.OK
3088 assert "--catalog" in res.output
3089 assert "--path" in res.output
3090 assert f"{PROGRAM} --catalog --path" in res.output
3091
3092
3093 # --- `--catalog-search`, which searches a catalog instead of walking it -----
3094
3095
3096 def test_catalog_search_reaches_every_level_in_one_ask(
3097 hsql: Hsql, catalog_db: list[str]
3098 ) -> None:
3099 """The question a walk cannot answer: where the thing named that lives,
3100 whatever level it is on."""
3101 res = hsql(*catalog_db, "--catalog-search", "order", "-tA")
3102 assert res.exit_code == ExitCode.OK, res.stderr
3103 assert [(row[0], row[3]) for row in cells(res.stdout)] == [
3104 ("cat.analytics.order_summary", "VIEW"),
3105 ("cat.analytics.orders", "BASE TABLE"),
3106 ]
3107
3108
3109 def test_catalog_search_matches_a_column_wherever_it_is(
3110 hsql: Hsql, catalog_db: list[str]
3111 ) -> None:
3112 res = hsql(*catalog_db, "--catalog-search", "CUSTOMER_ID", "-tA")
3113 assert res.exit_code == ExitCode.OK, res.stderr
3114 assert cells(res.stdout) == [
3115 [
3116 "cat.analytics.orders.customer_id",
3117 "customer_id",
3118 '"customer_id"',
3119 "BIGINT",
3120 "##",
3121 ]
3122 ]
3123
3124
3125 def test_catalog_search_matches_the_levels_above_a_relation_too(
3126 hsql: Hsql, catalog_db: list[str]
3127 ) -> None:
3128 """A caller searching a catalog does not know its shape, so zero rows has
3129 to mean nothing is named that -- not that the level was not looked at."""
3130 res = hsql(*catalog_db, "--catalog-search", "analytics", "-tA")
3131 assert res.exit_code == ExitCode.OK, res.stderr
3132 assert [(row[0], row[4]) for row in cells(res.stdout)] == [("cat.analytics", "sch")]
3133
3134
3135 def test_a_found_path_is_a_path_catalog_walks(
3136 hsql: Hsql, catalog_db: list[str]
3137 ) -> None:
3138 """The two modes build their rows the same way, so a cell copied out of one
3139 is an argument to the other -- including for a label with a dot in it."""
3140 res = hsql(*catalog_db, "--catalog-search", "t", "-tA")
3141 assert res.exit_code == ExitCode.OK, res.stderr
3142 found = path_of(res.stdout, "t")
3143 assert found == 'cat."my.schema".t'
3144
3145 res = hsql(*catalog_db, "--catalog", "--path", found, "-tA")
3146 assert res.exit_code == ExitCode.OK, res.stderr
3147 assert [row[1] for row in cells(res.stdout)] == ["n"]
3148
3149
3150 def test_path_scopes_a_find(hsql: Hsql, catalog_db: list[str]) -> None:
3151 res = hsql(*catalog_db, "--catalog-search", "n", "--path", 'cat."my.schema"', "-tA")
3152 assert res.exit_code == ExitCode.OK, res.stderr
3153 assert [row[0] for row in cells(res.stdout)] == ['cat."my.schema".t.n']
3154
3155
3156 def test_a_scope_that_names_nothing_says_what_is_there(
3157 hsql: Hsql, catalog_db: list[str]
3158 ) -> None:
3159 res = hsql(*catalog_db, "--catalog-search", "orders", "--path", "cat.analytic")
3160 assert res.exit_code == ExitCode.USAGE
3161 assert res.stdout == ""
3162 assert "Did you mean analytics?" in res.stderr
3163
3164
3165 def test_a_wildcard_scope_is_a_usage_error(hsql: Hsql, catalog_db: list[str]) -> None:
3166 """`--catalog-search` already matches on a term; a second filter over the
3167 same names is the same question asked twice."""
3168 res = hsql(*catalog_db, "--catalog-search", "orders", "--path", "cat.analytic*")
3169 assert res.exit_code == ExitCode.USAGE
3170 assert res.stdout == ""
3171 assert "wildcard" in res.stderr
3172
3173
3174 def test_a_term_that_matches_nothing_is_zero_rows(
3175 hsql: Hsql, catalog_db: list[str]
3176 ) -> None:
3177 res = hsql(*catalog_db, "--catalog-search", "nothing-is-called-this")
3178 assert res.exit_code == ExitCode.OK
3179 assert res.stdout.endswith("(0 rows)\n")
3180
3181
3182 def test_a_blank_term_is_a_usage_error(hsql: Hsql, catalog_db: list[str]) -> None:
3183 """`--catalog-search "$NAME"` with nothing in NAME is a mistake, not a
3184 request for the whole catalog."""
3185 res = hsql(*catalog_db, "--catalog-search", "")
3186 assert res.exit_code == ExitCode.USAGE
3187 assert res.stdout == ""
3188 assert "--catalog-search needs a term" in res.stderr
3189
3190
3191 def test_catalog_search_refuses_an_adapter_that_does_not_declare_it(
3192 hsql: Hsql, monkeypatch: pytest.MonkeyPatch
3193 ) -> None:
3194 """Refused before it connects: an adapter that cannot search is one whose
3195 catalog would have to be walked, and a `--catalog-search` that quietly
3196 walked it is the round-trip cliff this mode exists to avoid."""
3197 from harlequin.adapter import HarlequinAdapter, HarlequinConnection
3198
3199 class Unsearchable(HarlequinAdapter):
3200 ADAPTER_OPTIONS = None
3201
3202 def __init__(self, conn_str: Sequence[str], **options: Any) -> None:
3203 pass
3204
3205 def connect(self) -> HarlequinConnection:
3206 raise AssertionError("connected before checking the declaration")
3207
3208 entry_point = MagicMock()
3209 entry_point.name = "unsearchable"
3210 entry_point.load.return_value = Unsearchable
3211 monkeypatch.setattr("harlequin.plugins.entry_points", lambda group: [entry_point])
3212
3213 res = hsql("-a", "unsearchable", "--catalog-search", "orders")
3214 assert res.exit_code == ExitCode.USAGE
3215 assert res.stdout == ""
3216 assert "unsearchable" in res.stderr
3217 assert "--catalog" in res.stderr and "--info" in res.stderr
3218
3219
3220 def test_catalog_search_takes_every_format_a_result_set_does(
3221 hsql: Hsql, catalog_db: list[str]
3222 ) -> None:
3223 res = hsql(*catalog_db, "--catalog-search", "order", "--csv")
3224 assert res.exit_code == ExitCode.OK
3225 assert res.stdout.splitlines()[0] == "path,name,query_name,type,type_label"
3226
3227 res = hsql(*catalog_db, "--catalog-search", "order", "--json")
3228 assert res.exit_code == ExitCode.OK
3229 assert [row["name"] for row in json.loads(res.stdout)] == [
3230 "order_summary",
3231 "orders",
3232 ]
3233
3234
3235 def test_catalog_search_goes_to_the_file_dash_o_names(
3236 hsql: Hsql, catalog_db: list[str], tmp_path: Path
3237 ) -> None:
3238 destination = tmp_path / "found.csv"
3239 res = hsql(
3240 *catalog_db, "--catalog-search", "orders", "-o", str(destination), "--csv"
3241 )
3242 assert res.exit_code == ExitCode.OK
3243 assert res.stdout == ""
3244 assert (
3245 destination.read_text(encoding="utf-8")
3246 .splitlines()[1]
3247 .startswith("cat.analytics.orders,orders")
3248 )
3249
3250
3251 def test_display_rows_caps_a_find(hsql: Hsql, catalog_db: list[str]) -> None:
3252 res = hsql(*catalog_db, "--catalog-search", "order", "--display-rows", "1")
3253 assert res.exit_code == ExitCode.OK
3254 assert res.stdout.endswith("(1 of 2 rows)\n")
3255
3256
3257 def test_limit_says_it_did_not_reach_the_find(
3258 hsql: Hsql, catalog_db: list[str]
3259 ) -> None:
3260 """It is the hard fetch limit, and a search is however many objects the
3261 adapter reported. Silence would read as a limit that was applied."""
3262 res = hsql(*catalog_db, "--catalog-search", "order", "--limit", "1", "-tA")
3263 assert res.exit_code == ExitCode.OK
3264 assert len(res.stdout.splitlines()) == 2
3265 assert "--limit" in res.stderr and "no effect" in res.stderr
3266
3267
3268 def test_catalog_search_does_not_run_sql(hsql: Hsql, catalog_db: list[str]) -> None:
3269 res = hsql(*catalog_db, "--catalog-search", "orders", "-c", "select 1")
3270 assert res.exit_code == ExitCode.USAGE
3271 assert res.stdout == ""
3272 assert "does not run SQL" in res.stderr
3273
3274
3275 @pytest.mark.parametrize(
3276 "other", [["--catalog"], ["--info"], ["--spec"], ["--config", "show"]]
3277 )
3278 def test_catalog_search_beside_another_mode_is_a_usage_error(
3279 hsql: Hsql, other: list[str]
3280 ) -> None:
3281 res = hsql("--catalog-search", "orders", *other)
3282 assert res.exit_code == ExitCode.USAGE
3283 assert res.stdout == ""
3284 assert "--catalog-search" in res.stderr
3285
3286
3287 @pytest.mark.parametrize("adapter", ["duckdb", "sqlite"])
3288 def test_catalog_search_answers_for_every_bundled_adapter(
3289 hsql: Hsql, tmp_path: Path, adapter: str
3290 ) -> None:
3291 """Both in-tree adapters implement the search, rather than declaring the
3292 capability and leaving it to the ecosystem. Each spells the path to what it
3293 found its own way, and each spells one `--catalog --path` walks."""
3294 argv = ["-a", adapter, "--no-init", str(tmp_path / f"{adapter}.db")]
3295 res = hsql(
3296 *argv, "--format", "none", "-c", "create table orders (customer_id bigint)"
3297 )
3298 assert res.exit_code == ExitCode.OK, res.stderr
3299
3300 res = hsql(*argv, "--catalog-search", "customer_id", "-tA")
3301 assert res.exit_code == ExitCode.OK, res.stderr
3302 assert [row[1] for row in cells(res.stdout)] == ["customer_id"]
3303 assert path_of(res.stdout, "customer_id").endswith("orders.customer_id")
3304
3305
3306 def test_every_bundled_adapter_declares_catalog_search(hsql: Hsql) -> None:
3307 """`--info` is where a caller learns which adapters can search."""
3308 res = hsql("--info")
3309 assert res.exit_code == ExitCode.OK
3310 adapters = json.loads(res.stdout)["adapters"]
3311 assert all(
3312 adapters[name]["capabilities"]["implements_catalog_search"]
3313 for name in ("duckdb", "sqlite")
3314 )
3315
3316
3317 def test_catalog_search_is_in_the_help(hsql: Hsql) -> None:
3318 res = hsql("--help")
3319 assert res.exit_code == ExitCode.OK
3320 assert "--catalog-search" in res.output
3321 assert f"{PROGRAM} --catalog-search" in res.output
3322
3323
3324 # --- `--read-only`, and the capability it needs -------------------------------
3325
3326
3327 @pytest.fixture
3328 def declares_nothing(monkeypatch: pytest.MonkeyPatch) -> str:
3329 """The name of an installed adapter that declares no capability at all.
3330
3331 Which is every adapter the day before it adds a declaration, so this is
3332 what a refusal has to be right about -- and `connect()` raising is what
3333 proves the refusal came first.
3334 """
3335 from harlequin.adapter import HarlequinAdapter, HarlequinConnection
3336
3337 class DeclaresNothing(HarlequinAdapter):
3338 ADAPTER_OPTIONS = None
3339
3340 def __init__(self, conn_str: Sequence[str], **options: Any) -> None:
3341 pass
3342
3343 def connect(self) -> HarlequinConnection:
3344 raise AssertionError("connected before checking the declaration")
3345
3346 entry_point = MagicMock()
3347 entry_point.name = "undeclared"
3348 entry_point.load.return_value = DeclaresNothing
3349 monkeypatch.setattr("harlequin.plugins.entry_points", lambda group: [entry_point])
3350 return "undeclared"
3351
3352
3353 def test_read_only_refuses_an_adapter_that_does_not_declare_it(
3354 hsql: Hsql, declares_nothing: str
3355 ) -> None:
3356 """A flag that no-ops is worse than one that is absent.
3357
3358 An adapter drops an option it does not recognize, so a run that believed it
3359 was read-only would write. Refused before it connects, which is the whole
3360 of what the flag promises.
3361 """
3362 res = hsql("-a", declares_nothing, "--read-only", "-c", "select 1")
3363 assert res.exit_code == ExitCode.USAGE
3364 assert res.stdout == ""
3365 assert declares_nothing in res.stderr
3366 assert "--read-only" in res.stderr and "--info" in res.stderr
3367
3368
3369 def test_read_only_from_a_profile_is_refused_the_same_way(
3370 hsql: Hsql, declares_nothing: str, tmp_path: Path
3371 ) -> None:
3372 """The spelling a human is likelier to have used, and to trust.
3373
3374 `read_only = true` in a profile is a promise made once and relied on by
3375 every invocation that loads it, so it is refused where the flag is.
3376 """
3377 path = tmp_path / ".harlequin.toml"
3378 path.write_text("[profiles.prod]\nread_only = true\n")
3379 res = hsql(
3380 "--config-path",
3381 str(path),
3382 "-P",
3383 "prod",
3384 "-a",
3385 declares_nothing,
3386 "-c",
3387 "select 1",
3388 )
3389 assert res.exit_code == ExitCode.USAGE
3390 assert res.stdout == ""
3391 assert declares_nothing in res.stderr
3392 assert "profile" in res.stderr
3393
3394
3395 def test_read_only_is_refused_ahead_of_the_mode_that_would_connect(
3396 hsql: Hsql, declares_nothing: str
3397 ) -> None:
3398 """`--catalog` connects too, so it meets the same refusal."""
3399 res = hsql("-a", declares_nothing, "--read-only", "--catalog")
3400 assert res.exit_code == ExitCode.USAGE
3401 assert res.stdout == ""
3402 assert declares_nothing in res.stderr
3403
3404
3405 def test_read_only_is_refused_before_it_is_written_into_a_profile(
3406 hsql: Hsql, declares_nothing: str, init_dirs: tuple[Path, Path]
3407 ) -> None:
3408 """`--config init` imports the adapter to write the options it declares, so
3409 it can refuse a profile that names one and a read-only it cannot honor --
3410 which is a profile no run would start under."""
3411 cwd, _ = init_dirs
3412 res = hsql("--config", "init", "-P", "prod", "-a", declares_nothing, "--read-only")
3413 assert res.exit_code == ExitCode.USAGE
3414 assert declares_nothing in res.stderr
3415 assert not (cwd / ".harlequin.toml").exists()
3416
3417
3418 def test_config_validate_reports_a_read_only_the_adapter_cannot_do(
3419 hsql: Hsql, declares_nothing: str, config_dirs: tuple[Path, Path]
3420 ) -> None:
3421 """`--config validate` imports an adapter per profile already, so it can
3422 say that a profile pairs one with a read-only it cannot honor."""
3423 cwd, _ = config_dirs
3424 (cwd / ".harlequin.toml").write_text(
3425 f"[profiles.prod]\nadapter = '{declares_nothing}'\nread_only = true\n"
3426 )
3427
3428 # `-a` only to satisfy the choice of installed adapters; the mode reads the
3429 # adapter each profile names
3430 res = hsql("--config", "validate", "-a", declares_nothing, "-tA")
3431 assert res.exit_code == ExitCode.USAGE
3432 file, key, problem, _ = res.stdout.strip().split("|")
3433 assert file == str(cwd / ".harlequin.toml")
3434 assert key == "profiles.prod.read_only"
3435 assert declares_nothing in problem
3436
3437
3438 @pytest.mark.parametrize(
3439 "mode", [["--info"], ["--spec"], ["--config", "show"], ["--config", "validate"]]
3440 )
3441 def test_read_only_does_not_refuse_a_mode_that_reads_no_database(
3442 hsql: Hsql, declares_nothing: str, mode: list[str], config_dirs: tuple[Path, Path]
3443 ) -> None:
3444 """None of them can write whatever they are told -- and two of them are
3445 where a caller finds out which adapter they are on and where its read-only
3446 came from, which is no use if the flag refuses them."""
3447 res = hsql(*mode, "-a", declares_nothing, "--read-only")
3448 assert res.exit_code == ExitCode.OK, res.stderr
3449
3450
3451 def test_info_reports_an_adapter_that_cannot_be_read_only(
3452 hsql: Hsql, declares_nothing: str
3453 ) -> None:
3454 """`--info` is where the refusal points, so it answers rather than joining
3455 in."""
3456 res = hsql("--info", "-a", declares_nothing, "--read-only")
3457 assert res.exit_code == ExitCode.OK
3458 capabilities = info_of(res)["adapters"][declares_nothing]["capabilities"]
3459 assert capabilities["implements_read_only"] is False
3460
3461
3462 def test_every_bundled_adapter_declares_read_only(hsql: Hsql) -> None:
3463 """`--info` is where a caller learns which adapters can be read-only."""
3464 adapters = info_of(hsql("--info"))["adapters"]
3465 assert all(
3466 adapters[name]["capabilities"]["implements_read_only"]
3467 for name in ("duckdb", "sqlite")
3468 )
3469
3470
3471 def one_row_db(adapter: str, path: Path) -> list[str]:
3472 """A database with a table in it, written by the driver itself.
3473
3474 Built outside hsql because a connection this process still holds is one
3475 duckdb will not reopen under a different configuration -- and read-only is
3476 a different configuration.
3477 """
3478 if adapter == "duckdb":
3479 import duckdb
3480
3481 duck = duckdb.connect(str(path))
3482 duck.execute("create table t as select 1 as n")
3483 duck.close()
3484 else:
3485 import sqlite3
3486
3487 lite = sqlite3.connect(str(path))
3488 lite.execute("create table t as select 1 as n")
3489 lite.commit()
3490 lite.close()
3491 return ["-a", adapter, "--no-init", str(path)]
3492
3493
3494 @pytest.mark.parametrize("adapter", ["duckdb", "sqlite"])
3495 def test_read_only_stops_a_write_on_every_bundled_adapter(
3496 hsql: Hsql, tmp_path: Path, adapter: str
3497 ) -> None:
3498 """The flag's whole job, end to end: reads answer, writes fail."""
3499 argv = one_row_db(adapter, tmp_path / f"{adapter}.db")
3500
3501 res = hsql(*argv, "--read-only", "-c", "select n from t", "-tA")
3502 assert res.exit_code == ExitCode.OK, res.stderr
3503 assert res.stdout == "1\n"
3504
3505 res = hsql(*argv, "--read-only", "-c", "insert into t values (2)")
3506 assert res.exit_code == ExitCode.QUERY
3507 assert res.stdout == ""
3508 assert res.stderr
3509
3510
3511 @pytest.mark.parametrize("spelling", ["-r", "--read-only"])
3512 def test_read_only_means_the_same_thing_however_it_is_spelled(
3513 hsql: Hsql, tmp_path: Path, spelling: str
3514 ) -> None:
3515 argv = one_row_db("sqlite", tmp_path / "one.db")
3516
3517 res = hsql(*argv, spelling, "-c", "insert into t values (2)")
3518 assert res.exit_code == ExitCode.QUERY
3519 assert res.stdout == ""
3520
3521
3522 def test_the_single_dash_long_spelling_is_not_one(hsql: Hsql, tmp_path: Path) -> None:
3523 """`-readonly` is two spellings' worth of nothing: `-r` and `--read-only`
3524 are what a caller has, on both commands and for every adapter."""
3525 argv = one_row_db("sqlite", tmp_path / "one.db")
3526
3527 res = hsql(*argv, "-readonly", "-c", "insert into t values (2)")
3528 assert res.exit_code == ExitCode.USAGE
3529 assert res.stdout == ""
3530
3531
3532 def test_read_only_is_in_the_help(hsql: Hsql) -> None:
3533 """On the adapter-agnostic surface, because the refusal is too."""
3534 res = hsql("--help")
3535 assert res.exit_code == ExitCode.OK
3536 assert "--read-only" in res.output
3537
3538
3539 # --- secrets, and the promise that none of them is printed -------------------
3540
3541 SECRET = "hunter2-and-then-some"
3542 """One value, in a profile and in a connection string, asserted for negatively.
3543
3544 Long enough that finding it in the output is unambiguous, and distinctive
3545 enough that a substring search over every byte written means what it says.
3546 """
3547
3548
3549 @pytest.fixture
3550 def secret_config(config_dirs: tuple[Path, Path]) -> Path:
3551 """A profile with a secret in an option *and* in a connection string.
3552
3553 Both halves, because they are hidden by two different mechanisms:
3554 `md_token` is masked because the DuckDB adapter declares it secret, and the
3555 token in the connection string because `redact_conn_str` reads the DSN.
3556 """
3557 cwd, _ = config_dirs
3558 path = cwd / ".harlequin.toml"
3559 path.write_text(
3560 'default_profile = "md"\n'
3561 "[profiles.md]\n"
3562 'adapter = "duckdb"\n'
3563 f'conn_str = [ "md:my_db?motherduck_token={SECRET}" ]\n'
3564 f'md_token = "{SECRET}"\n'
3565 "limit = 500\n"
3566 )
3567 return path
3568
3569
3570 def test_info_prints_no_secret(hsql: Hsql, secret_config: Path) -> None:
3571 """The document a caller pastes into an issue."""
3572 res = hsql("--info")
3573 assert res.exit_code == ExitCode.OK
3574 assert SECRET not in res.output
3575 options = json.loads(res.stdout)["profile"]["options"]
3576 assert options["md_token"] == "********"
3577 assert options["conn_str"] == ["md:my_db?motherduck_token=********"]
3578 # and still the document it was: what a reader needs is all still there
3579 assert options["limit"] == 500
3580 assert options["adapter"] == "duckdb"
3581
3582
3583 def test_config_show_prints_no_secret(hsql: Hsql, secret_config: Path) -> None:
3584 """Masked without importing an adapter to ask, which is why the fallback to
3585 the key's name exists."""
3586 res = hsql("--config", "show")
3587 assert res.exit_code == ExitCode.OK
3588 assert SECRET not in res.output
3589 assert 'md_token = "********"' in res.stdout
3590 assert "motherduck_token=********" in res.stdout
3591 # the provenance is the whole point of the mode, and survives
3592 assert f"# from {secret_config}" in res.stdout
3593
3594
3595 def test_config_show_masks_a_secret_the_key_name_does_not_give_away(
3596 hsql: Hsql, config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch
3597 ) -> None:
3598 """The reason this mode imports the adapters its profiles name.
3599
3600 A key called `hush` is not one core could have guessed at, and guessing is
3601 what the fallback does. Only the adapter knows, so the mode asks it.
3602 """
3603 from harlequin.options import TextOption
3604
3605 monkeypatch.setattr(
3606 "harlequin_duckdb.DuckDbAdapter.ADAPTER_OPTIONS",
3607 [TextOption(name="hush", description="x", secret=True)],
3608 )
3609 cwd, _ = config_dirs
3610 (cwd / ".harlequin.toml").write_text(
3611 f'[profiles.one]\nadapter = "duckdb"\nhush = "{SECRET}"\n'
3612 )
3613 res = hsql("--config", "show")
3614 assert res.exit_code == ExitCode.OK
3615 assert SECRET not in res.output
3616 assert 'hush = "********"' in res.stdout
3617
3618
3619 def test_config_show_asks_the_default_adapter_for_a_profile_that_names_none(
3620 hsql: Hsql, config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch
3621 ) -> None:
3622 """A profile with no `adapter` connects with the default, so that is the
3623 one whose declarations decide what it is hiding."""
3624 from harlequin.options import TextOption
3625
3626 monkeypatch.setattr(
3627 "harlequin_duckdb.DuckDbAdapter.ADAPTER_OPTIONS",
3628 [TextOption(name="hush", description="x", secret=True)],
3629 )
3630 cwd, _ = config_dirs
3631 (cwd / ".harlequin.toml").write_text(f'[profiles.one]\nhush = "{SECRET}"\n')
3632 res = hsql("--config", "show")
3633 assert res.exit_code == ExitCode.OK
3634 assert SECRET not in res.output
3635 assert 'hush = "********"' in res.stdout
3636
3637
3638 def test_config_show_says_when_it_masked_by_name_alone(
3639 hsql: Hsql, config_dirs: tuple[Path, Path]
3640 ) -> None:
3641 """The one path where a value this would have masked might print, so it is
3642 said out loud rather than left for a reader to notice."""
3643 cwd, _ = config_dirs
3644 (cwd / ".harlequin.toml").write_text(
3645 f'[profiles.one]\nadapter = "nonesuch"\npassword = "{SECRET}"\n'
3646 )
3647 res = hsql("--config", "show")
3648 assert res.exit_code == ExitCode.OK
3649 assert SECRET not in res.output
3650 assert 'password = "********"' in res.stdout
3651 assert "could not import nonesuch" in res.stderr
3652
3653
3654 def test_config_show_json_prints_no_secret(hsql: Hsql, secret_config: Path) -> None:
3655 res = hsql("--config", "show", "--json")
3656 assert res.exit_code == ExitCode.OK
3657 assert SECRET not in res.output
3658 profile = json.loads(res.stdout)["profiles"]["md"]["value"]
3659 assert profile["md_token"] == "********"
3660
3661
3662 def test_config_list_profiles_prints_no_secret(hsql: Hsql, secret_config: Path) -> None:
3663 """It prints names rather than values, and this is what says so."""
3664 res = hsql("--config", "list-profiles")
3665 assert res.exit_code == ExitCode.OK
3666 assert SECRET not in res.output
3667 assert "md" in res.stdout
3668
3669
3670 def test_config_validate_prints_no_secret(hsql: Hsql, secret_config: Path) -> None:
3671 res = hsql("--config", "validate")
3672 assert SECRET not in res.output
3673
3674
3675 def test_spec_prints_no_secret_and_says_which_options_are(
3676 hsql: Hsql, secret_config: Path
3677 ) -> None:
3678 """`--spec` publishes no values, and publishes which options hold one.
3679
3680 That key is what teaches an agent not to construct `hsql --md_token
3681 hunter2`, where `ps` and a shell history can read it.
3682 """
3683 res = hsql("--spec", "-a", "duckdb")
3684 assert res.exit_code == ExitCode.OK
3685 assert SECRET not in res.output
3686 options = {
3687 entry["name"]: entry
3688 for entry in json.loads(res.stdout)["adapters"]["duckdb"]["options"]
3689 }
3690 assert options["md_token"]["secret"] is True
3691 assert options["no_init"]["secret"] is False
3692 # both halves of the document answer with the same keys
3693 assert all("secret" in entry for entry in json.loads(res.stdout)["options"])
3694
3695
3696 def test_spec_masks_a_default_an_adapter_shipped_for_a_secret(
3697 hsql: Hsql, monkeypatch: pytest.MonkeyPatch
3698 ) -> None:
3699 """An adapter that ships a default for a secret has shipped the secret, and
3700 this document would otherwise write it down for every installation."""
3701 from harlequin.options import TextOption
3702
3703 monkeypatch.setattr(
3704 "harlequin_duckdb.DuckDbAdapter.ADAPTER_OPTIONS",
3705 [TextOption(name="md_token", description="x", default=SECRET, secret=True)],
3706 )
3707 res = hsql("--spec", "-a", "duckdb")
3708 assert res.exit_code == ExitCode.OK
3709 assert SECRET not in res.output
3710 (option,) = json.loads(res.stdout)["adapters"]["duckdb"]["options"]
3711 assert option["default"] == "********"
3712
3713
3714 def test_an_error_that_echoes_the_connection_string_prints_no_secret(
3715 hsql: Hsql, secret_config: Path, monkeypatch: pytest.MonkeyPatch
3716 ) -> None:
3717 """The backstop, and the case the option layer cannot reach: a driver that
3718 quotes back the DSN it was handed."""
3719
3720 def exploding_connect(self: Any) -> Any:
3721 raise HarlequinConnectionError(f"could not connect to {self.conn_str[0]}")
3722
3723 monkeypatch.setattr(
3724 "harlequin_duckdb.DuckDbAdapter.connect", exploding_connect, raising=True
3725 )
3726 res = hsql("-c", "select 1")
3727 assert res.exit_code == ExitCode.CONNECTION
3728 assert SECRET not in res.output
3729 assert "could not connect to md:my_db?motherduck_token=********" in res.stderr
3730
3731
3732 class _RefusingConnection:
3733 """A connection that refuses every statement, quoting the DSN as it does.
3734
3735 Which is the shape of the failure that matters here: the message comes from
3736 the driver, so nothing in the option layer has had a chance to shape it.
3737 """
3738
3739 def execute(self, query: str) -> Any:
3740 raise HarlequinQueryError(f"rejected: md:my_db?motherduck_token={SECRET}")
3741
3742
3743 def test_stats_prints_no_secret(
3744 hsql: Hsql, secret_config: Path, monkeypatch: pytest.MonkeyPatch
3745 ) -> None:
3746 """`--stats` carries the failure's message, so it carries this promise too.
3747
3748 It is a second channel rather than the same one twice: the error goes to
3749 stderr as prose, and this goes to stderr as JSON a script parses.
3750 """
3751 monkeypatch.setattr(
3752 "harlequin_duckdb.DuckDbAdapter.connect", lambda self: _RefusingConnection()
3753 )
3754 res = hsql("--stats", "-c", "select 1")
3755 assert res.exit_code == ExitCode.QUERY
3756 assert SECRET not in res.output
3757 stats = json.loads(res.stderr.strip().splitlines()[-1])
3758 assert stats["status"] == "error"
3759 assert "motherduck_token=********" in stats["error"]
3760
3761
3762 def test_a_secret_typed_on_the_command_line_is_still_hidden_in_errors(
3763 hsql: Hsql, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
3764 ) -> None:
3765 """Typing one there is the thing `--spec` teaches a caller not to do, and
3766 it is not a reason to print it back."""
3767 monkeypatch.chdir(tmp_path)
3768
3769 def exploding_connect(self: Any) -> Any:
3770 raise HarlequinConnectionError(f"token {self.md_token} rejected")
3771
3772 monkeypatch.setattr("harlequin_duckdb.DuckDbAdapter.connect", exploding_connect)
3773 res = hsql(
3774 "-a", "duckdb", "--no-init", ":memory:", "--md_token", SECRET, "-c", "select 1"
3775 )
3776 assert res.exit_code == ExitCode.CONNECTION
3777 assert SECRET not in res.output
3778 assert "token ******** rejected" in res.stderr
3779
3780
3781 def test_nothing_is_hidden_from_a_run_with_no_secrets(
3782 hsql: Hsql, duck: list[str]
3783 ) -> None:
3784 """The other half: a message with nothing to hide is printed as it is."""
3785 res = hsql(*duck, "-c", "select nope")
3786 assert res.exit_code == ExitCode.QUERY
3787 assert "********" not in res.output
3788 assert "nope" in res.stderr
3789
3790
3791 def test_the_secret_still_reaches_the_adapter(
3792 hsql: Hsql, secret_config: Path, monkeypatch: pytest.MonkeyPatch
3793 ) -> None:
3794 """Redaction is for output. A run that connected with asterisks would be a
3795 worse bug than the one this is fixing."""
3796 seen: dict[str, Any] = {}
3797
3798 def recording_connect(self: Any) -> Any:
3799 seen["md_token"] = self.md_token
3800 seen["conn_str"] = self.conn_str
3801 raise HarlequinConnectionError("stop here")
3802
3803 monkeypatch.setattr("harlequin_duckdb.DuckDbAdapter.connect", recording_connect)
3804 hsql("-c", "select 1")
3805 assert seen["md_token"] == SECRET
3806 assert list(seen["conn_str"]) == [f"md:my_db?motherduck_token={SECRET}"]
3807
3808
3809 # --- `${VAR}`, the environment a config file reads ----------------------------
3810
3811
3812 def test_a_profile_reads_a_variable_from_the_environment(
3813 hsql: Hsql, config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch
3814 ) -> None:
3815 """End to end: a config file that names a variable, and a query that runs.
3816
3817 Which is what the feature is for -- a profile a team shares, and a
3818 credential each of them keeps in their own environment.
3819 """
3820 monkeypatch.setenv("HARLEQUIN_TEST_DB", ":memory:")
3821 cwd, _ = config_dirs
3822 (cwd / ".harlequin.toml").write_text(
3823 'default_profile = "prod"\n'
3824 "[profiles.prod]\n"
3825 'adapter = "duckdb"\n'
3826 'conn_str = ["${HARLEQUIN_TEST_DB}"]\n'
3827 "no_init = true\n"
3828 )
3829 res = hsql("-tA", "-c", "select 42")
3830 assert res.exit_code == ExitCode.OK
3831 assert res.stdout == "42\n"
3832
3833
3834 def test_an_unset_variable_is_a_usage_error_that_names_it(
3835 hsql: Hsql, config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch
3836 ) -> None:
3837 """Exit 2 before the connection, rather than an empty string three layers in."""
3838 monkeypatch.delenv("HARLEQUIN_TEST_TOKEN", raising=False)
3839 cwd, _ = config_dirs
3840 (cwd / ".harlequin.toml").write_text(
3841 'default_profile = "prod"\n'
3842 "[profiles.prod]\n"
3843 'adapter = "duckdb"\n'
3844 'md_token = "${HARLEQUIN_TEST_TOKEN}"\n'
3845 )
3846 res = hsql("-c", "select 1")
3847 assert res.exit_code == ExitCode.USAGE
3848 assert res.stdout == ""
3849 assert "HARLEQUIN_TEST_TOKEN" in res.stderr
3850 assert str(cwd / ".harlequin.toml") in res.stderr
3851
3852
3853 def test_info_reports_an_unset_variable_rather_than_refusing(
3854 hsql: Hsql, config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch
3855 ) -> None:
3856 """A caller whose config is broken is one of the likeliest to run `--info`,
3857 so the variable it could not read is part of the answer."""
3858 monkeypatch.delenv("HARLEQUIN_TEST_TOKEN", raising=False)
3859 cwd, _ = config_dirs
3860 (cwd / ".harlequin.toml").write_text(
3861 'default_profile = "prod"\n'
3862 "[profiles.prod]\n"
3863 'adapter = "duckdb"\n'
3864 'md_token = "${HARLEQUIN_TEST_TOKEN}"\n'
3865 )
3866 res = hsql("--info")
3867 assert res.exit_code == ExitCode.OK
3868 profile = json.loads(res.stdout)["profile"]
3869 assert profile["options"] is None
3870 assert "HARLEQUIN_TEST_TOKEN" in profile["error"]
3871
3872
3873 def test_config_validate_reports_an_unset_variable(
3874 hsql: Hsql, config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch
3875 ) -> None:
3876 """The mode that reads every file reports this like any other problem."""
3877 monkeypatch.delenv("HARLEQUIN_TEST_TOKEN", raising=False)
3878 cwd, _ = config_dirs
3879 (cwd / ".harlequin.toml").write_text(
3880 '[profiles.prod]\nadapter = "duckdb"\nmd_token = "${HARLEQUIN_TEST_TOKEN}"\n'
3881 )
3882 res = hsql("--config", "validate", "-tA")
3883 assert res.exit_code == ExitCode.USAGE
3884 file, key, problem, _ = res.stdout.strip().split("|")
3885 assert file == str(cwd / ".harlequin.toml")
3886 assert key == "profiles.prod.md_token"
3887 assert "HARLEQUIN_TEST_TOKEN" in problem
3888
3889
3890 def test_config_show_prints_the_variable_rather_than_what_it_resolves_to(
3891 hsql: Hsql, config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch
3892 ) -> None:
3893 """The mode reports on config files, so it reports what they say.
3894
3895 Which is also the answer a reader wants: `${HARLEQUIN_TEST_TOKEN}` says
3896 where the value comes from, where the value itself would not -- and an
3897 unset variable is not a reason to refuse a report about the file naming it.
3898 """
3899 monkeypatch.delenv("HARLEQUIN_TEST_TOKEN", raising=False)
3900 cwd, _ = config_dirs
3901 (cwd / ".harlequin.toml").write_text(
3902 '[profiles.md]\nadapter = "duckdb"\nconn_str = ["${HARLEQUIN_TEST_TOKEN}"]\n'
3903 )
3904 res = hsql("--config", "show")
3905 assert res.exit_code == ExitCode.OK
3906 assert 'conn_str = ["${HARLEQUIN_TEST_TOKEN}"]' in res.stdout
3907
3908
3909 def test_info_masks_a_secret_read_from_the_environment(
3910 hsql: Hsql, config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch
3911 ) -> None:
3912 """Interpolation resolves a value; it does not make one printable.
3913
3914 Both mechanisms, over a value that was never written in the file: the
3915 option DuckDB declares secret, and the credential inside the DSN.
3916 """
3917 monkeypatch.setenv("HARLEQUIN_TEST_TOKEN", SECRET)
3918 cwd, _ = config_dirs
3919 (cwd / ".harlequin.toml").write_text(
3920 'default_profile = "md"\n'
3921 "[profiles.md]\n"
3922 'adapter = "duckdb"\n'
3923 'conn_str = ["md:my_db?motherduck_token=${HARLEQUIN_TEST_TOKEN}"]\n'
3924 'md_token = "${HARLEQUIN_TEST_TOKEN}"\n'
3925 )
3926 res = hsql("--info")
3927 assert res.exit_code == ExitCode.OK
3928 assert SECRET not in res.output
3929 options = json.loads(res.stdout)["profile"]["options"]
3930 assert options["md_token"] == "********"
3931 assert options["conn_str"] == ["md:my_db?motherduck_token=********"]
3932
3933
3934 def test_config_init_writes_the_variable_rather_than_what_it_resolves_to(
3935 hsql: Hsql, init_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch
3936 ) -> None:
3937 """Writing is the other side of reading, and it writes what it was given.
3938
3939 `--config init` is how a caller puts `${MD_TOKEN}` in a config file from a
3940 script, so what lands in the file has to be the six characters they typed.
3941 """
3942 monkeypatch.setenv("HARLEQUIN_TEST_TOKEN", SECRET)
3943 cwd, _ = init_dirs
3944 res = hsql(
3945 "--config",
3946 "init",
3947 "-P",
3948 "md",
3949 "-a",
3950 "duckdb",
3951 "--md_token",
3952 "${HARLEQUIN_TEST_TOKEN}",
3953 "md:my_db",
3954 )
3955 assert res.exit_code == ExitCode.OK
3956 assert SECRET not in (cwd / ".harlequin.toml").read_text()
3957 assert written(cwd / ".harlequin.toml")["profiles"]["md"]["md_token"] == (
3958 "${HARLEQUIN_TEST_TOKEN}"
3959 )
3960
3961
3962 def test_a_secret_read_from_the_environment_is_hidden_in_an_error(
3963 hsql: Hsql, config_dirs: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch
3964 ) -> None:
3965 """The backstop reaches a value that was never in a config file either."""
3966 monkeypatch.setenv("HARLEQUIN_TEST_TOKEN", SECRET)
3967 cwd, _ = config_dirs
3968 (cwd / ".harlequin.toml").write_text(
3969 'default_profile = "md"\n'
3970 "[profiles.md]\n"
3971 'adapter = "duckdb"\n'
3972 'md_token = "${HARLEQUIN_TEST_TOKEN}"\n'
3973 )
3974
3975 def exploding_connect(self: Any) -> Any:
3976 raise HarlequinConnectionError(f"token {self.md_token} rejected")
3977
3978 monkeypatch.setattr("harlequin_duckdb.DuckDbAdapter.connect", exploding_connect)
3979 res = hsql("-c", "select 1")
3980 assert res.exit_code == ExitCode.CONNECTION
3981 assert SECRET not in res.output
3982 assert "token ******** rejected" in res.stderr
3983
3984
3985 # --- `--timeout`, and the cancellation it has to attribute --------------------
3986
3987
3988 class _StuckCursor:
3989 """A cursor whose fetch blocks until the connection is cancelled.
3990
3991 What a cancelled DuckDB cursor does when it comes back: swallows the
3992 interrupt and returns no rows, which is also what a query that matched
3993 nothing returns. Nothing downstream can tell the two apart, which is why
3994 hsql attributes the timeout itself.
3995 """
3996
3997 def __init__(self, released: threading.Event) -> None:
3998 self.released = released
3999
4000 def columns(self) -> list[tuple[str, str]]:
4001 return [("n", "##")]
4002
4003 def set_limit(self, limit: int) -> "_StuckCursor":
4004 return self
4005
4006 def fetchall(self) -> None:
4007 self.released.wait(timeout=30)
4008 return None
4009
4010
4011 class _StuckConnection:
4012 """A connection whose every query blocks until it is cancelled."""
4013
4014 def __init__(self, *, stoppable: bool = True) -> None:
4015 self.stoppable = stoppable
4016 self.released = threading.Event()
4017 self.cancelled = False
4018
4019 def execute(self, query: str) -> _StuckCursor:
4020 return _StuckCursor(self.released)
4021
4022 def get_catalog(self) -> Any:
4023 self.released.wait(timeout=30)
4024 from harlequin.catalog import Catalog
4025
4026 return Catalog(items=[])
4027
4028 def cancel(self) -> None:
4029 self.cancelled = True
4030 if self.stoppable:
4031 self.released.set()
4032
4033
4034 @pytest.fixture
4035 def stuck_adapter(monkeypatch: pytest.MonkeyPatch) -> list[_StuckConnection]:
4036 """An installed adapter whose queries block until they are cancelled.
4037
4038 A fake rather than a slow query: the deadline, the cancel and the
4039 attribution are what these tests are about, and a real query slow enough to
4040 time out is one every machine has a different opinion about.
4041
4042 Yields the list the connections it opened land in, so a test can ask whether
4043 the cancel it promised actually happened.
4044 """
4045 from harlequin.adapter import HarlequinAdapter
4046
4047 opened: list[_StuckConnection] = []
4048
4049 class StuckAdapter(HarlequinAdapter):
4050 ADAPTER_OPTIONS = None
4051 IMPLEMENTS_CANCEL = True
4052
4053 def __init__(self, conn_str: Sequence[str], **options: Any) -> None:
4054 pass
4055
4056 def connect(self) -> Any:
4057 opened.append(_StuckConnection())
4058 return opened[-1]
4059
4060 entry_point = MagicMock()
4061 entry_point.name = "stuck"
4062 entry_point.load.return_value = StuckAdapter
4063 monkeypatch.setattr("harlequin.plugins.entry_points", lambda group: [entry_point])
4064 return opened
4065
4066
4067 def test_timeout_cancels_the_run_and_attributes_it(
4068 hsql: Hsql, stuck_adapter: list[_StuckConnection]
4069 ) -> None:
4070 """The whole flag, on the run it exists for.
4071
4072 Nothing on stdout is the half a naive deadline gets wrong: the result set a
4073 cancel produces is empty and error-free, and printing it would report "your
4074 query returned nothing" for a query that was killed.
4075 """
4076 res = hsql("-a", "stuck", "--timeout", "0.1", "-c", "select 1")
4077 assert res.exit_code == ExitCode.TIMEOUT
4078 assert res.stdout == ""
4079 assert "timed out after 0.1s" in res.stderr
4080 assert stuck_adapter[0].cancelled
4081
4082
4083 def test_timeout_stops_the_statements_after_the_one_it_cancelled(
4084 hsql: Hsql, stuck_adapter: list[_StuckConnection]
4085 ) -> None:
4086 """A script is stopped, not just the statement that ran too long."""
4087 res = hsql("-a", "stuck", "--timeout", "0.1", "-c", "select 1; select 2; select 3")
4088 assert res.exit_code == ExitCode.TIMEOUT
4089 assert res.stdout == ""
4090 # the one it was inside when the clock ran out, and none after it
4091 assert res.stderr.count("timed out") == 1
4092
4093
4094 def test_timeout_is_what_stats_reports(
4095 hsql: Hsql, stuck_adapter: list[_StuckConnection]
4096 ) -> None:
4097 """`--stats` is the machine channel, so it says what stderr said."""
4098 res = hsql("-a", "stuck", "--timeout", "0.1", "--stats", "-c", "select 1")
4099 assert res.exit_code == ExitCode.TIMEOUT
4100 stats = json.loads(res.stderr.strip().splitlines()[-1])
4101 assert stats["status"] == "error"
4102 assert stats["error"] == "timed out after 0.1s"
4103
4104
4105 def test_timeout_bounds_a_catalog_listing_too(
4106 hsql: Hsql, stuck_adapter: list[_StuckConnection]
4107 ) -> None:
4108 """`--catalog` connects and waits on the database like a run does, and a
4109 safety flag that silently did nothing there would be the worse half of the
4110 choice."""
4111 res = hsql("-a", "stuck", "--timeout", "0.1", "--catalog")
4112 assert res.exit_code == ExitCode.TIMEOUT
4113 assert "timed out after 0.1s" in res.stderr
4114 assert stuck_adapter[0].cancelled
4115
4116
4117 def test_a_run_inside_the_deadline_is_untouched(hsql: Hsql, duck: list[str]) -> None:
4118 """The clock is the only thing the flag adds: same bytes, same code."""
4119 res = hsql(*duck, "--timeout", "60", "-c", "select 1 as a")
4120 assert res.exit_code == ExitCode.OK
4121 assert res.stdout == " a\n---\n 1\n(1 row)\n"
4122 assert res.stderr == ""
4123
4124
4125 def test_timeout_refuses_an_adapter_that_cannot_cancel(
4126 hsql: Hsql, declares_nothing: str
4127 ) -> None:
4128 """There is no way to stop the work, so a deadline could only lie about
4129 having stopped it -- which is worse than not having the flag."""
4130 res = hsql("-a", declares_nothing, "--timeout", "30", "-c", "select 1")
4131 assert res.exit_code == ExitCode.USAGE
4132 assert res.stdout == ""
4133 assert declares_nothing in res.stderr
4134 assert "--timeout" in res.stderr and "--info" in res.stderr
4135
4136
4137 def test_timeout_from_a_profile_is_refused_the_same_way(
4138 hsql: Hsql, declares_nothing: str, tmp_path: Path
4139 ) -> None:
4140 path = tmp_path / ".harlequin.toml"
4141 path.write_text("[profiles.prod]\ntimeout = 30\n")
4142 res = hsql(
4143 "--config-path",
4144 str(path),
4145 "-P",
4146 "prod",
4147 "-a",
4148 declares_nothing,
4149 "-c",
4150 "select 1",
4151 )
4152 assert res.exit_code == ExitCode.USAGE
4153 assert res.stdout == ""
4154 assert declares_nothing in res.stderr
4155 assert "profile" in res.stderr
4156
4157
4158 def test_timeout_is_refused_ahead_of_the_mode_that_would_connect(
4159 hsql: Hsql, declares_nothing: str
4160 ) -> None:
4161 res = hsql("-a", declares_nothing, "--timeout", "30", "--catalog")
4162 assert res.exit_code == ExitCode.USAGE
4163 assert res.stdout == ""
4164 assert declares_nothing in res.stderr
4165
4166
4167 def test_timeout_is_refused_before_it_is_written_into_a_profile(
4168 hsql: Hsql, declares_nothing: str, init_dirs: tuple[Path, Path]
4169 ) -> None:
4170 """A profile pairing an adapter with a timeout it cannot honor is one no
4171 run would start under."""
4172 cwd, _ = init_dirs
4173 res = hsql(
4174 "--config", "init", "-P", "prod", "-a", declares_nothing, "--timeout", "5"
4175 )
4176 assert res.exit_code == ExitCode.USAGE
4177 assert declares_nothing in res.stderr
4178 assert not (cwd / ".harlequin.toml").exists()
4179
4180
4181 def test_config_validate_reports_a_timeout_the_adapter_cannot_do(
4182 hsql: Hsql, declares_nothing: str, config_dirs: tuple[Path, Path]
4183 ) -> None:
4184 cwd, _ = config_dirs
4185 (cwd / ".harlequin.toml").write_text(
4186 f"[profiles.prod]\nadapter = '{declares_nothing}'\ntimeout = 30\n"
4187 )
4188
4189 res = hsql("--config", "validate", "-a", declares_nothing, "-tA")
4190 assert res.exit_code == ExitCode.USAGE
4191 file, key, problem, _ = res.stdout.strip().split("|")
4192 assert file == str(cwd / ".harlequin.toml")
4193 assert key == "profiles.prod.timeout"
4194 assert declares_nothing in problem
4195
4196
4197 @pytest.mark.parametrize(
4198 "mode", [["--info"], ["--spec"], ["--config", "show"], ["--config", "validate"]]
4199 )
4200 def test_timeout_does_not_refuse_a_mode_that_reads_no_database(
4201 hsql: Hsql, declares_nothing: str, mode: list[str], config_dirs: tuple[Path, Path]
4202 ) -> None:
4203 """None of them waits on a database, and two of them are where a caller
4204 finds out which adapter they are on."""
4205 res = hsql(*mode, "-a", declares_nothing, "--timeout", "30")
4206 assert res.exit_code == ExitCode.OK, res.stderr
4207
4208
4209 @pytest.mark.parametrize("value", ["0", "-1", "abc"])
4210 def test_timeout_takes_a_positive_number_of_seconds(
4211 hsql: Hsql, duck: list[str], value: str
4212 ) -> None:
4213 res = hsql(*duck, "--timeout", value, "-c", "select 1")
4214 assert res.exit_code == ExitCode.USAGE
4215 assert res.stdout == ""
4216
4217
4218 @pytest.mark.parametrize("value", ["0", "true", "'soon'"])
4219 def test_a_profile_takes_a_positive_number_of_seconds_too(
4220 hsql: Hsql, tmp_path: Path, value: str
4221 ) -> None:
4222 """click vets what was typed; a config file can say anything."""
4223 path = tmp_path / ".harlequin.toml"
4224 path.write_text(f"[profiles.prod]\nadapter = 'duckdb'\ntimeout = {value}\n")
4225 res = hsql("--config-path", str(path), "-P", "prod", ":memory:", "-c", "select 1")
4226 assert res.exit_code == ExitCode.USAGE
4227 assert res.stdout == ""
4228 assert "--timeout" in res.stderr
4229
4230
4231 def test_every_bundled_adapter_declares_cancel(hsql: Hsql) -> None:
4232 """`--info` is where a caller learns which adapters can be timed out."""
4233 adapters = info_of(hsql("--info"))["adapters"]
4234 assert all(
4235 adapters[name]["capabilities"]["implements_cancel"]
4236 for name in ("duckdb", "sqlite")
4237 )
4238
4239
4240 def test_timeout_is_in_the_help(hsql: Hsql) -> None:
4241 res = hsql("--help")
4242 assert res.exit_code == ExitCode.OK
4243 assert "--timeout" in res.output
4244
4245
4246 UNSTOPPABLE = """
4247 import sys, threading
4248 from unittest.mock import MagicMock
4249
4250 import harlequin.plugins
4251 import harlequin.hsql.timeout as timeout
4252 from harlequin.adapter import HarlequinAdapter
4253
4254 timeout.GRACE_SECONDS = 0.5
4255
4256
4257 class Cursor:
4258 def columns(self): return [("n", "##")]
4259 def set_limit(self, limit): return self
4260 def fetchall(self): threading.Event().wait(60)
4261
4262
4263 class Connection:
4264 def execute(self, query): return Cursor()
4265 def get_catalog(self): raise NotImplementedError
4266 def cancel(self): pass
4267
4268
4269 class Unstoppable(HarlequinAdapter):
4270 ADAPTER_OPTIONS = None
4271 IMPLEMENTS_CANCEL = True
4272 def __init__(self, conn_str, **options): pass
4273 def connect(self): return Connection()
4274
4275
4276 entry_point = MagicMock()
4277 entry_point.name = "unstoppable"
4278 entry_point.load.return_value = Unstoppable
4279 harlequin.plugins.entry_points = lambda group: [entry_point]
4280
4281 sys.argv = ["hsql", "-a", "unstoppable", "--timeout", "0.2", "-c", "select 1"]
4282 from harlequin.hsql import main
4283 main()
4284 """
4285 """An adapter that declares it can cancel and then does not stop."""
4286
4287
4288 def test_a_run_that_outlasts_the_grace_period_still_exits_4(tmp_path: Path) -> None:
4289 """`sys.exit()` around a thread still inside a driver aborts the interpreter
4290 and exits 134, which is not a code hsql documents -- so the grace period
4291 ends in `os._exit()` instead. Only a real subprocess can show the code.
4292 """
4293 proc = subprocess.run(
4294 [sys.executable, "-c", UNSTOPPABLE],
4295 stdout=subprocess.PIPE,
4296 stderr=subprocess.PIPE,
4297 text=True,
4298 timeout=60,
4299 cwd=tmp_path, # out of the repo, whose own .harlequin.toml would apply
4300 )
4301 assert proc.returncode == ExitCode.TIMEOUT, proc.stderr
4302 assert proc.stdout == ""
4303 assert "timed out after 0.2s" in proc.stderr
4304
4305
4306 def test_timeout_is_hsqls_where_an_adapter_declares_the_spelling(hsql: Hsql) -> None:
4307 """SQLite's own `timeout` is how long to wait for a locked table, and hsql's
4308 own flags are the frozen part -- so `--timeout` here is the deadline, and
4309 the adapter's is `--lock-timeout`."""
4310 res = hsql(
4311 "-a",
4312 "sqlite",
4313 ":memory:",
4314 "--timeout",
4315 "60",
4316 "--lock-timeout",
4317 "1",
4318 "-tAc",
4319 "select 1",
4320 )
4321 assert res.exit_code == ExitCode.OK, res.stderr
4322 assert res.stdout == "1\n"
4323
4324
4325 def test_a_timed_out_script_does_not_report_a_missing_result_set(
4326 hsql: Hsql, stuck_adapter: list[_StuckConnection]
4327 ) -> None:
4328 """A cancelled script produced fewer result sets than it was going to, and
4329 the deadline is what a caller has to hear about rather than the count."""
4330 res = hsql(
4331 "-a", "stuck", "--timeout", "0.1", "--result", "2", "-c", "select 1; select 2"
4332 )
4333 assert res.exit_code == ExitCode.TIMEOUT
4334 assert "timed out after 0.1s" in res.stderr
4335 assert "result sets" not in res.stderr
4336
4337
4338 def test_a_real_duckdb_query_times_out_and_says_so(tmp_path: Path) -> None:
4339 """The fakes above pin the attribution; this pins the interrupt itself.
4340
4341 A subprocess because it is the only place the exit code is real: an
4342 aggregate over fifty billion rows is one every machine is still working on
4343 a second in.
4344 """
4345 proc = subprocess.run(
4346 [
4347 sys.executable,
4348 "-c",
4349 "import sys; from harlequin.hsql import main; sys.argv = sys.argv[1:]; "
4350 "main()",
4351 "hsql",
4352 *["-a", "duckdb", "--no-init", ":memory:"],
4353 *["--timeout", "1", "-c", "select sum(i) from range(50000000000) t(i)"],
4354 ],
4355 stdout=subprocess.PIPE,
4356 stderr=subprocess.PIPE,
4357 text=True,
4358 timeout=120,
4359 cwd=tmp_path, # out of the repo, whose own .harlequin.toml would apply
4360 )
4361 assert proc.returncode == ExitCode.TIMEOUT, proc.stderr
4362 # the empty result set a cancelled DuckDB cursor returns, not printed
4363 assert proc.stdout == ""
4364 assert "timed out after 1s" in proc.stderr