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