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