| 1 |
# -*- encoding: utf-8 -*- |
| 2 |
""" |
| 3 |
Basic support for communicating with the database server. |
| 4 |
|
| 5 |
This is currently very postgres specific. If we really wanted to |
| 6 |
support some other database, this would need massive refactoring. |
| 7 |
""" |
| 8 |
|
| 9 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 10 |
#c |
| 11 |
#c This program is free software, covered by the GNU GPL. See the |
| 12 |
#c COPYING file in the source distribution. |
| 13 |
|
| 14 |
|
| 15 |
import contextlib |
| 16 |
import functools |
| 17 |
import os |
| 18 |
import random |
| 19 |
import re |
| 20 |
import threading |
| 21 |
import warnings |
| 22 |
import weakref |
| 23 |
|
| 24 |
import numpy |
| 25 |
|
| 26 |
from gavo import utils |
| 27 |
from gavo.base import config |
| 28 |
from psycopg2.extensions import cursor |
| 29 |
|
| 30 |
_DEBUG = "GAVO_SQL_DEBUG" in os.environ |
| 31 |
|
| 32 |
import psycopg2 |
| 33 |
import psycopg2.extensions |
| 34 |
import psycopg2.pool |
| 35 |
|
| 36 |
from psycopg2.extras import DictCursor #noflake: exported name |
| 37 |
|
| 38 |
from gavo.utils.dachstypes import (cast, Any, Callable, Dict, |
| 39 |
Iterable, Iterator, List, Mapping, Optional, Sequence, Set, Tuple, Type, |
| 40 |
TYPE_CHECKING, Union) |
| 41 |
|
| 42 |
if TYPE_CHECKING: |
| 43 |
from gavo.rscdef import TableDef |
| 44 |
from gavo.rscdesc import RD |
| 45 |
from psycopg2.sql import Composable |
| 46 |
_PsycoQuery = Union[str, bytes, Composable] |
| 47 |
_PsycoArgs = Union[Sequence[Any], Mapping[str, Any], None] |
| 48 |
from contextlib import _GeneratorContextManager |
| 49 |
_ConnectionManager = Callable[[], _GeneratorContextManager[ |
| 50 |
"DaCHSConnection"]] |
| 51 |
|
| 52 |
class Error(utils.Error): |
| 53 |
pass |
| 54 |
|
| 55 |
|
| 56 |
NUMERIC_TYPES = frozenset(["smallint", "integer", "bigint", "real", |
| 57 |
"double precision"]) |
| 58 |
|
| 59 |
ORDERED_TYPES = frozenset(["timestamp", "text", "unicode"]) | NUMERIC_TYPES |
| 60 |
|
| 61 |
|
| 62 |
_PG_TIME_UNITS = { |
| 63 |
"ms": 0.0001, |
| 64 |
"s": 1., |
| 65 |
"": 1., |
| 66 |
"min": 60., |
| 67 |
"h": 3600., |
| 68 |
"d": 86400.,} |
| 69 |
|
| 70 |
|
| 71 |
class SqlSetAdapter: |
| 72 |
"""An adapter that formats python sequences as SQL sets. |
| 73 |
""" |
| 74 |
def __init__(self, seq: Sequence[str]) -> None: |
| 75 |
self._seq = seq |
| 76 |
|
| 77 |
def prepare(self, conn: "DaCHSConnection") -> None: |
| 78 |
pass |
| 79 |
|
| 80 |
def getquoted(self) -> bytes: |
| 81 |
qobjs = [] |
| 82 |
for o in self._seq: |
| 83 |
if isinstance(o, str): |
| 84 |
qobjs.append(psycopg2.extensions.adapt(o).getquoted()) |
| 85 |
else: |
| 86 |
qobjs.append(psycopg2.extensions.adapt(o).getquoted()) |
| 87 |
return b'(%s)'%(b", ".join(qobjs)) |
| 88 |
|
| 89 |
def __str__(self) -> str: |
| 90 |
return self.getquoted().decode("utf-8") |
| 91 |
|
| 92 |
|
| 93 |
class SqlArrayAdapter: |
| 94 |
"""An adapter that formats python lists as SQL arrays |
| 95 |
|
| 96 |
It makes, in the shameful tradition of VOTable, NULLs from empty arrays. |
| 97 |
""" |
| 98 |
def __init__(self, seq: List[Any]) -> None: |
| 99 |
self._seq = seq |
| 100 |
for item in seq: |
| 101 |
if item is not None: |
| 102 |
self.itemType: Optional[Type[Any]] = type(item) |
| 103 |
break |
| 104 |
else: |
| 105 |
self.itemType = None |
| 106 |
|
| 107 |
def prepare(self, conn: "DaCHSConnection") -> None: |
| 108 |
pass |
| 109 |
|
| 110 |
def _addCastIfNecessary(self, serializedList: List[bytes]) -> None: |
| 111 |
"""adds a typecast to serializedList if it needs one. |
| 112 |
|
| 113 |
This is when all entries in serializedList are NULL; so, we're fine |
| 114 |
anyway if the first element is non-NULL; if it's not, we try to |
| 115 |
guess. |
| 116 |
|
| 117 |
serializedList is changed in place, the method returns nothing. |
| 118 |
""" |
| 119 |
if not serializedList or serializedList[0]!=b"NULL": |
| 120 |
return |
| 121 |
|
| 122 |
if isinstance(self._seq, utils.floatlist): |
| 123 |
serializedList[0] = b"NULL::REAL" |
| 124 |
elif isinstance(self._seq, utils.intlist): |
| 125 |
serializedList[0] = b"NULL::INTEGER" |
| 126 |
|
| 127 |
def getquoted(self) -> bytes: |
| 128 |
if len(self._seq)==0: |
| 129 |
return b'NULL' |
| 130 |
|
| 131 |
if self.itemType and issubclass(self.itemType, str): |
| 132 |
# I need to be a bit verbose here because psycopg's default |
| 133 |
# encoding still is latin-1, and it seems there's no better |
| 134 |
# way to force it to utf-8 than this: |
| 135 |
qobjs = [] |
| 136 |
for o in self._seq: |
| 137 |
item = psycopg2.extensions.adapt(o) |
| 138 |
item.encoding = "utf-8" |
| 139 |
qobjs.append(item.getquoted()) |
| 140 |
else: |
| 141 |
qobjs = [psycopg2.extensions.adapt(o).getquoted() |
| 142 |
for o in self._seq] |
| 143 |
|
| 144 |
self._addCastIfNecessary(qobjs) |
| 145 |
|
| 146 |
return b'ARRAY[ %s ]'%(b", ".join(qobjs)) |
| 147 |
|
| 148 |
def __str__(self): |
| 149 |
return self.getquoted().encode("utf-8") |
| 150 |
|
| 151 |
|
| 152 |
class FloatableAdapter: |
| 153 |
"""An adapter for things that do "float", in particular numpy.float* |
| 154 |
""" |
| 155 |
def __init__(self, val: Any) -> None: |
| 156 |
self.val = float(val) |
| 157 |
|
| 158 |
def prepare(self, conn: "DaCHSConnection") -> None: |
| 159 |
pass |
| 160 |
|
| 161 |
def getquoted(self) -> bytes: |
| 162 |
if self.val!=self.val: |
| 163 |
return b"'nan'::real" |
| 164 |
else: |
| 165 |
return repr(self.val).encode("ascii") |
| 166 |
|
| 167 |
def __str__(self): |
| 168 |
return self.getquoted().encode("utf-8") |
| 169 |
|
| 170 |
|
| 171 |
class IntableAdapter: |
| 172 |
"""An adapter for things that do "int", in particular numpy.int* |
| 173 |
""" |
| 174 |
def __init__(self, val: Any) -> None: |
| 175 |
self.val = int(val) |
| 176 |
|
| 177 |
def prepare(self, conn: "DaCHSConnection") -> None: |
| 178 |
pass |
| 179 |
|
| 180 |
def getquoted(self) -> bytes: |
| 181 |
return str(self.val).encode("ascii") |
| 182 |
|
| 183 |
def __str__(self): |
| 184 |
return self.getquoted().decode("utf-8") |
| 185 |
|
| 186 |
|
| 187 |
class NULLAdapter(object): |
| 188 |
"""An adapter for things that should end up as NULL in the DB. |
| 189 |
""" |
| 190 |
def __init__(self, val: Any) -> None: |
| 191 |
# val doesn't matter, we're making it NULL anyway |
| 192 |
pass |
| 193 |
|
| 194 |
def prepare(self, conn: "DaCHSConnection") -> None: |
| 195 |
pass |
| 196 |
|
| 197 |
def getquoted(self) -> bytes: |
| 198 |
return b"NULL" |
| 199 |
|
| 200 |
def __str__(self): |
| 201 |
return self.getquoted().encode("utf-8") |
| 202 |
|
| 203 |
|
| 204 |
# register_adapter has a weird upstream prototype. I'll just shut |
| 205 |
# up mypy. |
| 206 |
psycopg2.extensions.register_adapter(list, SqlArrayAdapter) # type: ignore |
| 207 |
psycopg2.extensions.register_adapter(numpy.ndarray, SqlArrayAdapter) # type: ignore |
| 208 |
psycopg2.extensions.register_adapter(tuple, SqlSetAdapter) # type: ignore |
| 209 |
psycopg2.extensions.register_adapter(set, SqlSetAdapter) # type: ignore |
| 210 |
psycopg2.extensions.register_adapter(frozenset, SqlSetAdapter) # type: ignore |
| 211 |
|
| 212 |
for numpyType, adapter in [ |
| 213 |
("float32", FloatableAdapter), |
| 214 |
("float64", FloatableAdapter), |
| 215 |
("float96", FloatableAdapter), |
| 216 |
("int8", IntableAdapter), |
| 217 |
("int16", IntableAdapter), |
| 218 |
("int32", IntableAdapter), |
| 219 |
("int64", IntableAdapter),]: |
| 220 |
try: |
| 221 |
psycopg2.extensions.register_adapter( |
| 222 |
getattr(numpy, numpyType), adapter) # type: ignore |
| 223 |
except AttributeError: # pragma: no cover |
| 224 |
# types not present on the python end we don't need to adapt |
| 225 |
pass |
| 226 |
|
| 227 |
# Override psycopg2's mapping of numeric to decimal, because our |
| 228 |
# serialisers (votable, fits, json) don't really work with decimal. |
| 229 |
psycopg2.extensions.register_type( |
| 230 |
psycopg2.extensions.new_type( |
| 231 |
psycopg2.extensions.DECIMAL.values, |
| 232 |
"numeric_float", |
| 233 |
lambda value, cursor: float(value) if value is not None else None)) |
| 234 |
|
| 235 |
|
| 236 |
from gavo.utils import pyfits |
| 237 |
psycopg2.extensions.register_adapter(pyfits.Undefined, NULLAdapter) |
| 238 |
|
| 239 |
from psycopg2 import (OperationalError, #noflake: exported names |
| 240 |
DatabaseError, IntegrityError, ProgrammingError, |
| 241 |
InterfaceError, DataError, InternalError) |
| 242 |
from psycopg2.extensions import QueryCanceledError #noflake: exported name |
| 243 |
from psycopg2 import Error as DBError |
| 244 |
from psycopg2 import errors |
| 245 |
|
| 246 |
|
| 247 |
class DebugCursor(psycopg2.extensions.cursor): # pragma: no cover |
| 248 |
def execute(self, |
| 249 |
sql: "_PsycoQuery", |
| 250 |
args: "_PsycoArgs" = None) -> None: |
| 251 |
print("Executing %s %s"%(id(self.connection), cast(str, sql))) |
| 252 |
psycopg2.extensions.cursor.execute(self, sql, args) |
| 253 |
print("Finished %s %s"%(id(self.connection), |
| 254 |
(self.query or b"").decode("utf-8"))) |
| 255 |
|
| 256 |
def executemany(self, sql: "_PsycoQuery", args: Iterable["_PsycoArgs"] = [] |
| 257 |
) -> None: |
| 258 |
print("Executing many", sql) |
| 259 |
args = cast(List, args) |
| 260 |
print(("%d args, first one:\n%s"%(len(args), args[0]))) |
| 261 |
psycopg2.extensions.cursor.executemany(self, sql, args) |
| 262 |
print("Finished many", (self.query or b"").decode("utf-8")) |
| 263 |
|
| 264 |
|
| 265 |
class DaCHSConnection(psycopg2.extensions.connection): |
| 266 |
"""A psycopg2 connection with some additional methods. |
| 267 |
|
| 268 |
This derivation is also done so we can attach the getDBConnection |
| 269 |
arguments to the connection; it is used when recovering from |
| 270 |
a database restart. |
| 271 |
""" |
| 272 |
# extensionFunctions is filled senseEnvironment (and contains names of |
| 273 |
# postgres extension functions that might modify our behaviour) |
| 274 |
extensionFunctions = None |
| 275 |
|
| 276 |
@classmethod |
| 277 |
def senseEnvironment(cls, conn: "DaCHSConnection"): |
| 278 |
"""configures us depending on what is in the database. |
| 279 |
|
| 280 |
The argument needs to be a connection to the database we will |
| 281 |
connect to. In practice, _initPsycopg calls this once during |
| 282 |
DaCHS startup. |
| 283 |
""" |
| 284 |
cls.extensionFunctions = frozenset(r[0] for r in |
| 285 |
conn.query( |
| 286 |
"SELECT proname FROM pg_proc WHERE" |
| 287 |
" proname in ('epoch_prop', 'q3c_ang2ipix'," |
| 288 |
" 'smoc_union', 'healpix_nest')")) |
| 289 |
|
| 290 |
|
| 291 |
def getParameter(self, key: str, csr: Optional[cursor] = None) -> str: |
| 292 |
"""returns the value of the postgres parameter key. |
| 293 |
|
| 294 |
This returns unprocessed values, probably almost always as strings. |
| 295 |
Caveat emptor. |
| 296 |
|
| 297 |
The main purpose of this function is to help the parameters context |
| 298 |
manager, so users shouldn't really mess with it. |
| 299 |
""" |
| 300 |
if not re.match("[A-Za-z_]+", key): |
| 301 |
raise ValueError("Invalid settings key: %s"%key) |
| 302 |
|
| 303 |
csr = cast(cursor, csr or self.cursor()) |
| 304 |
csr.execute(f"SHOW {key}") |
| 305 |
return list(csr)[0][0] |
| 306 |
|
| 307 |
def configure(self, |
| 308 |
settings: Sequence[Tuple[str, Union[str, int]]], |
| 309 |
cursor: Optional[cursor] = None) -> List[Tuple[str, str]]: |
| 310 |
"""sets a number of postgres connection parameters. |
| 311 |
|
| 312 |
settings is a list of (parameter, value) pairs, where value |
| 313 |
must be a python value that psycopg2 understands and that works |
| 314 |
for the parameter in question. |
| 315 |
|
| 316 |
This returns a settings-list that restores the previous values |
| 317 |
when passed to configure() |
| 318 |
""" |
| 319 |
cursor = cursor or self.cursor() |
| 320 |
resetTo = [] |
| 321 |
for key, _ in settings: |
| 322 |
resetTo.append((key, self.getParameter(key, cursor))) |
| 323 |
|
| 324 |
for key, val in settings: |
| 325 |
cursor.execute("SET %s=%%(val)s"%key, {"val": val}) |
| 326 |
|
| 327 |
return resetTo |
| 328 |
|
| 329 |
@contextlib.contextmanager |
| 330 |
def parameters(self, |
| 331 |
settings: Sequence[Tuple[str, str]], |
| 332 |
cursor: Optional[cursor] = None) -> Iterator: |
| 333 |
"""executes a block with a certain set of parameters on a connection, |
| 334 |
resetting them to their original value again afterwards. |
| 335 |
|
| 336 |
Of course, this only works as expected if you're not sharing your |
| 337 |
connections to widely. |
| 338 |
|
| 339 |
When the database returns an error in the controlled block, we do |
| 340 |
not attempt to restore the parameters; we'd have to roll back |
| 341 |
the transaction for that, and that could have unwelcome side effects |
| 342 |
(that has changed in DaCHS 2.13; that would have reset the params; |
| 343 |
I now think that was silly behaviour because the transaction |
| 344 |
is hosed at that point anyway, and the parameter settings would |
| 345 |
probably be gone anyway). |
| 346 |
""" |
| 347 |
# shortcut if there are to settings to do |
| 348 |
if not settings: |
| 349 |
yield |
| 350 |
return |
| 351 |
|
| 352 |
cursor = cursor or self.cursor() |
| 353 |
resetTo = self.configure(settings, cursor) |
| 354 |
|
| 355 |
try: |
| 356 |
yield |
| 357 |
except Exception as ex: |
| 358 |
# if it looks like the database itself failed, the transaction |
| 359 |
# is hosed, and there's no point bringing it back to the previous |
| 360 |
# state. |
| 361 |
if not isinstance(ex, psycopg2.Error): |
| 362 |
self.configure(resetTo) |
| 363 |
raise |
| 364 |
|
| 365 |
self.configure(resetTo, cursor) |
| 366 |
|
| 367 |
def queryToDicts(self, |
| 368 |
query: str, |
| 369 |
args: Dict[str, Any] = {}, |
| 370 |
timeout: Optional[float] = None, |
| 371 |
caseFixer: Optional[Dict[str, str]] = None) -> Iterator: |
| 372 |
"""iterates over dictionary rows for query. |
| 373 |
|
| 374 |
This is a thin wrapper around query(yieldDicts=True) provided |
| 375 |
for convenience and backwards compatibility. |
| 376 |
""" |
| 377 |
return self.query(query, args, timeout, True, caseFixer) |
| 378 |
|
| 379 |
def query(self, |
| 380 |
query: "_PsycoQuery", |
| 381 |
args: "_PsycoArgs" = {}, |
| 382 |
timeout: Optional[float] = None, |
| 383 |
yieldDicts: bool = False, |
| 384 |
caseFixer: Optional[Dict[str, str]] = None) -> Iterator: |
| 385 |
"""iterates over result tuples for query. |
| 386 |
|
| 387 |
This is mainly for ad-hoc queries needing little metadata. |
| 388 |
|
| 389 |
You can pass yieldDicts=True to get dictionaries instead of tuples. |
| 390 |
The dictionary keys are determined by what the database says the |
| 391 |
column titles are; thus, it's usually lower-cased variants of what's |
| 392 |
in the select-list. To fix this, you can pass in a caseFixer dict |
| 393 |
that gives a properly cased version of lowercase names. |
| 394 |
|
| 395 |
Timeout is in seconds. |
| 396 |
|
| 397 |
Warning: this is an iterator, so unless you iterate over the result, |
| 398 |
the query will not get executed. Hence, for non-select statements |
| 399 |
you will generally have to use conn.execute. |
| 400 |
""" |
| 401 |
cursor = self.cursor() |
| 402 |
params = [] |
| 403 |
if timeout is not None: |
| 404 |
params.append(("statement_timeout", "%s ms"%int(timeout*1000))) |
| 405 |
|
| 406 |
try: |
| 407 |
with self.parameters(params, cursor): |
| 408 |
cursor.execute(query, args) |
| 409 |
|
| 410 |
if yieldDicts: |
| 411 |
keys = [cd[0] for cd in cursor.description or ()] |
| 412 |
if caseFixer: |
| 413 |
keys = [caseFixer.get(key, key) for key in keys] |
| 414 |
for row in cursor: |
| 415 |
yield dict(list(zip(keys, row))) |
| 416 |
|
| 417 |
else: |
| 418 |
for row in cursor: |
| 419 |
yield row |
| 420 |
finally: |
| 421 |
cursor.close() |
| 422 |
|
| 423 |
def execute(self, query: "_PsycoQuery", args: "_PsycoArgs" = {}) -> int: |
| 424 |
"""executes query in a cursor. |
| 425 |
|
| 426 |
This returns the rowcount of the cursor used. |
| 427 |
""" |
| 428 |
cursor = self.cursor() |
| 429 |
try: |
| 430 |
cursor.execute(query, args) |
| 431 |
return cursor.rowcount |
| 432 |
finally: |
| 433 |
cursor.close() |
| 434 |
|
| 435 |
@contextlib.contextmanager |
| 436 |
def savepoint(self) -> Iterator: |
| 437 |
"""sets up a section protected by a savepoint that will be released |
| 438 |
after use. |
| 439 |
|
| 440 |
If an exception happens in the controlled section, the connection |
| 441 |
will be rolled back to the savepoint. |
| 442 |
""" |
| 443 |
savepointName = "auto_%s"%(random.randint(0, 2147483647)) |
| 444 |
self.execute("SAVEPOINT %s"%savepointName) |
| 445 |
try: |
| 446 |
yield |
| 447 |
except: |
| 448 |
self.execute("ROLLBACK TO SAVEPOINT %s"%savepointName) |
| 449 |
raise |
| 450 |
finally: |
| 451 |
self.execute("RELEASE SAVEPOINT %s"%savepointName) |
| 452 |
|
| 453 |
|
| 454 |
class DebugConnection(DaCHSConnection): # pragma: no cover |
| 455 |
def cursor(self, *args, **kwargs): |
| 456 |
kwargs["cursor_factory"] = DebugCursor |
| 457 |
return psycopg2.extensions.connection.cursor(self, *args, **kwargs) |
| 458 |
|
| 459 |
def commit(self) -> None: |
| 460 |
print("Commit %s"%id(self)) |
| 461 |
return DaCHSConnection.commit(self) |
| 462 |
|
| 463 |
def rollback(self) -> None: |
| 464 |
print("Rollback %s"%id(self)) |
| 465 |
return DaCHSConnection.rollback(self) |
| 466 |
|
| 467 |
def getPID(self) -> int: |
| 468 |
cursor = self.cursor() |
| 469 |
cursor.execute("SELECT pg_backend_pid()") |
| 470 |
pid = list(cursor)[0][0] |
| 471 |
cursor.close() |
| 472 |
return pid |
| 473 |
|
| 474 |
|
| 475 |
def getDBConnection( |
| 476 |
profile: Union[str, config.DBProfile], |
| 477 |
debug: bool = _DEBUG, |
| 478 |
autocommitted: bool = False) -> DaCHSConnection: |
| 479 |
"""returns an enhanced database connection through profile. |
| 480 |
|
| 481 |
You will typically rather use the context managers for the standard |
| 482 |
profiles (``getTableConnection`` and friends). Use this function if |
| 483 |
you want to keep your connection out of connection pools or if you want |
| 484 |
to use non-standard profiles. |
| 485 |
|
| 486 |
profile will usually be a string naming a profile defined in |
| 487 |
``GAVO_ROOT/etc``. |
| 488 |
""" |
| 489 |
if isinstance(profile, str): |
| 490 |
profile = config.getDBProfile(profile) |
| 491 |
profile = cast(config.DBProfile, profile) |
| 492 |
|
| 493 |
if _DEBUG: # pragma: no cover |
| 494 |
conn = psycopg2.connect( # type: ignore # upstream types too crazy |
| 495 |
connection_factory=cast(Callable, DebugConnection), |
| 496 |
**profile.getArgs()) |
| 497 |
print("NEW CONN using %s (%s)"%(profile.name, conn.getPID()), id(conn)) |
| 498 |
def closer(): |
| 499 |
print("CONNECTION CLOSE", id(conn)) |
| 500 |
return DebugConnection.close(conn) |
| 501 |
conn.close = closer |
| 502 |
else: |
| 503 |
try: |
| 504 |
conn = psycopg2.connect( # type: ignore # upstream types too crazy |
| 505 |
connection_factory=cast(Callable, DaCHSConnection), |
| 506 |
**profile.getArgs()) |
| 507 |
except OperationalError as msg: |
| 508 |
raise utils.ReportableError("Cannot connect to the database server." |
| 509 |
" The database library reported:\n\n%s"%str(msg), |
| 510 |
hint="This usually means you must adapt either the access profiles" |
| 511 |
" in $GAVO_DIR/etc or your database config (in particular," |
| 512 |
" pg_hba.conf).") |
| 513 |
|
| 514 |
if autocommitted: |
| 515 |
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) |
| 516 |
conn.set_client_encoding("UTF8") |
| 517 |
|
| 518 |
conn._getDBConnectionArgs = { |
| 519 |
"profile": profile, |
| 520 |
"debug": _DEBUG, |
| 521 |
"autocommitted": autocommitted} |
| 522 |
return conn |
| 523 |
|
| 524 |
|
| 525 |
def _parseTableName( |
| 526 |
tableName: str, |
| 527 |
schema: Optional[Any] = None) -> Tuple[str, str]: |
| 528 |
"""returns schema, unqualified table name for the arguments. |
| 529 |
|
| 530 |
schema=None selects the default schema (public for postgresql). |
| 531 |
|
| 532 |
If tableName is qualified (i.e. schema.table), the schema given |
| 533 |
in the name overrides the schema argument. |
| 534 |
|
| 535 |
We do not support delimited identifiers for tables in DaCHS. Hence, |
| 536 |
this will raise a ValueError if anything that wouldn't work as |
| 537 |
an SQL regular identifier (except we don't filter for reserved |
| 538 |
words yet, which is an implementation detail that might change). |
| 539 |
""" |
| 540 |
parts = tableName.split(".") |
| 541 |
if len(parts)>2: |
| 542 |
raise ValueError("%s is not a SQL regular identifier"%repr(tableName)) |
| 543 |
for p in parts: |
| 544 |
if not utils.identifierPattern.match(p): |
| 545 |
raise ValueError("%s is not a SQL regular identifier"%repr(tableName)) |
| 546 |
|
| 547 |
if len(parts)==1: |
| 548 |
name = parts[0] |
| 549 |
else: |
| 550 |
schema, name = parts |
| 551 |
|
| 552 |
if schema is None: |
| 553 |
schema = "public" |
| 554 |
|
| 555 |
return schema.lower(), name.lower() |
| 556 |
|
| 557 |
|
| 558 |
def _parseBannerString(bannerString: str) -> Tuple[int, int]: |
| 559 |
"""returns digits from a postgres server banner. |
| 560 |
|
| 561 |
This hardcodes the response given by postgres 8 and raises a ValueError |
| 562 |
if the expected format is not found. |
| 563 |
""" |
| 564 |
mat = re.match(r"PostgreSQL ([\d.]*)", bannerString) |
| 565 |
if not mat: |
| 566 |
raise ValueError("Cannot make out the Postgres server version from %s"% |
| 567 |
repr(bannerString)) |
| 568 |
return cast(Tuple[int, int], |
| 569 |
tuple(int(s) for s in mat.group(1).split("."))[:2]) |
| 570 |
|
| 571 |
|
| 572 |
def getPgVersion(digits: int = 2) -> Tuple[int, int]: |
| 573 |
"""returns the version number of the postgres server executing |
| 574 |
untrusted (ADQL) queries. |
| 575 |
|
| 576 |
This is relatively expensive, as it will actually ask the server. |
| 577 |
""" |
| 578 |
with getUntrustedConn() as conn: |
| 579 |
bannerString = list(conn.query("SELECT version()"))[0][0] |
| 580 |
return _parseBannerString(bannerString) |
| 581 |
|
| 582 |
|
| 583 |
class PostgresQueryMixin: |
| 584 |
"""A mixin containing various useful queries that are postgres specific. |
| 585 |
|
| 586 |
This mixin expects a parent that mixes in QuerierMixin (that, for now, |
| 587 |
also mixes in PostgresQueryMixin, so you won't need to mix this in). |
| 588 |
|
| 589 |
Looking back, all this should be moved to functions simply receiving |
| 590 |
a connection as an argument. Let's make it that one of these days. |
| 591 |
""" |
| 592 |
|
| 593 |
connection = cast(DaCHSConnection, None) |
| 594 |
|
| 595 |
def getPrimaryIndexName(self, tableName: str) -> str: |
| 596 |
"""returns the name of the index corresponding to the primary key on |
| 597 |
(the unqualified) tableName. |
| 598 |
""" |
| 599 |
return ("%s_pkey"%tableName).lower() |
| 600 |
|
| 601 |
def schemaExists(self, schema: str) -> bool: |
| 602 |
"""returns True if the named schema exists in the database. |
| 603 |
""" |
| 604 |
matches = list(self.connection.query("SELECT nspname FROM" |
| 605 |
" pg_namespace WHERE LOWER(nspname)=%(schemaName)s", { |
| 606 |
'schemaName': schema.lower(), |
| 607 |
})) |
| 608 |
return len(matches)!=0 |
| 609 |
|
| 610 |
def hasIndex(self, |
| 611 |
tableName: str, |
| 612 |
indexName: str, |
| 613 |
schema: Optional[str] = None |
| 614 |
) -> bool: |
| 615 |
"""returns True if table tablename has and index called indexName. |
| 616 |
|
| 617 |
See _parseTableName on the meaning of the arguments. |
| 618 |
""" |
| 619 |
schema, tableName = _parseTableName(tableName, schema) |
| 620 |
res = list(self.connection.query("SELECT indexname FROM" |
| 621 |
" pg_indexes WHERE schemaname=lower(%(schema)s) AND" |
| 622 |
" tablename=lower(%(tableName)s) AND" |
| 623 |
" indexname=lower(%(indexName)s)", locals())) |
| 624 |
return len(list(res))>0 |
| 625 |
|
| 626 |
def _getColIndices(self, |
| 627 |
relOID: int, |
| 628 |
colNames: Union[Set[str], List[str]]) -> List[int]: |
| 629 |
"""returns a list of column indices of colNames in the relation relOID. |
| 630 |
|
| 631 |
This really is a helper for foreignKeyExists. |
| 632 |
""" |
| 633 |
colNames = set(n.lower() for n in colNames) |
| 634 |
res = [r[0] for r in |
| 635 |
self.connection.query("SELECT attnum FROM pg_attribute WHERE" |
| 636 |
" attrelid=%(relOID)s and attname IN %(colNames)s", |
| 637 |
locals())] |
| 638 |
res.sort() |
| 639 |
return res |
| 640 |
|
| 641 |
def getForeignKeyName(self, |
| 642 |
srcTableName: str, |
| 643 |
destTableName: str, |
| 644 |
srcColNames: List[str], |
| 645 |
destColNames: List[str], |
| 646 |
schema: Optional[str] = None) -> Union[bool, str]: |
| 647 |
"""returns True-ish if there's a foreign key constraint on srcTable's |
| 648 |
srcColNames using destTableName's destColNames. |
| 649 |
|
| 650 |
Warning: names in XColNames that are not column names in the respective |
| 651 |
tables are ignored. |
| 652 |
|
| 653 |
This raises a ValueError if the foreign keys do not exist. |
| 654 |
""" |
| 655 |
try: |
| 656 |
srcOID = self.getOIDForTable(srcTableName, schema) |
| 657 |
srcColInds = self._getColIndices( #noflake: used in locals() |
| 658 |
srcOID, srcColNames) |
| 659 |
destOID = self.getOIDForTable(destTableName, schema) |
| 660 |
destColInds = self._getColIndices( #noflake: used in locals() |
| 661 |
destOID, destColNames) |
| 662 |
except Error: # Some of the items related probably don't exist |
| 663 |
return False |
| 664 |
|
| 665 |
res = list(self.connection.query("""SELECT conname FROM pg_constraint WHERE |
| 666 |
contype='f' |
| 667 |
AND conrelid=%(srcOID)s |
| 668 |
AND confrelid=%(destOID)s |
| 669 |
AND conkey=%(srcColInds)s::SMALLINT[] |
| 670 |
AND confkey=%(destColInds)s::SMALLINT[]""", locals())) |
| 671 |
|
| 672 |
if len(res)==1: |
| 673 |
return res[0][0] |
| 674 |
else: |
| 675 |
raise ValueError("Non-existing or ambiguous foreign key") |
| 676 |
|
| 677 |
def foreignKeyExists(self, |
| 678 |
srcTableName: str, |
| 679 |
destTableName: str, |
| 680 |
srcColNames: List[str], |
| 681 |
destColNames: List[str], |
| 682 |
schema: Optional[str] = None) -> bool: |
| 683 |
try: |
| 684 |
_ = self.getForeignKeyName( |
| 685 |
srcTableName, destTableName, |
| 686 |
srcColNames, destColNames, |
| 687 |
schema) |
| 688 |
return True |
| 689 |
except ValueError: |
| 690 |
return False |
| 691 |
|
| 692 |
@functools.lru_cache() |
| 693 |
def _resolveTypeCode(self, oid: int) -> str: |
| 694 |
"""returns a textual description for a type oid as returned |
| 695 |
by cursor.description. |
| 696 |
|
| 697 |
These descriptions are *not* DDL-ready. |
| 698 |
|
| 699 |
*** postgres specific *** |
| 700 |
""" |
| 701 |
res = list(self.connection.query( |
| 702 |
"select typname from pg_type where oid=%(oid)s", {"oid": oid})) |
| 703 |
return res[0][0] |
| 704 |
|
| 705 |
def getColumnsFromDB(self, tableName: str) -> List[Tuple[str, str]]: |
| 706 |
"""returns a sequence of (name, type) pairs of the columns this |
| 707 |
table has in the database. |
| 708 |
|
| 709 |
If the table is not on disk, this will raise a NotFoundError. |
| 710 |
|
| 711 |
*** postgres specific *** |
| 712 |
""" |
| 713 |
# _parseTableName bombs out on non-regular identifiers, hence |
| 714 |
# foiling a possible SQL injection |
| 715 |
_parseTableName(tableName) |
| 716 |
cursor = self.connection.cursor() |
| 717 |
try: |
| 718 |
cursor.execute("select * from %s limit 0"%tableName) |
| 719 |
return [(col.name, self._resolveTypeCode(col.type_code)) for col in |
| 720 |
cursor.description or ()] |
| 721 |
finally: |
| 722 |
cursor.close() |
| 723 |
|
| 724 |
def getRowEstimate(self, tableName: str) -> int: |
| 725 |
"""returns the size of the table in rows as estimated by the query |
| 726 |
planner. |
| 727 |
|
| 728 |
This will raise a KeyError with tableName if the table isn't known |
| 729 |
to postgres. |
| 730 |
|
| 731 |
*** postgres specific *** |
| 732 |
""" |
| 733 |
res = list(self.connection.query( |
| 734 |
"SELECT reltuples FROM pg_class WHERE oid = %(tableName)s::regclass", |
| 735 |
locals())) |
| 736 |
# this is guaranteed to return something because of the ::regclass |
| 737 |
# cast that will fail for non-existing tables. |
| 738 |
return int(res[0][0]) |
| 739 |
|
| 740 |
def roleExists(self, role: str) -> bool: |
| 741 |
"""returns True if there role is known to the database. |
| 742 |
|
| 743 |
*** postgres specific *** |
| 744 |
""" |
| 745 |
matches = list(self.connection.query( |
| 746 |
"SELECT usesysid FROM pg_user WHERE usename=%(role)s", |
| 747 |
locals())) |
| 748 |
return len(matches)!=0 |
| 749 |
|
| 750 |
def getOIDForTable(self, tableName: str, schema: Optional[str] = None) -> int: |
| 751 |
"""returns the current oid of tableName. |
| 752 |
|
| 753 |
tableName may be schema qualified. If it is not, public is assumed. |
| 754 |
|
| 755 |
*** postgres specific *** |
| 756 |
""" |
| 757 |
schema, tableName = _parseTableName(tableName, schema) |
| 758 |
try: |
| 759 |
return list(self.connection.query( |
| 760 |
"SELECT %(tableName)s::regclass::bigint", |
| 761 |
{"tableName": f"{schema}.{tableName}"}))[0][0] |
| 762 |
except errors.UndefinedTable as ex: |
| 763 |
raise DBError(str(ex)) from ex |
| 764 |
|
| 765 |
def getTableType(self, |
| 766 |
tableName: str, |
| 767 |
schema: Optional[str] = None) -> Optional[str]: |
| 768 |
"""returns the type of the relation relationName. |
| 769 |
|
| 770 |
If relationName does not exist, None is returned. Otherwise, it's |
| 771 |
what is in the information schema for the table, which for postgres |
| 772 |
currently is one of BASE TABLE, VIEW, FOREIGN TABLE, MATERIALIZED VIEW, |
| 773 |
or LOCAL TEMPORARY. |
| 774 |
|
| 775 |
The DaCHS-idiomatic way to see if a relation exists is |
| 776 |
getTableType() is not None. |
| 777 |
|
| 778 |
You can pass in schema-qualified relation names, or the relation name |
| 779 |
and the schema separately. |
| 780 |
|
| 781 |
*** postgres specific *** |
| 782 |
""" |
| 783 |
schema, tableName = _parseTableName(tableName, schema) |
| 784 |
res = list( |
| 785 |
self.connection.query("""SELECT table_name, table_type FROM |
| 786 |
information_schema.tables WHERE ( |
| 787 |
table_schema=%(schemaName)s |
| 788 |
OR table_type='LOCAL TEMPORARY') |
| 789 |
AND table_name=%(tableName)s""", { |
| 790 |
'tableName': tableName.lower(), |
| 791 |
'schemaName': schema.lower()})) |
| 792 |
|
| 793 |
if not res: |
| 794 |
# materialised views are not yet in information_schema.tables, |
| 795 |
# so we try again with a special postgres case. |
| 796 |
if list(self.connection.query( |
| 797 |
"select table_name from information_schema.tables" |
| 798 |
" where table_name='pg_matviews'")): |
| 799 |
res = list( |
| 800 |
self.connection.query( |
| 801 |
"""SELECT matviewname, 'MATERIALIZED VIEW' AS table_type |
| 802 |
FROM pg_matviews |
| 803 |
WHERE |
| 804 |
schemaname=%(schemaName)s |
| 805 |
AND matviewname=%(tableName)s""", { |
| 806 |
'tableName': tableName.lower(), |
| 807 |
'schemaName': schema.lower()})) |
| 808 |
|
| 809 |
if not res: |
| 810 |
return None |
| 811 |
|
| 812 |
assert len(res)==1 |
| 813 |
return res[0][1] |
| 814 |
|
| 815 |
def dropTable(self, tableName: str, cascade: bool = False) -> None: |
| 816 |
"""drops a table or view named by tableName. |
| 817 |
|
| 818 |
This does not raise an error if no such relation exists. |
| 819 |
|
| 820 |
*** postgres specific *** |
| 821 |
""" |
| 822 |
tableType = self.getTableType(tableName) |
| 823 |
if tableType is None: |
| 824 |
return |
| 825 |
|
| 826 |
dropQualification = { |
| 827 |
"VIEW": "VIEW", |
| 828 |
"MATERIALIZED VIEW": "MATERIALIZED VIEW", |
| 829 |
"FOREIGN TABLE": "FOREIGN TABLE", |
| 830 |
"BASE TABLE": "TABLE", |
| 831 |
"LOCAL TEMPORARY": "TABLE"}[tableType] |
| 832 |
self.connection.execute("DROP %s %s %s"%( |
| 833 |
dropQualification, |
| 834 |
tableName, |
| 835 |
"CASCADE" if cascade else "")) |
| 836 |
|
| 837 |
def getSchemaPrivileges(self, schema: str) -> Dict[str, str]: |
| 838 |
"""returns (owner, readRoles, allRoles) for schema's ACL. |
| 839 |
""" |
| 840 |
res = list(self.connection.query("SELECT nspacl FROM pg_namespace WHERE" |
| 841 |
" nspname=%(schema)s", locals())) |
| 842 |
return self.parsePGACL(res[0][0]) |
| 843 |
|
| 844 |
def getTablePrivileges(self, schema: str, tableName: str) -> Dict: |
| 845 |
"""returns (owner, readRoles, allRoles) for the relation tableName |
| 846 |
and the schema. |
| 847 |
|
| 848 |
*** postgres specific *** |
| 849 |
""" |
| 850 |
res = list(self.connection.query("SELECT relacl FROM pg_class WHERE" |
| 851 |
" lower(relname)=lower(%(tableName)s) AND" |
| 852 |
" relnamespace=(SELECT oid FROM pg_namespace WHERE nspname=%(schema)s)", |
| 853 |
locals())) |
| 854 |
try: |
| 855 |
return self.parsePGACL(res[0][0]) |
| 856 |
except IndexError: # Table doesn't exist, so no privileges |
| 857 |
return {} |
| 858 |
|
| 859 |
_privTable = { |
| 860 |
"arwdRx": "ALL", |
| 861 |
"arwdDxt": "ALL", |
| 862 |
"arwdRxt": "ALL", |
| 863 |
"arwdxt": "ALL", |
| 864 |
"r": "SELECT", |
| 865 |
"UC": "ALL", |
| 866 |
"U": "USAGE", |
| 867 |
} |
| 868 |
|
| 869 |
def parsePGACL(self, acl: Optional[str]) -> Dict[str, str]: |
| 870 |
"""returns a dict roleName->acl for acl in postgres' |
| 871 |
ACL serialization. |
| 872 |
|
| 873 |
** postgres specific ** |
| 874 |
""" |
| 875 |
if acl is None: |
| 876 |
return {} |
| 877 |
res = [] |
| 878 |
for acs in cast(re.Match, re.match("{(.*)}", acl)).group(1).split(","): |
| 879 |
if acs!='': # empty ACLs don't match the RE, so catch them here |
| 880 |
role, privs, granter = cast(re.Match, |
| 881 |
re.match("([^=]*)=([^/]*)/(.*)", acs)).groups() |
| 882 |
res.append((role, self._privTable.get(privs, "READ"))) |
| 883 |
return dict(res) |
| 884 |
|
| 885 |
def getACLFromRes(self, |
| 886 |
thingWithPrivileges: Union["TableDef", "RD"]) -> Dict[str, str]: |
| 887 |
"""returns a dict of (role, ACL) as it is defined in thingWithPrivileges. |
| 888 |
|
| 889 |
thingWithPrivileges is something mixing in rscdef.common.PrivilegesMixin. |
| 890 |
(or has readProfiles and allProfiles attributes containing |
| 891 |
sequences of profile names). |
| 892 |
""" |
| 893 |
res = [] |
| 894 |
if hasattr(thingWithPrivileges, "schema"): # it's an RD |
| 895 |
readRight = "USAGE" |
| 896 |
else: |
| 897 |
readRight = "SELECT" |
| 898 |
|
| 899 |
for profile in thingWithPrivileges.readProfiles: |
| 900 |
res.append((config.getDBProfile(profile).roleName, readRight)) |
| 901 |
for profile in thingWithPrivileges.allProfiles: |
| 902 |
res.append((config.getDBProfile(profile).roleName, "ALL")) |
| 903 |
return dict(res) |
| 904 |
|
| 905 |
|
| 906 |
class StandardQueryMixin(PostgresQueryMixin): |
| 907 |
"""is a mixin containing various useful queries that should work |
| 908 |
against all SQL systems. |
| 909 |
|
| 910 |
This mixin expects a parent that mixes is QuerierMixin (that, for now, |
| 911 |
also mixes in StandardQueryMixin, so you won't need to mix this in). |
| 912 |
|
| 913 |
The parent also needs to mix in something like PostgresQueryMixin (I |
| 914 |
might want to define an interface there once I'd like to support |
| 915 |
other databases). |
| 916 |
|
| 917 |
Really, the idea of having a cross-DB DaCHS is a thing of the past. |
| 918 |
Let's convert all of these into functions, too. |
| 919 |
""" |
| 920 |
def setSchemaPrivileges(self, rd: "RD") -> None: |
| 921 |
"""sets the privileges defined on rd to its schema. |
| 922 |
|
| 923 |
This function will never touch the public schema. |
| 924 |
""" |
| 925 |
schema = rd.schema.lower() |
| 926 |
if schema=="public": |
| 927 |
return |
| 928 |
self._updatePrivileges(f"SCHEMA {schema}", |
| 929 |
self.getSchemaPrivileges(schema), self.getACLFromRes(rd)) |
| 930 |
|
| 931 |
def setTablePrivileges(self, tableDef: "TableDef") -> None: |
| 932 |
"""sets the privileges defined in tableDef for that table through |
| 933 |
querier. |
| 934 |
""" |
| 935 |
self._updatePrivileges(tableDef.getQName(), |
| 936 |
self.getTablePrivileges(tableDef.rd.schema, tableDef.id), |
| 937 |
self.getACLFromRes(tableDef)) |
| 938 |
|
| 939 |
def _updatePrivileges(self, |
| 940 |
objectName: str, |
| 941 |
foundPrivs: Dict[str, str], |
| 942 |
shouldPrivs: Dict[str, str]) -> None: |
| 943 |
"""helps set[Table|Schema]Privileges. |
| 944 |
|
| 945 |
Requests for granting privileges not known to the database are |
| 946 |
ignored, but a log entry is generated. |
| 947 |
""" |
| 948 |
for role in set(foundPrivs)-set(shouldPrivs): |
| 949 |
if role: |
| 950 |
self.connection.execute("REVOKE ALL PRIVILEGES ON %s FROM %s"%( |
| 951 |
objectName, role)) |
| 952 |
for role in set(shouldPrivs)-set(foundPrivs): |
| 953 |
if role: |
| 954 |
if self.roleExists(role): |
| 955 |
self.connection.execute( |
| 956 |
"GRANT %s ON %s TO %s"%(shouldPrivs[role], objectName, role)) |
| 957 |
else: |
| 958 |
utils.sendUIEvent("Warning", |
| 959 |
"Request to grant privileges to non-existing" |
| 960 |
" database user %s dropped"%role) |
| 961 |
for role in set(shouldPrivs)&set(foundPrivs): |
| 962 |
if role: |
| 963 |
if shouldPrivs[role]!=foundPrivs[role]: |
| 964 |
self.connection.execute("REVOKE ALL PRIVILEGES ON %s FROM %s"%( |
| 965 |
objectName, role)) |
| 966 |
self.connection.execute("GRANT {} ON {} TO {}".format( |
| 967 |
shouldPrivs[role], |
| 968 |
objectName, |
| 969 |
role)) |
| 970 |
|
| 971 |
|
| 972 |
class QuerierMixin(StandardQueryMixin): |
| 973 |
"""A mixin for "queriers", i.e., objects that maintain a db connection. |
| 974 |
|
| 975 |
The mixin assumes an attribute ``connection`` from the parent. |
| 976 |
""" |
| 977 |
defaultProfile = None |
| 978 |
# _reconnecting is used in query |
| 979 |
_reconnecting = False |
| 980 |
|
| 981 |
def enableAutocommit(self) -> None: |
| 982 |
self.connection.set_isolation_level( |
| 983 |
psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) |
| 984 |
|
| 985 |
def _queryReconnecting(self, |
| 986 |
query: "_PsycoQuery", |
| 987 |
data: "_PsycoArgs", |
| 988 |
timeout: Optional[float]) -> Iterator: |
| 989 |
"""helps query in case of disconnections. |
| 990 |
""" |
| 991 |
self.connection = getDBConnection( |
| 992 |
**self.connection._getDBConnectionArgs) # type: ignore # set externally |
| 993 |
self._reconnecting = True |
| 994 |
res = self.connection.query(query, data, timeout) |
| 995 |
self._reconnecting = False |
| 996 |
return res |
| 997 |
|
| 998 |
def query(self, |
| 999 |
query: "_PsycoQuery", |
| 1000 |
data: "_PsycoArgs" = {}, |
| 1001 |
timeout: Optional[float] = None) -> Iterator: |
| 1002 |
"""wraps conn.query adding logic to re-establish lost connections. |
| 1003 |
|
| 1004 |
Don't use this method any more in new code. It contains wicked |
| 1005 |
logic to tell DDL statements (that run without anyone pulling |
| 1006 |
the results) from actual selects. That's a bad API. Also note |
| 1007 |
that the timeout is ignored for DDL statements. |
| 1008 |
|
| 1009 |
We'll drop this some time in 2023. |
| 1010 |
|
| 1011 |
Use either connection.query or connection.execute in new code. |
| 1012 |
""" |
| 1013 |
warnings.warn("You are using querier.query (or perhaps table.query)." |
| 1014 |
" This has terrible semantics; use querier.connection.query" |
| 1015 |
" for statements returning rows and .execute for DDL statements.", |
| 1016 |
category=FutureWarning) |
| 1017 |
|
| 1018 |
if self.connection is None: |
| 1019 |
raise utils.ReportableError( |
| 1020 |
"SimpleQuerier connection is None.", |
| 1021 |
hint="This usually is because an AdhocQuerier's query method" |
| 1022 |
" was used outside of a with block.") |
| 1023 |
|
| 1024 |
try: |
| 1025 |
if cast(str, query)[:5].lower() in ["selec", "with "]: |
| 1026 |
return self.connection.query(query, data, timeout) |
| 1027 |
else: |
| 1028 |
# it's DDL that we execute directly, ignoring the timeout |
| 1029 |
self.connection.execute(query, data) |
| 1030 |
except DBError as ex: |
| 1031 |
if isinstance(ex, OperationalError) and self.connection.fileno()==-1: |
| 1032 |
if not self._reconnecting: |
| 1033 |
return self._queryReconnecting(query, data, timeout) |
| 1034 |
raise |
| 1035 |
|
| 1036 |
return iter([]) |
| 1037 |
|
| 1038 |
def queryToDicts(self, *args, **kwargs): |
| 1039 |
"""wraps conn.queryToDicts for backwards compatilitiy. |
| 1040 |
""" |
| 1041 |
return self.connection.queryToDicts(*args, **kwargs) |
| 1042 |
|
| 1043 |
|
| 1044 |
class UnmanagedQuerier(QuerierMixin): |
| 1045 |
"""A simple interface to querying the database through a connection |
| 1046 |
managed by someone else. |
| 1047 |
|
| 1048 |
This is typically used as in:: |
| 1049 |
|
| 1050 |
with base.getTableConn() as conn: |
| 1051 |
q = UnmanagedQuerier(conn) |
| 1052 |
... |
| 1053 |
|
| 1054 |
This contains numerous methods abstracting DB functionality a bit. |
| 1055 |
Documented ones include: |
| 1056 |
|
| 1057 |
* schemaExists(schema) |
| 1058 |
* getColumnsFromDB(tableName) |
| 1059 |
* getTableType(tableName) -- this will return None for non-existing tables, |
| 1060 |
which is DaCHS' official way to determine table existence. |
| 1061 |
|
| 1062 |
Again, let's move all this to plain functions. |
| 1063 |
""" |
| 1064 |
def __init__(self, connection: DaCHSConnection) -> None: |
| 1065 |
self.connection = connection |
| 1066 |
|
| 1067 |
|
| 1068 |
class AdhocQuerier(QuerierMixin): |
| 1069 |
"""A simple interface to querying the database through pooled |
| 1070 |
connections. |
| 1071 |
|
| 1072 |
These are constructed using the connection getters (getTableConn (default), |
| 1073 |
getAdminConn) and then serve as context managers, handing back the connection |
| 1074 |
as you exit the controlled block. |
| 1075 |
|
| 1076 |
Since they operate through pooled connections, no transaction |
| 1077 |
management takes place. These are typically for read-only things. |
| 1078 |
|
| 1079 |
You can use the query method and everything that's in the QuerierMixin. |
| 1080 |
""" |
| 1081 |
def __init__(self, |
| 1082 |
connectionManager: Optional["_ConnectionManager"] = None) -> None: |
| 1083 |
if connectionManager is None: |
| 1084 |
self.connectionManager: "_ConnectionManager" = getTableConn |
| 1085 |
else: |
| 1086 |
self.connectionManager = connectionManager |
| 1087 |
self.connection: DaCHSConnection = cast(DaCHSConnection, None) |
| 1088 |
|
| 1089 |
def __enter__(self) -> "AdhocQuerier": |
| 1090 |
self._cm = self.connectionManager() |
| 1091 |
self.connection = self._cm.__enter__() |
| 1092 |
return self |
| 1093 |
|
| 1094 |
def __exit__(self, *args: Any) -> Optional[bool]: |
| 1095 |
self.connection = cast(DaCHSConnection, None) |
| 1096 |
return self._cm.__exit__(*args) |
| 1097 |
|
| 1098 |
|
| 1099 |
_NBQueryResult = Union[Exception, List[Union[Dict, Tuple]], None] |
| 1100 |
|
| 1101 |
class NonBlockingQuery: |
| 1102 |
"""a query run in a pseudo-nonblocking way. |
| 1103 |
|
| 1104 |
While psycopg2 can do proper async, that doesn't play well with |
| 1105 |
about everything else DaCHS is doing so far. So, here's a quick |
| 1106 |
way to allow long-running queries that users can still interrupt. |
| 1107 |
The ugly secret is that it's based on threads. |
| 1108 |
|
| 1109 |
Note that psycopg2 has set_wait_callback, which would let us do |
| 1110 |
this without threads. But since that's a global setting, we can't |
| 1111 |
really use it here, because even outside of the server, we don't |
| 1112 |
control what other database queries will run and not expect to |
| 1113 |
suddenly be async. |
| 1114 |
|
| 1115 |
This should not be used within the server. We might want to port |
| 1116 |
the async taprunner (which runs outside of the server) to using this, |
| 1117 |
though. |
| 1118 |
|
| 1119 |
To use it, construct it with conn, query and perhaps args and |
| 1120 |
use it as a context manager. For non-SELECT queries, you have |
| 1121 |
to pass fetchResults=False; results, in this case, will become |
| 1122 |
an empty list once the query has run. |
| 1123 |
|
| 1124 |
Poll getResult() until it's non-None; this will then be either a list of |
| 1125 |
result rows (empty if you passed fetchResults=False) or an Exception (which |
| 1126 |
will also be raised when exiting the context manager). |
| 1127 |
|
| 1128 |
Do not access _results directly without holding resultLock. |
| 1129 |
|
| 1130 |
To abort a running query, call abort(). |
| 1131 |
""" |
| 1132 |
def __init__(self, |
| 1133 |
conn: DaCHSConnection, |
| 1134 |
query: str, |
| 1135 |
args: Dict[str, str] = {}, |
| 1136 |
fetchResults: bool = True) -> None: |
| 1137 |
self.conn, self.query, self.args = conn, query, args |
| 1138 |
self.backendPID = list(self.conn.query("SELECT pg_backend_pid()"))[0] |
| 1139 |
self.fetchResults = fetchResults |
| 1140 |
self.resultLock = threading.RLock() |
| 1141 |
|
| 1142 |
# will be set only from the thread |
| 1143 |
self._result: _NBQueryResult = None |
| 1144 |
|
| 1145 |
def __enter__(self) -> "NonBlockingQuery": |
| 1146 |
self.thread = threading.Thread(target=self._runQuery) |
| 1147 |
self.thread.setDaemon(True) |
| 1148 |
self.thread.start() |
| 1149 |
return self |
| 1150 |
|
| 1151 |
def __exit__(self, *excInfo: Any) -> None: |
| 1152 |
self.cleanup(2) |
| 1153 |
if excInfo==(None, None, None) and isinstance(self._result, Exception): |
| 1154 |
# this probably is a memory leak, which is one of the reasons |
| 1155 |
# this shouldn't be used in the server without more thought |
| 1156 |
raise self._result |
| 1157 |
|
| 1158 |
def _runQuery(self) -> None: |
| 1159 |
try: |
| 1160 |
cursor = self.conn.cursor() |
| 1161 |
cursor.execute(self.query, self.args) |
| 1162 |
if self.fetchResults: |
| 1163 |
self.setResult(list(cursor)) |
| 1164 |
else: |
| 1165 |
self.setResult([]) |
| 1166 |
except QueryCanceledError: |
| 1167 |
# assume this happened on user request |
| 1168 |
pass |
| 1169 |
except Exception as ex: |
| 1170 |
self.setResult(ex) |
| 1171 |
|
| 1172 |
def setResult(self, result: _NBQueryResult) -> None: |
| 1173 |
with self.resultLock: |
| 1174 |
self._result = result |
| 1175 |
|
| 1176 |
def getResult(self) -> _NBQueryResult: |
| 1177 |
with self.resultLock: |
| 1178 |
return self._result |
| 1179 |
|
| 1180 |
def abort(self) -> None: |
| 1181 |
"""aborts the current query and reaps the thread. |
| 1182 |
""" |
| 1183 |
self.conn.cancel() |
| 1184 |
self.cleanup(1) |
| 1185 |
|
| 1186 |
def cleanup(self, timeout: Optional[float] = None) -> None: |
| 1187 |
"""tries to reap the thread (i.e., join it). |
| 1188 |
|
| 1189 |
If the thread hasn't terminated within timeout seconds, a |
| 1190 |
sqlsupport.Error is raised. |
| 1191 |
""" |
| 1192 |
self.thread.join(timeout=timeout) |
| 1193 |
if self.thread.is_alive(): |
| 1194 |
raise Error("Could not join NonBlockingQuery") |
| 1195 |
|
| 1196 |
|
| 1197 |
def setDBMeta(conn: DaCHSConnection, key: str, value: str): |
| 1198 |
"""adds/overwrites (key, value) in the dc.metastore table within |
| 1199 |
conn. |
| 1200 |
|
| 1201 |
conn must be an admin connection; this does not commit. |
| 1202 |
|
| 1203 |
key must be a string, value something unicodeable. |
| 1204 |
""" |
| 1205 |
conn.execute( |
| 1206 |
"INSERT INTO dc.metastore (key, value) VALUES (%(key)s, %(value)s)", { |
| 1207 |
'key': key, |
| 1208 |
'value': str(value)}) |
| 1209 |
|
| 1210 |
|
| 1211 |
def getDBMeta(key: str) -> str: |
| 1212 |
"""returns the value for key from within dc.metastore. |
| 1213 |
|
| 1214 |
This always returns a unicode string. Type conversions are the client's |
| 1215 |
business. |
| 1216 |
|
| 1217 |
If no value exists, this raises a KeyError. |
| 1218 |
""" |
| 1219 |
with getTableConn() as conn: |
| 1220 |
res = list(conn.query("SELECT value FROM dc.metastore WHERE" |
| 1221 |
" key=%(key)s", {"key": key})) |
| 1222 |
if not res: |
| 1223 |
raise KeyError(key) |
| 1224 |
return res[0][0] |
| 1225 |
|
| 1226 |
|
| 1227 |
class CustomConnectionPool(psycopg2.pool.ThreadedConnectionPool): |
| 1228 |
"""A threaded connection pool that returns connections made via |
| 1229 |
profileName. |
| 1230 |
""" |
| 1231 |
# we keep weak references to pools we've created so we can invalidate |
| 1232 |
# them all on a server restart to avoid having stale connections |
| 1233 |
# around. |
| 1234 |
knownPools: List[weakref.ReferenceType["CustomConnectionPool"]] = [] |
| 1235 |
|
| 1236 |
def __init__(self, |
| 1237 |
minconn: int, |
| 1238 |
maxconn: int, profileName: str, |
| 1239 |
autocommitted: bool = True) -> None: |
| 1240 |
# make sure no additional arguments come in, since we don't |
| 1241 |
# support them. |
| 1242 |
self.profileName = profileName |
| 1243 |
self.autocommitted = autocommitted |
| 1244 |
self.stale = False |
| 1245 |
psycopg2.pool.ThreadedConnectionPool.__init__( |
| 1246 |
self, minconn, maxconn) |
| 1247 |
self.knownPools.append(weakref.ref(self)) |
| 1248 |
|
| 1249 |
@classmethod |
| 1250 |
def serverRestarted(cls) -> None: |
| 1251 |
utils.sendUIEvent("Warning", "Suspecting a database restart." |
| 1252 |
" Discarding old connection pools, asking to create new ones.") |
| 1253 |
|
| 1254 |
for pool in cls.knownPools: |
| 1255 |
try: |
| 1256 |
cast("CustomConnectionPool", pool()).stale = True |
| 1257 |
except AttributeError: |
| 1258 |
# already gone |
| 1259 |
pass |
| 1260 |
# we risk a race condition here; this is used rarely enough that this |
| 1261 |
# shouldn't matter. |
| 1262 |
cls.knownPools = [] |
| 1263 |
|
| 1264 |
def _connect(self, key: Optional[int] = None) -> DaCHSConnection: |
| 1265 |
"""creates a new connection with our selected profile and assigns it to |
| 1266 |
key if not None. |
| 1267 |
|
| 1268 |
This is an implementation detail of psycopg2's connection |
| 1269 |
pools. |
| 1270 |
""" |
| 1271 |
conn = getDBConnection(self.profileName) |
| 1272 |
|
| 1273 |
if self.autocommitted: |
| 1274 |
try: |
| 1275 |
conn.set_session(autocommit=True, readonly=True) |
| 1276 |
except ProgrammingError: |
| 1277 |
utils.sendUIEvent("Warning", "Uncommitted transaction escaped; please" |
| 1278 |
" investigate and fix") |
| 1279 |
conn.commit() |
| 1280 |
|
| 1281 |
|
| 1282 |
# no idea why mypy doesn't see ThreadedConnectionPool's attributes |
| 1283 |
if key is not None: |
| 1284 |
self._used[key] = conn # type: ignore |
| 1285 |
self._rused[id(conn)] = key # type: ignore |
| 1286 |
else: |
| 1287 |
self._pool.append(conn) # type: ignore |
| 1288 |
return conn |
| 1289 |
|
| 1290 |
|
| 1291 |
def _cleanupAfterDBError( |
| 1292 |
ex: Exception, |
| 1293 |
conn: DaCHSConnection, |
| 1294 |
pool: List[CustomConnectionPool], |
| 1295 |
poolLock: threading.Lock) -> None: |
| 1296 |
"""removes conn from pool after an error occurred. |
| 1297 |
|
| 1298 |
This is a helper for getConnFromPool below. |
| 1299 |
""" |
| 1300 |
if isinstance(ex, OperationalError) and ex.pgcode is None: |
| 1301 |
# this is probably a db server restart. Invalidate all connections |
| 1302 |
# immediately. |
| 1303 |
with poolLock: |
| 1304 |
if pool: |
| 1305 |
pool[0].serverRestarted() |
| 1306 |
|
| 1307 |
# Make sure the connection is closed; something bad happened |
| 1308 |
# in it, so we don't want to re-use it |
| 1309 |
try: |
| 1310 |
pool[0].putconn(conn, close=True) |
| 1311 |
except InterfaceError: |
| 1312 |
# Connection already closed |
| 1313 |
pass |
| 1314 |
except Exception as msg: |
| 1315 |
utils.sendUIEvent("Error", |
| 1316 |
f"Disaster: {msg} while force-closing connection") |
| 1317 |
|
| 1318 |
|
| 1319 |
def _makeConnectionManager( |
| 1320 |
profileName: str, |
| 1321 |
autocommitted: bool = True, |
| 1322 |
singleton: bool = False) -> "_ConnectionManager": |
| 1323 |
"""returns a context manager for a connection pool for profileName |
| 1324 |
connections. |
| 1325 |
|
| 1326 |
With singleton=True, only one connection will be created rather than |
| 1327 |
[db]poolSize ones. |
| 1328 |
""" |
| 1329 |
pool = [] |
| 1330 |
poolLock = threading.Lock() |
| 1331 |
|
| 1332 |
def makePool() -> None: |
| 1333 |
if singleton: |
| 1334 |
minConn = 1 |
| 1335 |
else: |
| 1336 |
minConn = config.get("db", "poolSize") |
| 1337 |
|
| 1338 |
with poolLock: |
| 1339 |
pool.append(CustomConnectionPool( |
| 1340 |
minConn, |
| 1341 |
# I don't think there's any point in maxConn at all the |
| 1342 |
# way psycopg pools are done right now, so all I care about |
| 1343 |
# here is that it won't get in our way. |
| 1344 |
200, |
| 1345 |
profileName, |
| 1346 |
autocommitted)) |
| 1347 |
|
| 1348 |
def getConnFromPool() -> Iterator[Union[Iterator, Iterator[DaCHSConnection]]]: |
| 1349 |
# we delay pool creation since these functions are built during |
| 1350 |
# sqlsupport import. We probably don't have profiles ready |
| 1351 |
# at that point. |
| 1352 |
if not pool: |
| 1353 |
makePool() |
| 1354 |
|
| 1355 |
if pool[0].stale: |
| 1356 |
try: |
| 1357 |
pool[0].closeall() |
| 1358 |
except psycopg2.pool.PoolError: |
| 1359 |
# this happens when the pool has been closed already |
| 1360 |
pass |
| 1361 |
pool.pop() |
| 1362 |
makePool() |
| 1363 |
|
| 1364 |
conn = pool[0].getconn() |
| 1365 |
try: |
| 1366 |
yield conn |
| 1367 |
except Exception as ex: |
| 1368 |
# controlled block bombed out, do error handling |
| 1369 |
_cleanupAfterDBError(ex, conn, pool, poolLock) |
| 1370 |
raise |
| 1371 |
|
| 1372 |
else: |
| 1373 |
# no exception raised, commit if not autocommitted |
| 1374 |
if not autocommitted: |
| 1375 |
conn.commit() |
| 1376 |
|
| 1377 |
try: |
| 1378 |
pool[0].putconn(conn, close=conn.closed) |
| 1379 |
except InterfaceError: |
| 1380 |
# Connection already closed |
| 1381 |
pass |
| 1382 |
|
| 1383 |
res = contextlib.contextmanager(getConnFromPool) |
| 1384 |
# I want to look at the pools in web.ifpages.CurReaders, so I |
| 1385 |
# better expose them somewhere where they can be found in the |
| 1386 |
# hour of need. |
| 1387 |
res.pool = pool # type: ignore |
| 1388 |
|
| 1389 |
return cast("_ConnectionManager", res) |
| 1390 |
|
| 1391 |
|
| 1392 |
getUntrustedConn = _makeConnectionManager("untrustedquery") |
| 1393 |
getTableConn = _makeConnectionManager("trustedquery") |
| 1394 |
getAdminConn = _makeConnectionManager("admin", singleton=True) |
| 1395 |
|
| 1396 |
getWritableUntrustedConn = _makeConnectionManager("untrustedquery", |
| 1397 |
autocommitted=False, singleton=True) |
| 1398 |
getWritableTableConn = _makeConnectionManager("trustedquery", |
| 1399 |
autocommitted=False, singleton=True) |
| 1400 |
getWritableAdminConn = _makeConnectionManager("admin", |
| 1401 |
autocommitted=False, singleton=True) |
| 1402 |
|
| 1403 |
|
| 1404 |
def initPsycopg() -> None: |
| 1405 |
"""does any DaCHS-specific database setup necessary. |
| 1406 |
|
| 1407 |
This is executed on sqlsupport import unless we are in initdachs (or |
| 1408 |
setting up the testbed); see the foot of this module for how this is done. |
| 1409 |
|
| 1410 |
This needs to call the DaCHSConnection.senseEnvironment. |
| 1411 |
""" |
| 1412 |
conn = psycopg2.connect( # type: ignore # upstream types too crazy |
| 1413 |
connection_factory=DaCHSConnection, |
| 1414 |
**config.getDBProfile("feed").getArgs()) |
| 1415 |
try: |
| 1416 |
try: |
| 1417 |
from gavo.utils import pgsphere |
| 1418 |
pgsphere.preparePgSphere(conn) |
| 1419 |
except: # prama: no cover |
| 1420 |
warnings.warn("pgsphere missing -- ADQL, pg-SIAP, and SSA will not work") |
| 1421 |
|
| 1422 |
DaCHSConnection.senseEnvironment(conn) |
| 1423 |
finally: |
| 1424 |
conn.close() |
| 1425 |
|
| 1426 |
|
| 1427 |
if "GAVO_INIT_RUNNING" not in os.environ: |
| 1428 |
initPsycopg() |