Debian Codegraph @

tests/test_adapter.py

raw
1 from __future__ import annotations
2
3 import logging
4 import sys
5 from datetime import date, datetime
6
7 import psycopg
8 import pytest
9 from harlequin.adapter import HarlequinAdapter, HarlequinConnection, HarlequinCursor
10 from harlequin.catalog import Catalog, CatalogItem, InteractiveCatalogItem
11 from harlequin.exception import HarlequinConnectionError, HarlequinQueryError
12 from psycopg.pq import TransactionStatus
13 from textual_fastdatatable.backend import create_backend
14
15 from harlequin_postgres import adapter as adapter_module
16 from harlequin_postgres.adapter import (
17 HarlequinPostgresAdapter,
18 HarlequinPostgresConnection,
19 )
20
21 if sys.version_info < (3, 10):
22 from importlib_metadata import entry_points
23 else:
24 from importlib.metadata import entry_points
25
26 TEST_DB_CONN = "postgresql://postgres:for-testing@localhost:5432"
27
28
29 def test_plugin_discovery() -> None:
30 PLUGIN_NAME = "postgres"
31 eps = entry_points(group="harlequin.adapter")
32 assert eps[PLUGIN_NAME]
33 adapter_cls = eps[PLUGIN_NAME].load()
34 assert issubclass(adapter_cls, HarlequinAdapter)
35 assert adapter_cls == HarlequinPostgresAdapter
36
37
38 def test_connect() -> None:
39 conn = HarlequinPostgresAdapter(conn_str=(TEST_DB_CONN,)).connect()
40 assert isinstance(conn, HarlequinConnection)
41
42
43 def test_init_extra_kwargs() -> None:
44 assert HarlequinPostgresAdapter(
45 conn_str=(TEST_DB_CONN,), foo=1, bar="baz"
46 ).connect()
47
48
49 @pytest.mark.parametrize(
50 "conn_str",
51 [
52 ("foo",),
53 ("host=foo",),
54 ("postgresql://admin:pass@foo:5432/db",),
55 ],
56 )
57 def test_connect_raises_connection_error(conn_str: tuple[str]) -> None:
58 with pytest.raises(HarlequinConnectionError):
59 _ = HarlequinPostgresAdapter(conn_str=conn_str, connect_timeout=0.1).connect()
60
61
62 @pytest.mark.parametrize(
63 "conn_str,options,expected",
64 [
65 (("",), {}, "localhost:5432/postgres"),
66 (("host=foo",), {}, "foo:5432/postgres"),
67 (("postgresql://foo",), {}, "foo:5432/postgres"),
68 (("postgresql://foo",), {"port": 5431}, "foo:5431/postgres"),
69 (("postgresql://foo/mydb",), {"port": 5431}, "foo:5431/mydb"),
70 (("postgresql://admin:pass@foo/mydb",), {"port": 5431}, "foo:5431/mydb"),
71 (("postgresql://admin:pass@foo:5431/mydb",), {}, "foo:5431/mydb"),
72 ],
73 )
74 def test_connection_id(
75 conn_str: tuple[str], options: dict[str, int | float | str | None], expected: str
76 ) -> None:
77 adapter = HarlequinPostgresAdapter(
78 conn_str=conn_str,
79 **options, # type: ignore[arg-type]
80 )
81 assert adapter.connection_id == expected
82
83
84 def test_get_catalog(connection: HarlequinPostgresConnection) -> None:
85 catalog = connection.get_catalog()
86 assert isinstance(catalog, Catalog)
87 assert catalog.items
88 assert isinstance(catalog.items[0], CatalogItem)
89
90
91 def test_get_schemas_includes_user_schema_named_pgmq(
92 connection: HarlequinPostgresConnection,
93 ) -> None:
94 connection.execute("create schema pgmq")
95 schemas = connection._get_schemas("test")
96 assert ("pgmq",) in schemas
97
98
99 def test_get_completions(connection: HarlequinPostgresConnection) -> None:
100 completions = connection.get_completions()
101 test_labels = ["atomic", "greatest", "point_right", "autovacuum"]
102 filtered = list(filter(lambda x: x.label in test_labels, completions))
103 assert len(filtered) == 4
104 value_filtered = list(filter(lambda x: x.value in test_labels, completions))
105 assert len(value_filtered) == 4
106
107
108 def test_execute_ddl(connection: HarlequinPostgresConnection) -> None:
109 cur = connection.execute("create table foo (a int)")
110 assert cur is None
111
112
113 def test_execute_select(connection: HarlequinPostgresConnection) -> None:
114 cur = connection.execute("select 1 as a")
115 assert isinstance(cur, HarlequinCursor)
116 assert cur.columns() == [("a", "#")]
117 data = cur.fetchall()
118 backend = create_backend(data)
119 assert backend.column_count == 1
120 assert backend.row_count == 1
121
122
123 def test_execute_select_dupe_cols(connection: HarlequinPostgresConnection) -> None:
124 cur = connection.execute("select 1 as a, 2 as a, 3 as a")
125 assert isinstance(cur, HarlequinCursor)
126 assert len(cur.columns()) == 3
127 data = cur.fetchall()
128 backend = create_backend(data)
129 assert backend.column_count == 3
130 assert backend.row_count == 1
131
132
133 def test_set_limit(connection: HarlequinPostgresConnection) -> None:
134 cur = connection.execute("select 1 as a union all select 2 union all select 3")
135 assert isinstance(cur, HarlequinCursor)
136 cur = cur.set_limit(2)
137 assert isinstance(cur, HarlequinCursor)
138 data = cur.fetchall()
139 backend = create_backend(data)
140 assert backend.column_count == 1
141 assert backend.row_count == 2
142
143
144 def test_execute_raises_query_error(connection: HarlequinPostgresConnection) -> None:
145 with pytest.raises(HarlequinQueryError):
146 _ = connection.execute("sel;")
147
148
149 def test_inf_timestamps(connection: HarlequinPostgresConnection) -> None:
150 cur = connection.execute(
151 """select
152 'infinity'::date,
153 'infinity'::timestamp,
154 'infinity'::timestamptz,
155 '-infinity'::date,
156 '-infinity'::timestamp,
157 '-infinity'::timestamptz
158 """
159 )
160 assert cur is not None
161 data = cur.fetchall()
162 assert data == [
163 (
164 date.max,
165 datetime.max,
166 datetime.max,
167 date.min,
168 datetime.min,
169 datetime.min,
170 )
171 ]
172
173
174 def test_pooled_queries_return_idle_connections(
175 connection: HarlequinPostgresConnection,
176 caplog: pytest.LogCaptureFixture,
177 ) -> None:
178 """
179 Pooled connections are not autocommit, so a bare select leaves them INTRANS.
180 psycopg_pool logs a warning and rolls back for every connection returned that
181 way, so every helper that borrows one has to end its transaction first.
182 """
183 connection.execute("create schema one")
184 connection.execute("create table one.foo as select 1 as a")
185
186 with caplog.at_level(logging.WARNING, logger="psycopg.pool"):
187 catalog = connection.get_catalog()
188 [db_item] = [item for item in catalog.items if item.label == "test"]
189 assert isinstance(db_item, InteractiveCatalogItem)
190 [schema_item] = [
191 item for item in db_item.fetch_children() if item.label == "one"
192 ]
193 assert isinstance(schema_item, InteractiveCatalogItem)
194 [relation_item] = [
195 item for item in schema_item.fetch_children() if item.label == "foo"
196 ]
197 assert isinstance(relation_item, InteractiveCatalogItem)
198 relation_item.fetch_children()
199 connection.search_catalog("foo")
200 connection.get_completions()
201
202 assert [
203 record.getMessage()
204 for record in caplog.records
205 if record.name.startswith("psycopg")
206 ] == []
207
208 with connection.pool.connection() as conn:
209 assert conn.info.transaction_status == TransactionStatus.IDLE
210
211
212 def test_failed_pooled_query_does_not_leak_connections(
213 connection: HarlequinPostgresConnection,
214 monkeypatch: pytest.MonkeyPatch,
215 ) -> None:
216 """
217 A borrowed connection has to go back to the pool when the query raises, too;
218 otherwise a handful of failures would exhaust the pool.
219 """
220
221 def raise_error(conn: psycopg.Connection) -> None:
222 raise ValueError("boom")
223
224 monkeypatch.setattr(adapter_module, "_get_completions", raise_error)
225
226 for _ in range(connection.pool.max_size + 5):
227 with pytest.raises(ValueError):
228 connection.get_completions()
229
230 monkeypatch.undo()
231 # the pool still has connections to give out
232 assert connection.get_completions()
233
234
235 def test_closed_conn_raises_right_error(
236 connection: HarlequinPostgresConnection,
237 ) -> None:
238 connection._main_conn.close()
239
240 with pytest.raises(HarlequinQueryError):
241 connection.execute("select 1")
242
243
244 def test_implements_read_only() -> None:
245 assert HarlequinPostgresAdapter.IMPLEMENTS_READ_ONLY is True
246
247
248 def test_read_only_defaults_to_false() -> None:
249 adapter = HarlequinPostgresAdapter(conn_str=(TEST_DB_CONN,))
250 assert adapter.read_only is False
251 conn = adapter.connect()
252 assert conn.read_only is False
253 conn.close()
254
255
256 def test_read_only_is_not_a_conn_info_option() -> None:
257 """
258 read_only is not a libpq conninfo key, so it must never be passed to psycopg.
259 """
260 adapter = HarlequinPostgresAdapter(conn_str=(TEST_DB_CONN,), read_only=True)
261 assert adapter.read_only is True
262 assert "read_only" not in adapter.options
263 assert adapter.connection_id == "localhost:5432/postgres"
264
265 conn = adapter.connect()
266 # the conninfo passed to psycopg is unchanged; read-only is applied to each
267 # connection after it is opened.
268 assert "read_only" not in conn.conn_info
269 assert "options" not in conn.conn_info
270 conn.close()
271
272
273 def test_read_only_connection_can_read(
274 read_only_connection: HarlequinPostgresConnection,
275 ) -> None:
276 assert read_only_connection.read_only is True
277 cur = read_only_connection.execute("select * from foo")
278 assert isinstance(cur, HarlequinCursor)
279 assert cur.fetchall() == [(1,)]
280
281
282 @pytest.mark.parametrize(
283 "query",
284 [
285 "insert into foo values (2)",
286 "update foo set a = 2",
287 "delete from foo",
288 "create table bar (a int)",
289 "drop table foo",
290 ],
291 )
292 def test_read_only_connection_rejects_writes(
293 read_only_connection: HarlequinPostgresConnection, query: str
294 ) -> None:
295 with pytest.raises(HarlequinQueryError):
296 read_only_connection.execute(query)
297
298
299 def test_read_only_survives_transaction_mode_toggle(
300 read_only_connection: HarlequinPostgresConnection,
301 ) -> None:
302 assert read_only_connection.transaction_mode.label == "Auto"
303 for _ in range(4):
304 with pytest.raises(HarlequinQueryError):
305 read_only_connection.execute("insert into foo values (2)")
306 read_only_connection.toggle_transaction_mode()
307
308
309 def test_read_only_applies_to_pooled_connections(
310 read_only_connection: HarlequinPostgresConnection,
311 ) -> None:
312 # the catalog and completions run on connections from the pool, not on the
313 # main connection.
314 conn = read_only_connection.pool.getconn()
315 try:
316 with conn.cursor() as cur:
317 cur.execute("select current_setting('default_transaction_read_only')")
318 assert cur.fetchone() == ("on",)
319 with pytest.raises(psycopg.errors.ReadOnlySqlTransaction):
320 cur.execute("create table baz (a int)")
321 conn.rollback()
322 finally:
323 read_only_connection.pool.putconn(conn)
324
325
326 def test_read_only_connection_get_catalog(
327 read_only_connection: HarlequinPostgresConnection,
328 ) -> None:
329 catalog = read_only_connection.get_catalog()
330 assert isinstance(catalog, Catalog)
331 assert catalog.items
332
333
334 def test_read_only_refuses_to_connect_if_server_does_not_enforce(
335 monkeypatch: pytest.MonkeyPatch,
336 ) -> None:
337 """
338 If the read-only setting does not make it to the server, connecting must fail
339 loudly, rather than hand back a connection that would happily write.
340 """
341 monkeypatch.setattr(
342 HarlequinPostgresConnection,
343 "_configure_connection",
344 lambda self, conn: None,
345 )
346 with pytest.raises(HarlequinConnectionError):
347 HarlequinPostgresAdapter(conn_str=(TEST_DB_CONN,), read_only=True).connect()
348
349
350 def test_read_only_enforced_in_autocommit_session(
351 read_only_connection: HarlequinPostgresConnection,
352 ) -> None:
353 """
354 psycopg's Connection.read_only does not affect autocommit sessions, since
355 psycopg never issues a BEGIN for them; the session characteristic does.
356 """
357 assert read_only_connection.transaction_mode.label == "Auto"
358 assert read_only_connection._main_conn.autocommit is True
359 with pytest.raises(HarlequinQueryError):
360 read_only_connection.execute("insert into foo values (2)")