Debian Codegraph @

src/harlequin_postgres/adapter.py

raw symbols SCIP
1 from __future__ import annotations
2
3 from itertools import cycle
4 from typing import Any, Sequence
5
6 from harlequin import (
7 HarlequinAdapter,
8 HarlequinCompletion,
9 HarlequinConnection,
10 HarlequinCursor,
11 HarlequinTransactionMode,
12 )
13 from harlequin.catalog import (
14 Catalog,
15 CatalogItem,
16 CatalogSearchKind,
17 CatalogSearchResult,
18 )
19 from harlequin.exception import HarlequinConnectionError, HarlequinQueryError
20 from psycopg import Connection, Cursor, conninfo
21 from psycopg.errors import Error, QueryCanceled
22 from psycopg.pq import TransactionStatus
23 from psycopg_pool import ConnectionPool
24 from textual_fastdatatable.backend import AutoBackendType
25
26 from harlequin_postgres.catalog import (
27 MATERIALIZED_VIEW,
28 ColumnCatalogItem,
29 DatabaseCatalogItem,
30 ForeignCatalogItem,
31 MaterializedViewCatalogItem,
32 RelationCatalogItem,
33 SchemaCatalogItem,
34 TableCatalogItem,
35 TempTableCatalogItem,
36 ViewCatalogItem,
37 )
38 from harlequin_postgres.cli_options import POSTGRES_OPTIONS
39 from harlequin_postgres.completions import _get_completions
40 from harlequin_postgres.loaders import register_inf_loaders
41
42 _LIKE_ESCAPE = "\\"
43 """What escapes a LIKE metacharacter in a term the caller typed."""
44
45
46 def _user_schemas(column: str) -> str:
47 """The schemas the catalog shows, as a predicate on `column`.
48
49 The same filter `_get_schemas()` applies, so a search only reports paths
50 that `--catalog` also walks. The `%` is doubled because these queries are
51 executed with parameters.
52 """
53 return (
54 f"{column} != 'information_schema' and {column} not like 'pg\\_%%' escape '\\'"
55 )
56
57
58 _SEARCH_DATABASES = """
59 select d.datname::text, null::text, null::text, null::text, null::text, null::text
60 from pg_database d
61 where
62 d.datistemplate is false
63 and d.datallowconn is true
64 and d.datname ilike %s escape '\\'
65 """
66 """The databases on the server, which is the catalog's top level.
67
68 The pool is bound to one database, so every level below this one is the
69 connected database's; the others can still be matched by name, which is all
70 `_get_databases()` reads for them.
71 """
72
73 _SEARCH_SCHEMAS = f"""
74 select
75 s.catalog_name::text, s.schema_name::text,
76 null::text, null::text, null::text, null::text
77 from information_schema.schemata s
78 where
79 s.catalog_name = current_database()
80 and {_user_schemas("s.schema_name")}
81 and s.schema_name ilike %s escape '\\'
82 """
83
84 _SEARCH_RELATIONS = f"""
85 select
86 t.table_catalog::text, t.table_schema::text, t.table_name::text,
87 t.table_type::text, null::text, null::text
88 from information_schema.tables t
89 where
90 t.table_catalog = current_database()
91 and {_user_schemas("t.table_schema")}
92 and t.table_name ilike %s escape '\\'
93 """
94
95 _SEARCH_MATERIALIZED_VIEWS = f"""
96 select
97 current_database()::text, m.schemaname::text, m.matviewname::text,
98 '{MATERIALIZED_VIEW}'::text, null::text, null::text
99 from pg_matviews m
100 where
101 {_user_schemas("m.schemaname")}
102 and m.matviewname ilike %s escape '\\'
103 """
104 """Matviews are not in information_schema, the same reason `_get_mvs()` exists."""
105
106 _SEARCH_COLUMNS = f"""
107 select
108 c.table_catalog::text, c.table_schema::text, c.table_name::text,
109 t.table_type::text, c.column_name::text, c.data_type::text
110 from information_schema.columns c
111 join information_schema.tables t
112 on t.table_catalog = c.table_catalog
113 and t.table_schema = c.table_schema
114 and t.table_name = c.table_name
115 where
116 c.table_catalog = current_database()
117 and {_user_schemas("c.table_schema")}
118 and c.column_name ilike %s escape '\\'
119 """
120
121 _SEARCH_MATERIALIZED_VIEW_COLUMNS = f"""
122 select
123 current_database()::text, s.nspname::text, t.relname::text,
124 '{MATERIALIZED_VIEW}'::text, a.attname::text,
125 pg_catalog.format_type(a.atttypid, a.atttypmod)::text
126 from pg_attribute a
127 join pg_class t on a.attrelid = t.oid
128 join pg_namespace s on t.relnamespace = s.oid
129 where
130 t.relkind = 'm'
131 and a.attnum > 0
132 and not a.attisdropped
133 and {_user_schemas("s.nspname")}
134 and a.attname ilike %s escape '\\'
135 """
136 """The matview equivalent of `_SEARCH_COLUMNS`, shaped like `_get_mv_cols()`."""
137
138 _SEARCH_BRANCHES: dict[CatalogSearchKind, tuple[str, ...]] = {
139 "relations": (_SEARCH_RELATIONS, _SEARCH_MATERIALIZED_VIEWS),
140 "columns": (_SEARCH_COLUMNS, _SEARCH_MATERIALIZED_VIEW_COLUMNS),
141 "all": (
142 _SEARCH_DATABASES,
143 _SEARCH_SCHEMAS,
144 _SEARCH_RELATIONS,
145 _SEARCH_MATERIALIZED_VIEWS,
146 _SEARCH_COLUMNS,
147 _SEARCH_MATERIALIZED_VIEW_COLUMNS,
148 ),
149 }
150 """Which levels each kind unions, every branch in the same six columns.
151
152 A row names one item by filling in the levels above it and leaving the rest
153 null, so `all` is every level of the catalog rather than the two at the bottom.
154 Each branch binds the pattern exactly once, in this order.
155 """
156
157 _SEARCH_SQL = {
158 kind: " union all ".join(branches)
159 # `nulls first` explicitly, because Postgres sorts nulls last ascending:
160 # without it a schema would arrive after the relations under it.
161 + " order by 1, 2 nulls first, 3 nulls first, 5 nulls first"
162 for kind, branches in _SEARCH_BRANCHES.items()
163 }
164 """One query per kind, ordered so that an item arrives before its children."""
165
166
167 def _contains_pattern(term: str) -> str:
168 """A term as the LIKE pattern that matches any label containing it."""
169 escaped = term
170 for character in (_LIKE_ESCAPE, "%", "_"):
171 escaped = escaped.replace(character, f"{_LIKE_ESCAPE}{character}")
172 return f"%{escaped}%"
173
174
175 class HarlequinPostgresCursor(HarlequinCursor):
176 def __init__(self, conn: HarlequinPostgresConnection, cur: Cursor) -> None:
177 self.conn = conn
178 self.cur = cur
179 # we need to copy the description from the cursor in case the results are
180 # fetched and the cursor is closed before columns() is called.
181 assert cur.description is not None
182 self.description = cur.description.copy()
183 self._limit: int | None = None
184
185 def columns(self) -> list[tuple[str, str]]:
186 return [
187 (col.name, self.conn._short_column_type_from_oid(col.type_code))
188 for col in self.description
189 ]
190
191 def set_limit(self, limit: int) -> HarlequinPostgresCursor:
192 self._limit = limit
193 return self
194
195 def fetchall(self) -> AutoBackendType:
196 try:
197 if self._limit is None:
198 return self.cur.fetchall()
199 else:
200 return self.cur.fetchmany(self._limit)
201 except QueryCanceled:
202 return []
203 except Exception as e:
204 raise HarlequinQueryError(
205 msg=f"{e.__class__.__name__}: {e}",
206 title="Harlequin encountered an error while executing your query.",
207 ) from e
208 finally:
209 self.cur.close()
210
211
212 class HarlequinPostgresConnection(HarlequinConnection):
213 def __init__(
214 self,
215 conn_str: Sequence[str],
216 *_: Any,
217 init_message: str = "",
218 options: dict[str, Any],
219 read_only: bool = False,
220 ) -> None:
221 self.init_message = init_message
222 self.read_only = bool(read_only)
223 try:
224 self.conn_info = conninfo.conninfo_to_dict(
225 conninfo=conn_str[0] if conn_str else "", **options
226 )
227 except Exception as e:
228 raise HarlequinConnectionError(
229 msg=str(e),
230 title=(
231 "Harlequin could not connect to Postgres. "
232 "Invalid connection string."
233 ),
234 ) from e
235 try:
236 raw_timeout = self.conn_info.get("connect_timeout")
237 timeout = float(raw_timeout) if raw_timeout is not None else 30.0
238 except (TypeError, ValueError) as e:
239 raise HarlequinConnectionError(
240 msg=str(e),
241 title=(
242 "Harlequin could not connect to Postgres. "
243 "Invalid value for connection_timeout."
244 ),
245 ) from e
246 try:
247 self.pool: ConnectionPool = ConnectionPool(
248 conninfo=conn_str[0] if conn_str and conn_str[0] else "",
249 min_size=2,
250 max_size=5,
251 kwargs=options,
252 open=True,
253 timeout=timeout,
254 configure=self._configure_connection,
255 )
256 self._main_conn: Connection = self.pool.getconn()
257 except Exception as e:
258 raise HarlequinConnectionError(
259 msg=str(e), title="Harlequin could not connect to Postgres."
260 ) from e
261
262 self._transaction_modes = cycle(
263 [
264 HarlequinTransactionMode(label="Auto"),
265 HarlequinTransactionMode(
266 label="Manual",
267 commit=self.commit,
268 rollback=self.rollback,
269 ),
270 ]
271 )
272 self.toggle_transaction_mode()
273
274 if self.read_only:
275 try:
276 self._assert_read_only()
277 except HarlequinConnectionError:
278 self.close()
279 raise
280
281 def _configure_connection(self, conn: Connection) -> None:
282 """
283 Called by the pool for every connection that it creates, so that read-only
284 mode is enforced by every connection, not just the main one. Must leave
285 the connection idle (outside of a transaction).
286 """
287 if not self.read_only:
288 return
289 # psycopg's conn.read_only only adds READ ONLY to the transactions that
290 # psycopg itself begins, so it does nothing in an autocommit session,
291 # where psycopg never issues a BEGIN. SET SESSION CHARACTERISTICS sets
292 # default_transaction_read_only for the whole session instead, which the
293 # server enforces in both of our transaction modes.
294 conn.execute("set session characteristics as transaction read only;")
295 conn.commit()
296 # additionally declare the transactions psycopg begins READ ONLY, so
297 # Manual mode is still read-only if the session setting is changed.
298 conn.read_only = True
299
300 def _assert_read_only(self) -> None:
301 """
302 Confirms the server is actually enforcing read-only transactions, so this
303 adapter never claims to implement a guarantee that it did not deliver.
304 """
305 try:
306 with self._main_conn.cursor() as cur:
307 cur.execute("select current_setting('default_transaction_read_only');")
308 result = cur.fetchone()
309 setting = result[0] if result else None
310 except Exception as e:
311 raise HarlequinConnectionError(
312 msg=str(e),
313 title="Harlequin could not open a read-only connection to Postgres.",
314 ) from e
315 if setting != "on":
316 raise HarlequinConnectionError(
317 msg=(
318 "Harlequin requested a read-only connection, but this server "
319 "reports default_transaction_read_only is "
320 f"{setting!r}. Refusing to connect, since writes would not "
321 "be prevented."
322 ),
323 title="Harlequin could not open a read-only connection to Postgres.",
324 )
325
326 def execute(self, query: str) -> HarlequinCursor | None:
327 if (
328 self.transaction_mode.label != "Auto"
329 and self._main_conn.info.transaction_status == TransactionStatus.IDLE
330 ):
331 cur = self._main_conn.cursor()
332 cur.execute(query="begin;")
333 cur.close()
334
335 try:
336 cur = self._main_conn.cursor()
337 cur.execute(query=query)
338 except QueryCanceled:
339 cur.close()
340 return None
341 except Exception as e:
342 msg_suffix = ""
343 try:
344 cur.close()
345 self.rollback()
346 except Exception:
347 # likely connection is closed; error messages
348 # can be cryptic, so help the user.
349 msg_suffix = (
350 "\n\nYou may need to restart Harlequin to reconnect to the "
351 "database."
352 )
353 raise HarlequinQueryError(
354 msg=f"{e}{msg_suffix}",
355 title="Harlequin encountered an error while executing your query.",
356 ) from e
357 else:
358 if cur.description is not None:
359 return HarlequinPostgresCursor(self, cur)
360 else:
361 cur.close()
362 return None
363
364 def cancel(self) -> None:
365 self._main_conn.cancel_safe()
366
367 def commit(self) -> None:
368 self._main_conn.commit()
369
370 def rollback(self) -> None:
371 self._main_conn.rollback()
372
373 def get_catalog(self) -> Catalog:
374 databases = self._get_databases()
375 db_items: list[CatalogItem] = [
376 DatabaseCatalogItem.from_label(label=db, connection=self)
377 for (db,) in databases
378 ]
379 return Catalog(items=db_items)
380
381 def search_catalog(
382 self, term: str, kind: CatalogSearchKind = "all"
383 ) -> list[CatalogSearchResult]:
384 pattern = _contains_pattern(term)
385 parameters = [pattern] * len(_SEARCH_BRANCHES[kind])
386 conn: Connection = self.pool.getconn()
387 try:
388 with conn.cursor() as cur:
389 cur.execute(_SEARCH_SQL[kind], parameters)
390 found: list[
391 tuple[
392 str,
393 str | None,
394 str | None,
395 str | None,
396 str | None,
397 str | None,
398 ]
399 ] = cur.fetchall()
400 except Error as e:
401 raise HarlequinQueryError(
402 msg=str(e), title="Postgres raised an error searching the catalog:"
403 ) from e
404 finally:
405 self.pool.putconn(conn)
406
407 databases: dict[str, DatabaseCatalogItem] = {}
408 schemas: dict[tuple[str, str], SchemaCatalogItem] = {}
409 relations: dict[tuple[str, str, str], RelationCatalogItem] = {}
410 results: list[CatalogSearchResult] = []
411 # a row names the deepest level it fills in, and carries its ancestors
412 # so that each one is built once and the match knows its own path
413 for catalog, schema, relation, relation_type, column, column_type in found:
414 database_item = databases.setdefault(
415 catalog, DatabaseCatalogItem.from_label(label=catalog, connection=self)
416 )
417 if schema is None:
418 results.append(CatalogSearchResult(item=database_item))
419 continue
420 schema_item = schemas.setdefault(
421 (catalog, schema),
422 SchemaCatalogItem.from_parent(parent=database_item, label=schema),
423 )
424 if relation is None:
425 results.append(
426 CatalogSearchResult(item=schema_item, parents=(catalog,))
427 )
428 continue
429 relation_item = relations.setdefault(
430 (catalog, schema, relation),
431 self._relation_item(schema_item, relation, relation_type),
432 )
433 if column is None:
434 results.append(
435 CatalogSearchResult(item=relation_item, parents=(catalog, schema))
436 )
437 continue
438 results.append(
439 CatalogSearchResult(
440 item=ColumnCatalogItem.from_parent(
441 parent=relation_item,
442 label=column,
443 type_label=self._short_column_type(column_type or ""),
444 type_name=column_type,
445 ),
446 parents=(catalog, schema, relation),
447 )
448 )
449 return results
450
451 @staticmethod
452 def _relation_item(
453 parent: SchemaCatalogItem, label: str, relation_type: str | None
454 ) -> RelationCatalogItem:
455 """A relation of the class `fetch_children()` would have built for it."""
456 if relation_type == "VIEW":
457 return ViewCatalogItem.from_parent(
458 parent=parent, label=label, type_name=relation_type
459 )
460 if relation_type == "LOCAL TEMPORARY":
461 return TempTableCatalogItem.from_parent(
462 parent=parent, label=label, type_name=relation_type
463 )
464 if relation_type == "FOREIGN":
465 return ForeignCatalogItem.from_parent(
466 parent=parent, label=label, type_name=relation_type
467 )
468 if relation_type == MATERIALIZED_VIEW:
469 return MaterializedViewCatalogItem.from_parent(
470 parent=parent, label=label, type_name=relation_type
471 )
472 return TableCatalogItem.from_parent(
473 parent=parent, label=label, type_name=relation_type
474 )
475
476 def get_completions(self) -> list[HarlequinCompletion]:
477 conn: Connection = self.pool.getconn()
478 completions = _get_completions(conn)
479 self.pool.putconn(conn)
480 return completions
481
482 def close(self) -> None:
483 self.pool.putconn(self._main_conn)
484 self.pool.close()
485
486 @property
487 def transaction_mode(self) -> HarlequinTransactionMode:
488 return self._transaction_mode
489
490 def toggle_transaction_mode(self) -> HarlequinTransactionMode:
491 self._transaction_mode = next(self._transaction_modes)
492 self._sync_transaction_mode()
493 return self._transaction_mode
494
495 def _sync_transaction_mode(self) -> None:
496 """
497 Sync this class's transaction mode with the main connection
498 """
499 conn = self._main_conn
500 if self.transaction_mode.label == "Auto":
501 conn.autocommit = True
502 conn.commit()
503 else:
504 conn.autocommit = False
505
506 def _get_databases(self) -> list[tuple[str]]:
507 conn: Connection = self.pool.getconn()
508 with conn.cursor() as cur:
509 cur.execute(
510 """
511 select datname
512 from pg_database
513 where
514 datistemplate is false
515 and datallowconn is true
516 order by datname asc
517 ;"""
518 )
519 results: list[tuple[str]] = cur.fetchall()
520 self.pool.putconn(conn)
521 return results
522
523 def _get_schemas(self, dbname: str) -> list[tuple[str]]:
524 conn: Connection = self.pool.getconn()
525 with conn.cursor() as cur:
526 cur.execute(
527 """
528 select schema_name
529 from information_schema.schemata
530 where
531 catalog_name = %s
532 and schema_name != 'information_schema'
533 and schema_name not like 'pg\\_%%' escape '\\'
534 order by schema_name asc
535 ;""",
536 (dbname,),
537 )
538 results: list[tuple[str]] = cur.fetchall()
539 self.pool.putconn(conn)
540 return results
541
542 def _get_relations(self, dbname: str, schema: str) -> list[tuple[str, str]]:
543 conn: Connection = self.pool.getconn()
544 with conn.cursor() as cur:
545 cur.execute(
546 """
547 select table_name, table_type
548 from information_schema.tables
549 where
550 table_catalog = %s
551 and table_schema = %s
552 order by table_name asc
553 ;""",
554 (dbname, schema),
555 )
556 results: list[tuple[str, str]] = cur.fetchall()
557 self.pool.putconn(conn)
558 return results
559
560 # only works for the currently-connected db
561 def _get_mvs(self, schema: str) -> list[tuple[str]]:
562 conn: Connection = self.pool.getconn()
563 with conn.cursor() as cur:
564 cur.execute(
565 """
566 select matviewname
567 from pg_matviews
568 where
569 schemaname = %s
570 order by matviewname asc
571 ;""",
572 (schema,),
573 )
574 results: list[tuple[str]] = cur.fetchall()
575 self.pool.putconn(conn)
576 return results
577
578 def _get_columns(
579 self, dbname: str, schema: str, relation: str
580 ) -> list[tuple[str, str]]:
581 conn: Connection = self.pool.getconn()
582 with conn.cursor() as cur:
583 cur.execute(
584 """
585 select column_name, data_type
586 from information_schema.columns
587 where
588 table_catalog = %s
589 and table_schema = %s
590 and table_name = %s
591 order by ordinal_position asc
592 ;""",
593 (dbname, schema, relation),
594 )
595 results: list[tuple[str, str]] = cur.fetchall()
596 self.pool.putconn(conn)
597 return results
598
599 def _get_mv_cols(self, schema: str, mv: str) -> list[tuple[str, str]]:
600 conn: Connection = self.pool.getconn()
601 with conn.cursor() as cur:
602 cur.execute(
603 """
604 select
605 a.attname,
606 pg_catalog.format_type(a.atttypid, a.atttypmod)
607 from pg_attribute a
608 join pg_class t on a.attrelid = t.oid
609 join pg_namespace s on t.relnamespace = s.oid
610 where
611 a.attnum > 0
612 and not a.attisdropped
613 and s.nspname = %s
614 and t.relname = %s
615 order by a.attnum;
616 ;""",
617 (schema, mv),
618 )
619 results: list[tuple[str, str]] = cur.fetchall()
620 self.pool.putconn(conn)
621 return results
622
623 @staticmethod
624 def _short_column_type(type_name: str) -> str:
625 MAPPING = {
626 "bigint": "##",
627 "bigserial": "##",
628 "bit": "010",
629 "boolean": "t/f",
630 "box": "□",
631 "bytea": "b",
632 "character": "s",
633 "cidr": "ip",
634 "circle": "○",
635 "date": "d",
636 "double": "#.#",
637 "inet": "ip",
638 "integer": "#",
639 "interval": "|-|",
640 "json": "{}",
641 "jsonb": "b{}",
642 "line": "—",
643 "lseg": "-",
644 "macaddr": "mac",
645 "macaddr8": "mac",
646 "money": "$$",
647 "numeric": "#.#",
648 "path": "╭",
649 "pg_lsn": "lsn",
650 "pg_snapshot": "snp",
651 "point": "•",
652 "polygon": "▽",
653 "real": "#.#",
654 "smallint": "#",
655 "smallserial": "#",
656 "serial": "#",
657 "text": "s",
658 "time": "t",
659 "timestamp": "ts",
660 "tsquery": "tsq",
661 "tsvector": "tsv",
662 "txid_snapshot": "snp",
663 "uuid": "uid",
664 "xml": "xml",
665 "array": "[]",
666 }
667 return MAPPING.get(type_name.split("(")[0].split(" ")[0], "?")
668
669 @staticmethod
670 def _short_column_type_from_oid(oid: int) -> str:
671 MAPPING = {
672 16: "t/f",
673 17: "b",
674 18: "s",
675 19: "s",
676 20: "##",
677 21: "#",
678 22: "[#]",
679 23: "#",
680 25: "s",
681 26: "oid",
682 114: "{}",
683 142: "xml",
684 600: "•",
685 601: "-",
686 602: "╭",
687 603: "□",
688 604: "▽",
689 628: "—",
690 651: "[ip]",
691 700: "#.#",
692 701: "#.#",
693 704: "|-|",
694 718: "○",
695 790: "$$",
696 829: "mac",
697 869: "ip",
698 650: "ip",
699 774: "mac",
700 1000: "[t/f]",
701 1001: "[b]",
702 1002: "[s]",
703 1003: "[s]",
704 1009: "[s]",
705 1013: "[oid]",
706 1014: "[s]",
707 1015: "[s]",
708 1016: "[#]",
709 1021: "[#.#]",
710 1022: "[#.#]",
711 1028: "[oid]",
712 1040: "[mac]",
713 1041: "[ip]",
714 1042: "s",
715 1043: "s",
716 1082: "d",
717 1083: "t",
718 1114: "ts",
719 1115: "[ts]",
720 1182: "[d]",
721 1183: "[t]",
722 1184: "ts",
723 1185: "[ts]",
724 1186: "|-|",
725 1187: "[|-|]",
726 1231: "[#.#]",
727 1266: "t",
728 1270: "[t]",
729 1560: "010",
730 1562: "010",
731 1700: "#.#",
732 2950: "uid",
733 3614: "tsv",
734 3615: "tsq",
735 3802: "b{}",
736 }
737 return MAPPING.get(oid, "?")
738
739
740 class HarlequinPostgresAdapter(HarlequinAdapter):
741 ADAPTER_OPTIONS = POSTGRES_OPTIONS
742 IMPLEMENTS_CANCEL = True
743 IMPLEMENTS_CATALOG_SEARCH = True
744 IMPLEMENTS_READ_ONLY = True
745
746 def __init__(
747 self,
748 conn_str: Sequence[str],
749 read_only: bool = False,
750 host: str | None = None,
751 port: str | None = None,
752 dbname: str | None = None,
753 user: str | None = None,
754 password: str | None = None,
755 passfile: str | None = None,
756 require_auth: str | None = None,
757 channel_binding: str | None = None,
758 connect_timeout: int | float | None = None,
759 sslmode: str | None = None,
760 sslcert: str | None = None,
761 sslkey: str | None = None,
762 **_: Any,
763 ) -> None:
764 self.conn_str = conn_str
765 self.read_only = bool(read_only)
766 self.options: dict[str, str | int | None] = {
767 "host": host,
768 "port": port,
769 "dbname": dbname,
770 "user": user,
771 "password": password,
772 "passfile": passfile,
773 "require_auth": require_auth,
774 "channel_binding": channel_binding,
775 "connect_timeout": connect_timeout, # type: ignore[dict-item]
776 "sslmode": sslmode,
777 "sslcert": sslcert,
778 "sslkey": sslkey,
779 }
780
781 @property
782 def connection_id(self) -> str | None:
783 """
784 Use a simplified connection string, with only the host, port, and database
785 """
786 try:
787 conn_info = conninfo.conninfo_to_dict(
788 conninfo=self.conn_str[0] if self.conn_str else "",
789 **self.options,
790 )
791 except Exception:
792 return None
793
794 host = conn_info.get("host", "localhost")
795 port = conn_info.get("port", "5432")
796 dbname = conn_info.get("dbname", "postgres")
797 return f"{host}:{port}/{dbname}"
798
799 def connect(self) -> HarlequinPostgresConnection:
800 if len(self.conn_str) > 1:
801 raise HarlequinConnectionError(
802 "Cannot provide multiple connection strings to the Postgres adapter. "
803 f"{self.conn_str}"
804 )
805 # before creating the connection, register updated type adapters, so
806 # all subsequent connections will use those adapters
807 register_inf_loaders()
808 conn = HarlequinPostgresConnection(
809 self.conn_str, options=self.options, read_only=self.read_only
810 )
811 return conn