| 1 |
""" |
| 2 |
A table representing a query. |
| 3 |
|
| 4 |
This is mainly for streaming applications. The table represents |
| 5 |
a DB query result. All you can do with the data itself is iterate over |
| 6 |
the rows. The metadata is usable as with any other table. |
| 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 |
from gavo import base |
| 16 |
from gavo import rscdef |
| 17 |
from gavo.rsc import dbtable |
| 18 |
from gavo.rsc import table |
| 19 |
|
| 20 |
|
| 21 |
class QueryTable(table.BaseTable, dbtable.DBMethodsMixin): |
| 22 |
"""QueryTables are constructed with a table definition and a DB query |
| 23 |
feeding this table definition. |
| 24 |
|
| 25 |
A QueryTable must be constructed with a transactional connection (in |
| 26 |
sqlsupport terms: Writable). If you pass autoClose=True, it will close this |
| 27 |
connection after the data is delivered. |
| 28 |
|
| 29 |
This funky semantics is for the benefit of taprunner; it needs a |
| 30 |
connection up front for uploads. |
| 31 |
|
| 32 |
There's an alternative constructor allowing "quick" construction of |
| 33 |
the result table (fromColumns). |
| 34 |
""" |
| 35 |
connection = None |
| 36 |
|
| 37 |
def __init__(self, tableDef, query, connection, **kwargs): |
| 38 |
self.connection = connection |
| 39 |
self.autoClose = kwargs.pop("autoClose", False) |
| 40 |
if "rows" in kwargs: |
| 41 |
raise base.ReportableError("QueryTables cannot be constructed" |
| 42 |
" with rows.") |
| 43 |
self.query = query |
| 44 |
table.BaseTable.__init__(self, tableDef, connection=connection, |
| 45 |
**kwargs) |
| 46 |
self._parametersToRestore = [] |
| 47 |
|
| 48 |
@classmethod |
| 49 |
def fromColumns(cls, colSpec, query, connection, **kwargs): |
| 50 |
"""returns a QueryTable object for query, where the result table is |
| 51 |
inferred from colSpec. |
| 52 |
|
| 53 |
colSpec is a sequence consisting of either dictionaries with constructor |
| 54 |
arguments to rscdef.Column or complete objects suitable as rscdef.Column |
| 55 |
objects; further kwargs are passed on the the QueryTable's constructor. |
| 56 |
""" |
| 57 |
columns = [] |
| 58 |
for c in colSpec: |
| 59 |
if isinstance(c, dict): |
| 60 |
columns.append(base.makeStruct(rscdef.Column, **c)) |
| 61 |
else: |
| 62 |
columns.append(c) |
| 63 |
return cls(base.makeStruct(rscdef.TableDef, columns=columns), |
| 64 |
query, connection=connection, **kwargs) |
| 65 |
|
| 66 |
def __iter__(self): |
| 67 |
"""actually runs the query and returns rows (dictionaries). |
| 68 |
|
| 69 |
You can only iterate once. At exhaustion, the connection will |
| 70 |
be closed. |
| 71 |
""" |
| 72 |
if self.connection is None: |
| 73 |
raise base.ReportableError("QueryTable already exhausted.") |
| 74 |
|
| 75 |
nRows = 0 |
| 76 |
|
| 77 |
# We want to enable parallel execution for queries where it's |
| 78 |
# worth it, but we'd like to stream your giant select *-type |
| 79 |
# queries. First gung-ho criterion: If there's a GROUP (sc. BY) |
| 80 |
# in query, |
| 81 |
# second gung-ho criterion: obscore queries. |
| 82 |
loQ = self.query.lower() |
| 83 |
if "group" in loQ or "ivoa.obscore" in loQ: |
| 84 |
cursor = self.connection.cursor() |
| 85 |
else: |
| 86 |
cursor = self.connection.cursor("cursor"+hex(id(self))) |
| 87 |
|
| 88 |
cursor.execute(self.query) |
| 89 |
try: |
| 90 |
while True: |
| 91 |
nextRows = cursor.fetchmany(100000) |
| 92 |
if not nextRows: |
| 93 |
break |
| 94 |
for row in nextRows: |
| 95 |
nRows += 1 |
| 96 |
yield self.tableDef.makeRowFromTuple(row) |
| 97 |
cursor.close() |
| 98 |
|
| 99 |
# overflowLimit is usually set by the TAP machinery; we don't |
| 100 |
# want to depend on it, though. |
| 101 |
if getattr(self.tableDef, "overflowLimit", None)==nRows: |
| 102 |
self.setMeta("_queryStatus", "OVERFLOW") |
| 103 |
finally: |
| 104 |
self.cleanup() |
| 105 |
|
| 106 |
def __len__(self): |
| 107 |
return None |
| 108 |
|
| 109 |
def configureOnClose(self, parPairs): |
| 110 |
"""adds parameter pairs (as coming back from conn.configure) to |
| 111 |
a set of pairs to be restored when this qtable is being cleaned |
| 112 |
up. |
| 113 |
|
| 114 |
For a connection in error, use of this facility will mean |
| 115 |
that connections will be rolled back automatically (because |
| 116 |
we couldn't restore the parameters otherwise). |
| 117 |
""" |
| 118 |
self._parametersToRestore.extend(parPairs) |
| 119 |
|
| 120 |
def _restoreParameters(self): |
| 121 |
"""helps configureOnClose. |
| 122 |
""" |
| 123 |
if self._parametersToRestore and self.connection is not None: |
| 124 |
try: |
| 125 |
self.connection.configure(self._parametersToRestore) |
| 126 |
except base.DBError: |
| 127 |
# the connection might be in an error state. Roll back and |
| 128 |
# try again. If that fails again, things are really bad |
| 129 |
# and nobody will be interested in the fact that parameter |
| 130 |
# restoration has failed, so fail silently. |
| 131 |
try: |
| 132 |
self.connection.rollback() |
| 133 |
self.connection.configure(self._parametersToRestore) |
| 134 |
except base.DBError: # see above |
| 135 |
pass |
| 136 |
|
| 137 |
def cleanup(self): |
| 138 |
if getattr(self, "connection", None) is not None: |
| 139 |
if self.autoClose: |
| 140 |
try: |
| 141 |
self.connection.close() |
| 142 |
except base.DBError: |
| 143 |
# Connection already closed or similarly ignorable |
| 144 |
pass |
| 145 |
else: |
| 146 |
self._restoreParameters() |
| 147 |
|
| 148 |
self.connection = None |
| 149 |
|
| 150 |
def getPlan(self): |
| 151 |
"""returns a parsed query plan for the current query. |
| 152 |
|
| 153 |
After you use this method, the iterator is exhausted and the |
| 154 |
connection will be closed. |
| 155 |
""" |
| 156 |
cursor = self.connection.cursor() |
| 157 |
cursor.execute("EXPLAIN "+self.query) |
| 158 |
res = "\n".join(s[0] for s in cursor) |
| 159 |
self.cleanup() |
| 160 |
return res |
| 161 |
|
| 162 |
def __del__(self): |
| 163 |
self.cleanup() |