Debian Codegraph @

tests/test_catalog.py

raw
1 from typing import Callable
2
3 import pytest
4 from harlequin.catalog import CatalogSearchResult, InteractiveCatalogItem
5 from harlequin.exception import HarlequinQueryError
6
7 from harlequin_postgres.adapter import (
8 HarlequinPostgresAdapter,
9 HarlequinPostgresConnection,
10 )
11 from harlequin_postgres.catalog import (
12 ColumnCatalogItem,
13 DatabaseCatalogItem,
14 MaterializedViewCatalogItem,
15 RelationCatalogItem,
16 SchemaCatalogItem,
17 TableCatalogItem,
18 ViewCatalogItem,
19 )
20
21
22 @pytest.fixture
23 def connection_with_objects(
24 connection: HarlequinPostgresConnection,
25 ) -> HarlequinPostgresConnection:
26 connection.execute("create schema one")
27 connection.execute("create table one.foo as select 1 as a, '2' as b")
28 connection.execute("create table one.bar as select 1 as a, '2' as b")
29 connection.execute("create table one.baz as select 1 as a, '2' as b")
30 connection.execute("create schema two")
31 connection.execute("create view two.qux as select * from one.foo")
32 connection.execute("create schema three")
33 connection.execute("create schema four")
34 connection.execute("create materialized view four.foo as select * from one.foo")
35 # the original connection fixture will clean this up.
36 return connection
37
38
39 def test_catalog(connection_with_objects: HarlequinPostgresConnection) -> None:
40 conn = connection_with_objects
41
42 catalog = conn.get_catalog()
43
44 # at least two databases, postgres and test
45 assert len(catalog.items) >= 2
46
47 [test_db_item] = filter(lambda item: item.label == "test", catalog.items)
48 assert isinstance(test_db_item, InteractiveCatalogItem)
49 assert isinstance(test_db_item, DatabaseCatalogItem)
50 # the connected database is loaded eagerly, for its search path
51 assert test_db_item.children
52 assert test_db_item.loaded
53
54 schema_items = test_db_item.fetch_children()
55 assert all(isinstance(item, SchemaCatalogItem) for item in schema_items)
56
57 [schema_one_item] = filter(lambda item: item.label == "one", schema_items)
58 assert isinstance(schema_one_item, SchemaCatalogItem)
59 assert not schema_one_item.children
60 assert not schema_one_item.loaded
61
62 table_items = schema_one_item.fetch_children()
63 assert all(isinstance(item, RelationCatalogItem) for item in table_items)
64
65 [foo_item] = filter(lambda item: item.label == "foo", table_items)
66 assert isinstance(foo_item, TableCatalogItem)
67 assert not foo_item.children
68 assert not foo_item.loaded
69
70 foo_column_items = foo_item.fetch_children()
71 assert all(isinstance(item, ColumnCatalogItem) for item in foo_column_items)
72
73 [schema_two_item] = filter(lambda item: item.label == "two", schema_items)
74 assert isinstance(schema_two_item, SchemaCatalogItem)
75 assert not schema_two_item.children
76 assert not schema_two_item.loaded
77
78 view_items = schema_two_item.fetch_children()
79 assert all(isinstance(item, ViewCatalogItem) for item in view_items)
80
81 [qux_item] = filter(lambda item: item.label == "qux", view_items)
82 assert isinstance(qux_item, ViewCatalogItem)
83 assert not qux_item.children
84 assert not qux_item.loaded
85
86 qux_column_items = qux_item.fetch_children()
87 assert all(isinstance(item, ColumnCatalogItem) for item in qux_column_items)
88
89 assert [item.label for item in foo_column_items] == [
90 item.label for item in qux_column_items
91 ]
92
93 # ensure calling fetch_children on cols doesn't raise
94 children_items = foo_column_items[0].fetch_children()
95 assert not children_items
96
97 [schema_three_item] = filter(lambda item: item.label == "three", schema_items)
98 assert isinstance(schema_two_item, SchemaCatalogItem)
99 assert not schema_two_item.children
100 assert not schema_two_item.loaded
101
102 three_children = schema_three_item.fetch_children()
103 assert not three_children
104
105 [schema_four_item] = filter(lambda item: item.label == "four", schema_items)
106 assert isinstance(schema_four_item, SchemaCatalogItem)
107 assert not schema_four_item.children
108 assert not schema_four_item.loaded
109
110 mview_items = schema_four_item.fetch_children()
111 assert all(isinstance(item, MaterializedViewCatalogItem) for item in mview_items)
112
113 [foo_mv_item] = filter(lambda item: item.label == "foo", mview_items)
114 assert isinstance(foo_mv_item, MaterializedViewCatalogItem)
115 assert not foo_mv_item.children
116 assert not foo_mv_item.loaded
117
118 foo_mv_cols = foo_mv_item.fetch_children()
119 assert foo_mv_cols
120 assert all(isinstance(item, ColumnCatalogItem) for item in foo_mv_cols)
121
122
123 def test_catalog_items_carry_type_names(
124 connection_with_objects: HarlequinPostgresConnection,
125 ) -> None:
126 """Every item the catalog walk builds names its full type, not just a label."""
127 conn = connection_with_objects
128
129 [db_item] = [
130 i
131 for i in conn.get_catalog().items
132 if isinstance(i, DatabaseCatalogItem) and i.label == "test"
133 ]
134 schema_items = db_item.fetch_children()
135 [schema_one_item] = [i for i in schema_items if i.label == "one"]
136 [schema_two_item] = [i for i in schema_items if i.label == "two"]
137 [schema_four_item] = [i for i in schema_items if i.label == "four"]
138
139 [table_item] = [i for i in schema_one_item.fetch_children() if i.label == "foo"]
140 [view_item] = [i for i in schema_two_item.fetch_children() if i.label == "qux"]
141 [matview_item] = [i for i in schema_four_item.fetch_children() if i.label == "foo"]
142
143 assert table_item.type_name == "BASE TABLE"
144 assert view_item.type_name == "VIEW"
145 assert matview_item.type_name == "MATERIALIZED VIEW"
146
147 # a column's type_name is the full type its type_label is shortened from
148 assert [
149 (i.label, i.type_label, i.type_name) for i in table_item.fetch_children()
150 ] == [
151 ("a", "#", "integer"),
152 ("b", "s", "text"),
153 ]
154 assert [
155 (i.label, i.type_label, i.type_name) for i in matview_item.fetch_children()
156 ] == [
157 ("a", "#", "integer"),
158 ("b", "s", "text"),
159 ]
160
161
162 def _schema_items(
163 conn: HarlequinPostgresConnection,
164 ) -> dict[str, SchemaCatalogItem]:
165 """The schemas the catalog holds for the connected database, by label."""
166 [db_item] = [
167 item
168 for item in conn.get_catalog().items
169 if isinstance(item, DatabaseCatalogItem) and item.label == "test"
170 ]
171 assert db_item.loaded
172 return {
173 item.label: item
174 for item in db_item.children
175 if isinstance(item, SchemaCatalogItem)
176 }
177
178
179 def test_catalog_loads_the_default_search_path(
180 connection_with_objects: HarlequinPostgresConnection,
181 ) -> None:
182 """A relation in `public` is in the catalog without expanding anything."""
183 conn = connection_with_objects
184 conn.execute("create table public.quux as select 1 as a")
185
186 schema_items = _schema_items(conn)
187
188 public_item = schema_items["public"]
189 assert public_item.loaded
190 assert [item.label for item in public_item.children] == ["quux"]
191 # the rest of the catalog is still lazy
192 assert not schema_items["one"].loaded
193 assert not schema_items["one"].children
194 # and so are the columns under a schema that was loaded
195 [quux_item] = public_item.children
196 assert isinstance(quux_item, TableCatalogItem)
197 assert not quux_item.loaded
198 assert not quux_item.children
199
200
201 def test_catalog_loads_every_schema_on_the_search_path(
202 connection_with_objects: HarlequinPostgresConnection,
203 connect_again: Callable[..., HarlequinPostgresConnection],
204 ) -> None:
205 """A path of several schemas, spelled the many ways Postgres allows."""
206 connection_with_objects.execute(
207 'alter database test set search_path to "$user", one, "two", not_a_schema'
208 )
209
210 schema_items = _schema_items(connect_again())
211
212 assert schema_items["one"].loaded
213 assert sorted(item.label for item in schema_items["one"].children) == [
214 "bar",
215 "baz",
216 "foo",
217 ]
218 assert schema_items["two"].loaded
219 assert [item.label for item in schema_items["two"].children] == ["qux"]
220 # public is no longer on the path, and a schema that does not exist is
221 # not on it either -- `current_schemas()` drops both
222 assert not schema_items["public"].loaded
223 assert not schema_items["four"].loaded
224
225
226 def test_catalog_is_lazy_with_an_empty_search_path(
227 connection_with_objects: HarlequinPostgresConnection,
228 connect_again: Callable[..., HarlequinPostgresConnection],
229 ) -> None:
230 """Nothing resolves unqualified, so nothing is loaded up front."""
231 connection_with_objects.execute("alter database test set search_path to ''")
232
233 [db_item] = [
234 item
235 for item in connect_again().get_catalog().items
236 if isinstance(item, DatabaseCatalogItem) and item.label == "test"
237 ]
238
239 assert not db_item.loaded
240 assert not db_item.children
241
242
243 def test_catalog_loads_the_search_path_from_the_connection_string(
244 connection_with_objects: HarlequinPostgresConnection,
245 connect_again: Callable[..., HarlequinPostgresConnection],
246 ) -> None:
247 """The `options` a caller passes in the DSN set the path, like any other client."""
248 conn = connect_again("options=-csearch_path%3Dfour")
249
250 schema_items = _schema_items(conn)
251
252 assert schema_items["four"].loaded
253 assert [item.label for item in schema_items["four"].children] == ["foo"]
254 assert not schema_items["public"].loaded
255
256
257 @pytest.fixture
258 def connection_for_search(
259 connection_with_objects: HarlequinPostgresConnection,
260 ) -> HarlequinPostgresConnection:
261 conn = connection_with_objects
262 conn.execute("create table one.orders as select 1 as customer_id, 2 as amount")
263 # a schema, a relation, and a column that all match the same term, to check
264 # that a search reports a parent before the items under it
265 conn.execute("create schema five")
266 conn.execute("create table five.five_a as select 1 as five_col")
267 # names holding LIKE metacharacters, which a term must not be able to use
268 conn.execute('create table one."a_b" as select 1 as a')
269 conn.execute('create table one."axb" as select 1 as a')
270 conn.execute('create table one."pct%tbl" as select 1 as a')
271 # the original connection fixture will clean this up.
272 return conn
273
274
275 def _labeled(results: list[CatalogSearchResult], label: str) -> CatalogSearchResult:
276 [result] = [r for r in results if r.item.label == label]
277 return result
278
279
280 def test_implements_catalog_search() -> None:
281 assert HarlequinPostgresAdapter.IMPLEMENTS_CATALOG_SEARCH is True
282
283
284 def test_search_catalog_relations(
285 connection_for_search: HarlequinPostgresConnection,
286 ) -> None:
287 conn = connection_for_search
288
289 results = conn.search_catalog("foo", kind="relations")
290
291 assert [(r.item.label, r.parents) for r in results] == [
292 ("foo", ("test", "four")),
293 ("foo", ("test", "one")),
294 ]
295 matview_result, table_result = results
296 assert isinstance(matview_result.item, MaterializedViewCatalogItem)
297 assert isinstance(table_result.item, TableCatalogItem)
298 # a relation is built by the class fetch_children() would have used for it,
299 # so its query name is the one --catalog shows for the same object
300 assert table_result.item.query_name == '"one"."foo"'
301 assert (table_result.item.type_label, table_result.item.type_name) == (
302 "t",
303 "BASE TABLE",
304 )
305 assert (matview_result.item.type_label, matview_result.item.type_name) == (
306 "mv",
307 "MATERIALIZED VIEW",
308 )
309
310
311 def test_search_catalog_relations_finds_views(
312 connection_for_search: HarlequinPostgresConnection,
313 ) -> None:
314 results = connection_for_search.search_catalog("qux", kind="relations")
315
316 [result] = results
317 assert isinstance(result.item, ViewCatalogItem)
318 assert (result.item.type_label, result.item.type_name) == ("v", "VIEW")
319 assert result.parents == ("test", "two")
320
321
322 def test_search_catalog_columns(
323 connection_for_search: HarlequinPostgresConnection,
324 ) -> None:
325 results = connection_for_search.search_catalog("customer", kind="columns")
326
327 [result] = results
328 assert isinstance(result.item, ColumnCatalogItem)
329 assert result.item.label == "customer_id"
330 assert result.parents == ("test", "one", "orders")
331 assert result.item.query_name == '"customer_id"'
332 # type_name is the full type the label is shortened from
333 assert (result.item.type_label, result.item.type_name) == ("#", "integer")
334
335
336 def test_search_catalog_columns_finds_matview_columns(
337 connection_for_search: HarlequinPostgresConnection,
338 ) -> None:
339 # four.foo is a materialized view, which information_schema does not have
340 results = connection_for_search.search_catalog("b", kind="columns")
341
342 matview_results = [r for r in results if r.parents == ("test", "four", "foo")]
343 [result] = matview_results
344 assert isinstance(result.item, ColumnCatalogItem)
345 assert result.item.label == "b"
346 assert (result.item.type_label, result.item.type_name) == ("s", "text")
347
348
349 def test_search_catalog_kinds_are_scoped(
350 connection_for_search: HarlequinPostgresConnection,
351 ) -> None:
352 conn = connection_for_search
353
354 relations = conn.search_catalog("five", kind="relations")
355 assert [r.item.label for r in relations] == ["five_a"]
356
357 columns = conn.search_catalog("five", kind="columns")
358 assert [r.item.label for r in columns] == ["five_col"]
359
360
361 def test_search_catalog_all_returns_every_level(
362 connection_for_search: HarlequinPostgresConnection,
363 ) -> None:
364 results = connection_for_search.search_catalog("five", kind="all")
365
366 # a parent arrives before the items under it
367 assert [(r.item.label, r.parents) for r in results] == [
368 ("five", ("test",)),
369 ("five_a", ("test", "five")),
370 ("five_col", ("test", "five", "five_a")),
371 ]
372 schema_result, relation_result, column_result = results
373 assert isinstance(schema_result.item, SchemaCatalogItem)
374 assert isinstance(relation_result.item, TableCatalogItem)
375 assert isinstance(column_result.item, ColumnCatalogItem)
376
377
378 def test_search_catalog_matches_databases_by_name(
379 connection_for_search: HarlequinPostgresConnection,
380 ) -> None:
381 conn = connection_for_search
382
383 results = conn.search_catalog("postgres", kind="all")
384
385 # the pool is bound to one database, but the others can still be matched
386 # by name, which is all the catalog's top level shows for them
387 result = _labeled(results, "postgres")
388 assert isinstance(result.item, DatabaseCatalogItem)
389 assert result.parents == ()
390 assert result.item.query_name == '"postgres"'
391
392 # a database is not a relation, so the narrower kinds do not report it
393 assert not conn.search_catalog("postgres", kind="relations")
394
395
396 def test_search_catalog_is_case_insensitive(
397 connection_for_search: HarlequinPostgresConnection,
398 ) -> None:
399 conn = connection_for_search
400
401 assert [(r.item.label, r.parents) for r in conn.search_catalog("FOO")] == [
402 (r.item.label, r.parents) for r in conn.search_catalog("foo")
403 ]
404
405
406 def test_search_catalog_matches_a_substring(
407 connection_for_search: HarlequinPostgresConnection,
408 ) -> None:
409 results = connection_for_search.search_catalog("rder", kind="relations")
410
411 assert [r.item.label for r in results] == ["orders"]
412
413
414 @pytest.mark.parametrize(
415 "term,expected",
416 [
417 ("a_b", ["a_b"]),
418 ("%tbl", ["pct%tbl"]),
419 ("pct%", ["pct%tbl"]),
420 ],
421 )
422 def test_search_catalog_escapes_like_metacharacters(
423 connection_for_search: HarlequinPostgresConnection,
424 term: str,
425 expected: list[str],
426 ) -> None:
427 results = connection_for_search.search_catalog(term, kind="relations")
428
429 assert [r.item.label for r in results] == expected
430
431
432 def test_search_catalog_excludes_system_schemas(
433 connection_for_search: HarlequinPostgresConnection,
434 ) -> None:
435 conn = connection_for_search
436
437 # information_schema.columns and pg_catalog.pg_statistic exist, but the
438 # catalog tree does not show them, so a search must not report them either
439 assert not conn.search_catalog("information_schema", kind="all")
440 assert not conn.search_catalog("pg_statistic", kind="relations")
441
442
443 def test_search_catalog_without_a_match_is_empty(
444 connection_for_search: HarlequinPostgresConnection,
445 ) -> None:
446 assert connection_for_search.search_catalog("no-such-object") == []
447
448
449 def test_search_catalog_raises_query_error(
450 connection_for_search: HarlequinPostgresConnection,
451 monkeypatch: pytest.MonkeyPatch,
452 ) -> None:
453 from harlequin_postgres import adapter
454
455 monkeypatch.setitem(adapter._SEARCH_SQL, "all", "select not_a_column")
456
457 with pytest.raises(HarlequinQueryError):
458 connection_for_search.search_catalog("foo")
459
460 # the connection went back to the pool, so the next search still works
461 monkeypatch.undo()
462 assert connection_for_search.search_catalog("foo")
463
464
465 def test_search_catalog_items_match_fetch_children(
466 connection_for_search: HarlequinPostgresConnection,
467 ) -> None:
468 conn = connection_for_search
469
470 [db_item] = [
471 i
472 for i in conn.get_catalog().items
473 if isinstance(i, DatabaseCatalogItem) and i.label == "test"
474 ]
475 [schema_item] = [i for i in db_item.fetch_children() if i.label == "one"]
476 [walked_relation] = [i for i in schema_item.fetch_children() if i.label == "orders"]
477 [walked_column] = [
478 i for i in walked_relation.fetch_children() if i.label == "customer_id"
479 ]
480
481 [searched_relation] = conn.search_catalog("orders", kind="relations")
482 [searched_column] = conn.search_catalog("customer_id", kind="columns")
483
484 for walked, searched in (
485 (walked_relation, searched_relation.item),
486 (walked_column, searched_column.item),
487 ):
488 assert type(searched) is type(walked)
489 assert searched.label == walked.label
490 assert searched.query_name == walked.query_name
491 assert searched.qualified_identifier == walked.qualified_identifier
492 assert searched.type_label == walked.type_label
493 assert searched.type_name == walked.type_name