Debian Codegraph @

tests/unit_tests/test_query.py

raw
1 from __future__ import annotations
2
3 from typing import Any
4 from unittest import mock
5
6 import pyarrow as pa
7 import pytest
8
9 from harlequin.adapter import HarlequinAdapter, HarlequinConnection, HarlequinCursor
10 from harlequin.exception import HarlequinQueryError
11 from harlequin.query import (
12 ExecutedStatement,
13 ResultSet,
14 RowLimit,
15 execute,
16 fetch,
17 rows_to_result,
18 typed_rows_to_result,
19 )
20 from harlequin.statements import Statement, split
21
22
23 @pytest.fixture
24 def connection(duckdb_adapter: type[HarlequinAdapter]) -> HarlequinConnection:
25 return duckdb_adapter([":memory:"], no_init=True).connect()
26
27
28 def statements(script: str) -> list[Statement]:
29 return split(script)
30
31
32 class TestRowLimit:
33 def test_unlimited_asks_for_everything(self) -> None:
34 assert RowLimit().fetch_limit is None
35 assert RowLimit(max_rows=None, detect_overflow=True).fetch_limit is None
36
37 def test_plain_limit_asks_for_exactly_that_many(self) -> None:
38 assert RowLimit(max_rows=500).fetch_limit == 500
39
40 def test_overflow_detection_asks_for_one_more(self) -> None:
41 """Exactly n rows back from set_limit(n) is ambiguous; n+1 is not."""
42 assert RowLimit(max_rows=500, detect_overflow=True).fetch_limit == 501
43
44
45 class TestExecute:
46 def test_yields_one_result_per_statement(
47 self, connection: HarlequinConnection
48 ) -> None:
49 executed = list(execute(connection, statements("select 1; select 2; select 3")))
50 assert [e.statement.index for e in executed] == [0, 1, 2]
51 assert all(e.has_result_set for e in executed)
52 assert all(e.error is None for e in executed)
53
54 def test_ddl_yields_no_cursor(self, connection: HarlequinConnection) -> None:
55 executed = list(
56 execute(connection, statements("create table foo (a int); select 1"))
57 )
58 assert not executed[0].has_result_set
59 assert executed[0].error is None
60 assert executed[1].has_result_set
61
62 def test_is_lazy(self, connection: HarlequinConnection) -> None:
63 """A caller that stops consuming stops the script."""
64 script = statements("create table foo (a int); create table bar (a int)")
65 next(iter(execute(connection, script)))
66 cur = connection.execute("select count(*) from duckdb_tables()")
67 assert cur is not None
68 assert cur.fetchall().to_pylist() == [{"count_star()": 1}] # type: ignore[union-attr]
69
70 def test_stops_at_the_first_error_by_default(
71 self, connection: HarlequinConnection
72 ) -> None:
73 executed = list(execute(connection, statements("select 1; sel; select 3")))
74 assert len(executed) == 2
75 assert executed[0].error is None
76 assert isinstance(executed[1].error, HarlequinQueryError)
77 assert executed[1].statement.sql == "sel;"
78 assert not executed[1].has_result_set
79
80 def test_continues_past_an_error_when_asked(
81 self, connection: HarlequinConnection
82 ) -> None:
83 executed = list(
84 execute(
85 connection, statements("select 1; sel; select 3"), on_error="continue"
86 )
87 )
88 assert len(executed) == 3
89 assert [e.error is None for e in executed] == [True, False, True]
90
91 def test_applies_the_fetch_limit(self, connection: HarlequinConnection) -> None:
92 (executed,) = execute(
93 connection,
94 statements("select * from range(100)"),
95 limit=RowLimit(max_rows=5),
96 )
97 assert fetch(executed).row_count == 5
98
99 def test_overflow_detection_fetches_one_extra_row(
100 self, connection: HarlequinConnection
101 ) -> None:
102 (executed,) = execute(
103 connection,
104 statements("select * from range(100)"),
105 limit=RowLimit(max_rows=5, detect_overflow=True),
106 )
107 # the cursor holds 6; the result set keeps 5 and knows there were more.
108 assert fetch(executed).row_count == 6
109
110
111 class TestFetch:
112 def test_returns_columns_and_rows(self, connection: HarlequinConnection) -> None:
113 (executed,) = execute(connection, statements("select 1 as a, 'x' as b"))
114 result = fetch(executed)
115 assert [name for name, _ in result.columns] == ["a", "b"]
116 assert result.row_count == 1
117 assert result.backend.source_data.to_pylist() == [{"a": 1, "b": "x"}]
118 assert result.statement.sql == "select 1 as a, 'x' as b"
119 assert result.elapsed >= 0
120
121 def test_a_query_that_matches_nothing_returns_zero_rows(
122 self, connection: HarlequinConnection
123 ) -> None:
124 """Zero rows is not an error, and must not read like one."""
125 (executed,) = execute(connection, statements("select 1 where false"))
126 result = fetch(executed)
127 assert result.columns == [("1", "#")]
128 assert result.row_count == 0
129 assert result.backend.source_data.to_pylist() == []
130 assert result.truncated is False
131
132 def test_a_cursor_that_returns_none_still_gets_its_columns(self) -> None:
133 """The adapter interface lets a cursor return None instead of an empty
134 result. It still described its columns, and `create_backend()` is given
135 those, so the result is an empty table with a header rather than
136 nothing at all."""
137
138 class EmptyCursor(HarlequinCursor):
139 def __init__(self) -> None:
140 pass
141
142 def columns(self) -> list[tuple[str, str]]:
143 return [("a", "int")]
144
145 def set_limit(self, limit: int) -> HarlequinCursor:
146 return self
147
148 def fetchall(self) -> Any:
149 return None
150
151 result = fetch(
152 ExecutedStatement(statement=Statement("select 1", 0), cursor=EmptyCursor())
153 )
154 assert result.row_count == 0
155 assert result.truncated is False
156 assert result.arrow_table().column_names == ["a"]
157 assert result.arrow_table().num_rows == 0
158
159 def test_rejects_a_statement_with_no_cursor(
160 self, connection: HarlequinConnection
161 ) -> None:
162 (executed,) = execute(connection, statements("create table foo (a int)"))
163 with pytest.raises(ValueError):
164 fetch(executed)
165
166 def test_the_row_cap_is_not_the_fetch_limit(
167 self, connection: HarlequinConnection
168 ) -> None:
169 """The app fetches everything and caps what it displays, so the backend
170 knows the exact total -- which is what lets it say '5 of 100'."""
171 (executed,) = execute(connection, statements("select * from range(100)"))
172 result = fetch(executed, display_limit=5)
173 assert result.row_count == 5
174 assert result.fetched_row_count == 100
175 assert result.truncated is False
176
177 def test_the_display_cap_applies_over_the_fetch_limit(
178 self, connection: HarlequinConnection
179 ) -> None:
180 """Both at once: fifty fetched of an unknown number, five kept of the
181 fifty -- and the extra row that proved there were more is in neither."""
182 limit = RowLimit(max_rows=50, detect_overflow=True)
183 (executed,) = execute(
184 connection, statements("select * from range(100)"), limit=limit
185 )
186 result = fetch(executed, limit=limit, display_limit=5)
187 assert result.row_count == 5
188 assert result.fetched_row_count == 50
189 assert result.truncated is True
190
191
192 class TestTruncation:
193 @pytest.mark.parametrize(
194 ("rows", "expected_truncated", "expected_count"),
195 [(4, False, 4), (5, False, 5), (6, True, 5)],
196 ids=["under limit", "exactly at limit", "one over limit"],
197 )
198 def test_truncation_is_detected_from_one_extra_row(
199 self,
200 all_adapters: type[HarlequinAdapter],
201 rows: int,
202 expected_truncated: bool,
203 expected_count: int,
204 ) -> None:
205 """duckdb and sqlite implement set_limit differently enough to matter."""
206 connection = all_adapters([":memory:"], no_init=True).connect()
207 limit = RowLimit(max_rows=5, detect_overflow=True)
208 script = " union all ".join(f"select {i} as a" for i in range(rows))
209 (executed,) = execute(connection, statements(script), limit=limit)
210 result = fetch(executed, limit=limit)
211 assert result.row_count == expected_count
212 assert result.truncated is expected_truncated
213
214 def test_an_unlimited_fetch_is_never_truncated(
215 self, connection: HarlequinConnection
216 ) -> None:
217 limit = RowLimit(max_rows=None, detect_overflow=True)
218 (executed,) = execute(
219 connection, statements("select * from range(100)"), limit=limit
220 )
221 result = fetch(executed, limit=limit)
222 assert result.row_count == 100
223 assert result.truncated is False
224
225 def test_a_limit_of_zero_rows_still_detects_the_rest(
226 self, all_adapters: type[HarlequinAdapter]
227 ) -> None:
228 """`limit 0` asks what the columns are, and gets an answer that does
229 not pretend the table was empty."""
230 connection = all_adapters([":memory:"], no_init=True).connect()
231 limit = RowLimit(max_rows=0, detect_overflow=True)
232 (executed,) = execute(
233 connection, statements("select 1 as a union all select 2"), limit=limit
234 )
235 result = fetch(executed, limit=limit)
236 assert result.row_count == 0
237 assert result.fetched_row_count == 0
238 assert result.truncated is True
239 assert result.arrow_table().column_names == ["a"]
240
241 def test_a_soft_cap_is_not_truncation(
242 self, connection: HarlequinConnection
243 ) -> None:
244 """Nothing was left in the database, so nothing was cut short."""
245 (executed,) = execute(connection, statements("select * from range(100)"))
246 result = fetch(executed, display_limit=5)
247 assert result.truncated is False
248
249
250 class TestArrowTable:
251 def test_names_come_from_the_cursor(
252 self, all_adapters: type[HarlequinAdapter]
253 ) -> None:
254 """An adapter that returns rows as tuples normalizes to columns named
255 `f0`, `f1`, ... . The names the cursor described are the real ones."""
256 connection = all_adapters([":memory:"], no_init=True).connect()
257 (executed,) = execute(connection, statements("select 1 as a, 'x' as b"))
258 assert fetch(executed).arrow_table().column_names == ["a", "b"]
259
260 def test_duplicate_names_are_made_unique(
261 self, all_adapters: type[HarlequinAdapter]
262 ) -> None:
263 """Arrow allows duplicates and `to_pylist()` silently drops them, so
264 the backend resolves them. `export.write_file()` resolves them the same
265 way, so it does not matter which of the two saw the table first."""
266 connection = all_adapters([":memory:"], no_init=True).connect()
267 (executed,) = execute(connection, statements("select 1 as a, 2 as a"))
268 assert fetch(executed).arrow_table().column_names == ["a", "a0"]
269 # the names the cursor reported are still available, verbatim
270 assert [name for name, _ in fetch(executed).columns] == ["a", "a"]
271
272 def test_zero_rows_keeps_its_columns(
273 self, all_adapters: type[HarlequinAdapter]
274 ) -> None:
275 """Zero rows still has a header, whether the cursor returned an empty
276 result or nothing at all."""
277 connection = all_adapters([":memory:"], no_init=True).connect()
278 (executed,) = execute(
279 connection, statements("select 1 as a, 'x' as b where false")
280 )
281 table = fetch(executed).arrow_table()
282 assert table.column_names == ["a", "b"]
283 assert table.num_rows == 0
284
285 def test_it_holds_the_rows_kept_not_the_rows_fetched(
286 self, connection: HarlequinConnection
287 ) -> None:
288 """Under overflow detection one extra row was fetched to prove there
289 were more. It is not part of the result."""
290 limit = RowLimit(max_rows=5, detect_overflow=True)
291 (executed,) = execute(
292 connection, statements("select * from range(100)"), limit=limit
293 )
294 result = fetch(executed, limit=limit)
295 assert result.truncated is True
296 assert result.arrow_table().num_rows == 5
297
298
299 class TestTextColumns:
300 def test_every_value_is_a_string(self, connection: HarlequinConnection) -> None:
301 (executed,) = execute(
302 connection, statements("select 1 as a, 2.5::double as b, true as c")
303 )
304 text = fetch(executed).text_columns()
305 assert all(column.type == pa.string() for column in text.columns)
306 assert text.to_pylist() == [{"a": "1", "b": "2.5", "c": "true"}]
307
308 def test_duckdb_serializes_not_python(
309 self, connection: HarlequinConnection
310 ) -> None:
311 """`str()` on a blob is a Python repr (`b'\\x00\\xff'`) and on a bool is
312 `True`. Neither belongs in output an agent parses."""
313 (executed,) = execute(
314 connection,
315 statements("select '\\x00\\xFF'::blob as b, false as f"),
316 )
317 assert fetch(executed).text_columns().to_pylist() == [
318 {"b": "\\x00\\xFF", "f": "false"}
319 ]
320
321 def test_a_null_stays_a_null(self, connection: HarlequinConnection) -> None:
322 """So that it stays distinguishable from the literal string a caller
323 chose to render nulls as."""
324 (executed,) = execute(connection, statements("select null as a, 'NULL' as b"))
325 assert fetch(executed).text_columns().to_pylist() == [{"a": None, "b": "NULL"}]
326
327 def test_duplicate_names_survive_the_cast(
328 self, connection: HarlequinConnection
329 ) -> None:
330 (executed,) = execute(connection, statements("select 1 as a, 2 as a"))
331 text = fetch(executed).text_columns()
332 assert text.column_names == ["a", "a0"]
333 assert [column.to_pylist() for column in text.columns] == [["1"], ["2"]]
334
335 def test_zero_rows_is_not_an_error(self, connection: HarlequinConnection) -> None:
336 (executed,) = execute(connection, statements("select 1 as a where false"))
337 text = fetch(executed).text_columns()
338 assert text.column_names == ["a"]
339 assert text.num_rows == 0
340
341 def test_data_that_is_already_text_is_not_cast(
342 self, connection: HarlequinConnection, monkeypatch: pytest.MonkeyPatch
343 ) -> None:
344 """The cast is duckdb, and a string is already what it would return.
345
346 Asserted by making the cast fail rather than by timing it: this is what
347 keeps `hsql --config list-profiles` -- rows that never came from a
348 database -- from importing a database driver to render them.
349 """
350 cast: list[pa.Table] = []
351 monkeypatch.setattr("harlequin.query._cast_to_text", cast.append)
352 (executed,) = execute(connection, statements("select 'a' as a, 'b' as b"))
353 assert fetch(executed).text_columns().to_pylist() == [{"a": "a", "b": "b"}]
354 assert not cast
355
356 def test_a_type_duckdb_cannot_ingest_falls_back_loudly(self) -> None:
357 """Not an expected path -- duckdb ingests every Arrow type these
358 adapters have been seen to produce -- but a silent fallback would mean
359 output that quietly disagreed with an exported file."""
360
361 class UningestibleCursor(HarlequinCursor):
362 def __init__(self) -> None:
363 pass
364
365 def columns(self) -> list[tuple[str, str]]:
366 return [("a", "int")]
367
368 def set_limit(self, limit: int) -> HarlequinCursor:
369 return self
370
371 def fetchall(self) -> Any:
372 return pa.table({"a": [1, 2]})
373
374 result = fetch(
375 ExecutedStatement(
376 statement=Statement("select 1", 0), cursor=UningestibleCursor()
377 )
378 )
379 with mock.patch("duckdb.from_arrow", side_effect=RuntimeError("no such type")):
380 with pytest.warns(RuntimeWarning, match="falling back"):
381 text = result.text_columns()
382 assert text.to_pylist() == [{"a": "1"}, {"a": "2"}]
383
384
385 class TestExecuteWithoutAnAdapter:
386 """`execute()` is defined against the adapter interface, not against
387 duckdb, so a driver that misbehaves is worth exercising directly."""
388
389 def test_a_raw_driver_exception_does_not_escape(self) -> None:
390 class Exploding(HarlequinConnection):
391 def __init__(self) -> None:
392 pass
393
394 def execute(self, query: str) -> HarlequinCursor | None:
395 raise RuntimeError("the driver did not read the docs")
396
397 def get_catalog(self) -> Any:
398 raise NotImplementedError
399
400 (executed,) = execute(Exploding(), statements("select 1"))
401 assert isinstance(executed.error, RuntimeError)
402
403 def test_keyboard_interrupt_propagates(self) -> None:
404 """Ctrl-C is not a query error: it must not be reported as one, and it
405 must not be swallowed by on_error='continue'."""
406
407 class Interrupting(HarlequinConnection):
408 def __init__(self) -> None:
409 pass
410
411 def execute(self, query: str) -> HarlequinCursor | None:
412 raise KeyboardInterrupt
413
414 def get_catalog(self) -> Any:
415 raise NotImplementedError
416
417 with pytest.raises(KeyboardInterrupt):
418 list(execute(Interrupting(), statements("select 1"), on_error="continue"))
419
420
421 @pytest.mark.parametrize(
422 "returned",
423 [
424 {"a": [1, 2, 3]},
425 [(1,), (2,), (3,)],
426 pa.table({"a": [1, 2, 3]}),
427 pa.RecordBatch.from_arrays([pa.array([1, 2, 3])], names=["a"]),
428 ],
429 ids=["mapping", "records", "table", "record batch"],
430 )
431 def test_every_shape_a_cursor_may_return_is_normalized(returned: Any) -> None:
432 """`fetchall()` is typed `AutoBackendType`, which is `Any`. Routing each
433 shape through the one `create_backend()` the app already uses is what keeps
434 two front ends from disagreeing about what a row is."""
435
436 class FakeCursor(HarlequinCursor):
437 def __init__(self) -> None:
438 pass
439
440 def columns(self) -> list[tuple[str, str]]:
441 return [("a", "int")]
442
443 def set_limit(self, limit: int) -> HarlequinCursor:
444 return self
445
446 def fetchall(self) -> Any:
447 return returned
448
449 result = fetch(
450 ExecutedStatement(statement=Statement("select 1", 0), cursor=FakeCursor())
451 )
452 assert isinstance(result, ResultSet)
453 assert result.row_count == 3
454 assert [
455 next(iter(row.values())) for row in result.backend.source_data.to_pylist()
456 ] == [1, 2, 3]
457
458
459 class TestRowsToResult:
460 """Rows a mode produced, in the shape the writers already take."""
461
462 def test_they_render_as_any_other_result_set(self) -> None:
463 result = rows_to_result(
464 ["name", "adapter"], [("prod", "duckdb"), ("dev", None)]
465 )
466 assert result.columns == [("name", "s"), ("adapter", "s")]
467 assert result.row_count == 2
468 assert result.fetched_row_count == 2
469 # nothing held more of it, so nothing was cut short
470 assert result.truncated is False
471 assert result.text_columns().to_pylist() == [
472 {"name": "prod", "adapter": "duckdb"},
473 {"name": "dev", "adapter": None},
474 ]
475
476 def test_a_column_of_nulls_is_still_a_text_column(self) -> None:
477 """Inferred, it would be an Arrow null column, and rendering it would
478 cast the whole listing through duckdb to learn what it already is."""
479 result = rows_to_result(["name", "adapter"], [("prod", None)])
480 text = result.text_columns()
481 assert all(column.type == pa.string() for column in text.columns)
482 assert text.to_pylist() == [{"name": "prod", "adapter": None}]
483
484 def test_no_rows_is_still_a_header(self) -> None:
485 """The empty listing has to render as a listing with nothing in it."""
486 result = rows_to_result(["name", "adapter"], [])
487 assert [name for name, _ in result.columns] == ["name", "adapter"]
488 assert result.row_count == 0
489
490
491 class TestTypedRowsToResult:
492 """Rows a database returned to a query this module did not run."""
493
494 COLUMNS = (("sql", "s"), ("rows", "##"), ("elapsed_ms", "#.#"))
495
496 def test_the_values_keep_the_types_they_arrived_with(self) -> None:
497 """Which is the difference between a count an agent can sum and a
498 string it has to parse back."""
499 result = typed_rows_to_result(self.COLUMNS, [("select 1", 42, 12.5)])
500 assert result.columns == list(self.COLUMNS)
501 assert result.arrow_table().to_pylist() == [
502 {"sql": "select 1", "rows": 42, "elapsed_ms": 12.5}
503 ]
504 assert result.text_columns().to_pylist() == [
505 {"sql": "select 1", "rows": "42", "elapsed_ms": "12.5"}
506 ]
507
508 def test_no_rows_is_still_a_header(self) -> None:
509 result = typed_rows_to_result(self.COLUMNS, [])
510 assert [name for name, _ in result.columns] == ["sql", "rows", "elapsed_ms"]
511 assert result.row_count == 0
512 assert result.truncated is False
513
514 def test_a_caller_that_probed_for_one_more_row_can_say_so(self) -> None:
515 """The rows it keeps are the rows it was asked for; the probe proves
516 there was another, and the footer says `>`."""
517 result = typed_rows_to_result(
518 self.COLUMNS, [("select 1", 1, 1.0)], truncated=True
519 )
520 assert result.row_count == 1
521 assert result.fetched_row_count == 1
522 assert result.truncated is True