Debian Codegraph @

src/harlequin_postgres/adapter.py

raw
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 try:
387 with self.pool.connection() as conn, conn.cursor() as cur:
388 cur.execute(_SEARCH_SQL[kind], parameters)
389 found: list[
390 tuple[
391 str,
392 str | None,
393 str | None,
394 str | None,
395 str | None,
396 str | None,
397 ]
398 ] = cur.fetchall()
399 except Error as e:
400 raise HarlequinQueryError(
401 msg=str(e), title="Postgres raised an error searching the catalog:"
402 ) from e
403
404 databases: dict[str, DatabaseCatalogItem] = {}
405 schemas: dict[tuple[str, str], SchemaCatalogItem] = {}
406 relations: dict[tuple[str, str, str], RelationCatalogItem] = {}
407 results: list[CatalogSearchResult] = []
408 # a row names the deepest level it fills in, and carries its ancestors
409 # so that each one is built once and the match knows its own path
410 for catalog, schema, relation, relation_type, column, column_type in found:
411 database_item = databases.setdefault(
412 catalog, DatabaseCatalogItem.from_label(label=catalog, connection=self)
413 )
414 if schema is None:
415 results.append(CatalogSearchResult(item=database_item))
416 continue
417 schema_item = schemas.setdefault(
418 (catalog, schema),
419 SchemaCatalogItem.from_parent(parent=database_item, label=schema),
420 )
421 if relation is None:
422 results.append(
423 CatalogSearchResult(item=schema_item, parents=(catalog,))
424 )
425 continue
426 relation_item = relations.setdefault(
427 (catalog, schema, relation),
428 self._relation_item(schema_item, relation, relation_type),
429 )
430 if column is None:
431 results.append(
432 CatalogSearchResult(item=relation_item, parents=(catalog, schema))
433 )
434 continue
435 results.append(
436 CatalogSearchResult(
437 item=ColumnCatalogItem.from_parent(
438 parent=relation_item,
439 label=column,
440 type_label=self._short_column_type(column_type or ""),
441 type_name=column_type,
442 ),
443 parents=(catalog, schema, relation),
444 )
445 )
446 return results
447
448 @staticmethod
449 def _relation_item(
450 parent: SchemaCatalogItem, label: str, relation_type: str | None
451 ) -> RelationCatalogItem:
452 """A relation of the class `fetch_children()` would have built for it."""
453 if relation_type == "VIEW":
454 return ViewCatalogItem.from_parent(
455 parent=parent, label=label, type_name=relation_type
456 )
457 if relation_type == "LOCAL TEMPORARY":
458 return TempTableCatalogItem.from_parent(
459 parent=parent, label=label, type_name=relation_type
460 )
461 if relation_type == "FOREIGN":
462 return ForeignCatalogItem.from_parent(
463 parent=parent, label=label, type_name=relation_type
464 )
465 if relation_type == MATERIALIZED_VIEW:
466 return MaterializedViewCatalogItem.from_parent(
467 parent=parent, label=label, type_name=relation_type
468 )
469 return TableCatalogItem.from_parent(
470 parent=parent, label=label, type_name=relation_type
471 )
472
473 def get_completions(self) -> list[HarlequinCompletion]:
474 with self.pool.connection() as conn:
475 return _get_completions(conn)
476
477 def close(self) -> None:
478 self.pool.putconn(self._main_conn)
479 self.pool.close()
480
481 @property
482 def transaction_mode(self) -> HarlequinTransactionMode:
483 return self._transaction_mode
484
485 def toggle_transaction_mode(self) -> HarlequinTransactionMode:
486 self._transaction_mode = next(self._transaction_modes)
487 self._sync_transaction_mode()
488 return self._transaction_mode
489
490 def _sync_transaction_mode(self) -> None:
491 """
492 Sync this class's transaction mode with the main connection
493 """
494 conn = self._main_conn
495 if self.transaction_mode.label == "Auto":
496 conn.autocommit = True
497 conn.commit()
498 else:
499 conn.autocommit = False
500
501 def _get_databases(self) -> list[tuple[str]]:
502 with self.pool.connection() as conn, conn.cursor() as cur:
503 cur.execute(
504 """
505 select datname
506 from pg_database
507 where
508 datistemplate is false
509 and datallowconn is true
510 order by datname asc
511 ;"""
512 )
513 results: list[tuple[str]] = cur.fetchall()
514 return results
515
516 def _get_schemas(self, dbname: str) -> list[tuple[str]]:
517 with self.pool.connection() as conn, conn.cursor() as cur:
518 cur.execute(
519 """
520 select schema_name
521 from information_schema.schemata
522 where
523 catalog_name = %s
524 and schema_name != 'information_schema'
525 and schema_name not like 'pg\\_%%' escape '\\'
526 order by schema_name asc
527 ;""",
528 (dbname,),
529 )
530 results: list[tuple[str]] = cur.fetchall()
531 return results
532
533 def _get_relations(self, dbname: str, schema: str) -> list[tuple[str, str]]:
534 with self.pool.connection() as conn, conn.cursor() as cur:
535 cur.execute(
536 """
537 select table_name, table_type
538 from information_schema.tables
539 where
540 table_catalog = %s
541 and table_schema = %s
542 order by table_name asc
543 ;""",
544 (dbname, schema),
545 )
546 results: list[tuple[str, str]] = cur.fetchall()
547 return results
548
549 # only works for the currently-connected db
550 def _get_mvs(self, schema: str) -> list[tuple[str]]:
551 with self.pool.connection() as conn, conn.cursor() as cur:
552 cur.execute(
553 """
554 select matviewname
555 from pg_matviews
556 where
557 schemaname = %s
558 order by matviewname asc
559 ;""",
560 (schema,),
561 )
562 results: list[tuple[str]] = cur.fetchall()
563 return results
564
565 def _get_columns(
566 self, dbname: str, schema: str, relation: str
567 ) -> list[tuple[str, str]]:
568 with self.pool.connection() as conn, conn.cursor() as cur:
569 cur.execute(
570 """
571 select column_name, data_type
572 from information_schema.columns
573 where
574 table_catalog = %s
575 and table_schema = %s
576 and table_name = %s
577 order by ordinal_position asc
578 ;""",
579 (dbname, schema, relation),
580 )
581 results: list[tuple[str, str]] = cur.fetchall()
582 return results
583
584 def _get_mv_cols(self, schema: str, mv: str) -> list[tuple[str, str]]:
585 with self.pool.connection() as conn, conn.cursor() as cur:
586 cur.execute(
587 """
588 select
589 a.attname,
590 pg_catalog.format_type(a.atttypid, a.atttypmod)
591 from pg_attribute a
592 join pg_class t on a.attrelid = t.oid
593 join pg_namespace s on t.relnamespace = s.oid
594 where
595 a.attnum > 0
596 and not a.attisdropped
597 and s.nspname = %s
598 and t.relname = %s
599 order by a.attnum;
600 ;""",
601 (schema, mv),
602 )
603 results: list[tuple[str, str]] = cur.fetchall()
604 return results
605
606 @staticmethod
607 def _short_column_type(type_name: str) -> str:
608 MAPPING = {
609 "bigint": "##",
610 "bigserial": "##",
611 "bit": "010",
612 "boolean": "t/f",
613 "box": "□",
614 "bytea": "b",
615 "character": "s",
616 "cidr": "ip",
617 "circle": "○",
618 "date": "d",
619 "double": "#.#",
620 "inet": "ip",
621 "integer": "#",
622 "interval": "|-|",
623 "json": "{}",
624 "jsonb": "b{}",
625 "line": "—",
626 "lseg": "-",
627 "macaddr": "mac",
628 "macaddr8": "mac",
629 "money": "$$",
630 "numeric": "#.#",
631 "path": "╭",
632 "pg_lsn": "lsn",
633 "pg_snapshot": "snp",
634 "point": "•",
635 "polygon": "▽",
636 "real": "#.#",
637 "smallint": "#",
638 "smallserial": "#",
639 "serial": "#",
640 "text": "s",
641 "time": "t",
642 "timestamp": "ts",
643 "tsquery": "tsq",
644 "tsvector": "tsv",
645 "txid_snapshot": "snp",
646 "uuid": "uid",
647 "xml": "xml",
648 "array": "[]",
649 }
650 return MAPPING.get(type_name.split("(")[0].split(" ")[0], "?")
651
652 @staticmethod
653 def _short_column_type_from_oid(oid: int) -> str:
654 MAPPING = {
655 16: "t/f",
656 17: "b",
657 18: "s",
658 19: "s",
659 20: "##",
660 21: "#",
661 22: "[#]",
662 23: "#",
663 25: "s",
664 26: "oid",
665 114: "{}",
666 142: "xml",
667 600: "•",
668 601: "-",
669 602: "╭",
670 603: "□",
671 604: "▽",
672 628: "—",
673 651: "[ip]",
674 700: "#.#",
675 701: "#.#",
676 704: "|-|",
677 718: "○",
678 790: "$$",
679 829: "mac",
680 869: "ip",
681 650: "ip",
682 774: "mac",
683 1000: "[t/f]",
684 1001: "[b]",
685 1002: "[s]",
686 1003: "[s]",
687 1009: "[s]",
688 1013: "[oid]",
689 1014: "[s]",
690 1015: "[s]",
691 1016: "[#]",
692 1021: "[#.#]",
693 1022: "[#.#]",
694 1028: "[oid]",
695 1040: "[mac]",
696 1041: "[ip]",
697 1042: "s",
698 1043: "s",
699 1082: "d",
700 1083: "t",
701 1114: "ts",
702 1115: "[ts]",
703 1182: "[d]",
704 1183: "[t]",
705 1184: "ts",
706 1185: "[ts]",
707 1186: "|-|",
708 1187: "[|-|]",
709 1231: "[#.#]",
710 1266: "t",
711 1270: "[t]",
712 1560: "010",
713 1562: "010",
714 1700: "#.#",
715 2950: "uid",
716 3614: "tsv",
717 3615: "tsq",
718 3802: "b{}",
719 }
720 return MAPPING.get(oid, "?")
721
722
723 class HarlequinPostgresAdapter(HarlequinAdapter):
724 ADAPTER_OPTIONS = POSTGRES_OPTIONS
725 IMPLEMENTS_CANCEL = True
726 IMPLEMENTS_CATALOG_SEARCH = True
727 IMPLEMENTS_READ_ONLY = True
728
729 def __init__(
730 self,
731 conn_str: Sequence[str],
732 read_only: bool = False,
733 host: str | None = None,
734 port: str | None = None,
735 dbname: str | None = None,
736 user: str | None = None,
737 password: str | None = None,
738 passfile: str | None = None,
739 require_auth: str | None = None,
740 channel_binding: str | None = None,
741 connect_timeout: int | float | None = None,
742 sslmode: str | None = None,
743 sslcert: str | None = None,
744 sslkey: str | None = None,
745 **_: Any,
746 ) -> None:
747 self.conn_str = conn_str
748 self.read_only = bool(read_only)
749 self.options: dict[str, str | int | None] = {
750 "host": host,
751 "port": port,
752 "dbname": dbname,
753 "user": user,
754 "password": password,
755 "passfile": passfile,
756 "require_auth": require_auth,
757 "channel_binding": channel_binding,
758 "connect_timeout": connect_timeout, # type: ignore[dict-item]
759 "sslmode": sslmode,
760 "sslcert": sslcert,
761 "sslkey": sslkey,
762 }
763
764 @property
765 def connection_id(self) -> str | None:
766 """
767 Use a simplified connection string, with only the host, port, and database
768 """
769 try:
770 conn_info = conninfo.conninfo_to_dict(
771 conninfo=self.conn_str[0] if self.conn_str else "",
772 **self.options,
773 )
774 except Exception:
775 return None
776
777 host = conn_info.get("host", "localhost")
778 port = conn_info.get("port", "5432")
779 dbname = conn_info.get("dbname", "postgres")
780 return f"{host}:{port}/{dbname}"
781
782 def connect(self) -> HarlequinPostgresConnection:
783 if len(self.conn_str) > 1:
784 raise HarlequinConnectionError(
785 "Cannot provide multiple connection strings to the Postgres adapter. "
786 f"{self.conn_str}"
787 )
788 # before creating the connection, register updated type adapters, so
789 # all subsequent connections will use those adapters
790 register_inf_loaders()
791 conn = HarlequinPostgresConnection(
792 self.conn_str, options=self.options, read_only=self.read_only
793 )
794 return conn