| 1 |
""" |
| 2 |
Tables on disk |
| 3 |
""" |
| 4 |
|
| 5 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 6 |
#c |
| 7 |
#c This program is free software, covered by the GNU GPL. See the |
| 8 |
#c COPYING file in the source distribution. |
| 9 |
|
| 10 |
|
| 11 |
import sys |
| 12 |
|
| 13 |
from psycopg2.extras import execute_batch |
| 14 |
|
| 15 |
from gavo import base |
| 16 |
from gavo import rscdef |
| 17 |
from gavo import utils |
| 18 |
from gavo.base import sqlsupport |
| 19 |
from gavo.rsc import table |
| 20 |
|
| 21 |
|
| 22 |
class _Feeder(table._Feeder): |
| 23 |
"""A context manager for feeding data into a table. |
| 24 |
|
| 25 |
This feeder hands through batchSize items at a time to the database. |
| 26 |
|
| 27 |
After an exit, the instances have an nAffected attribute that says |
| 28 |
how many rows were processed by the database through this feeder. |
| 29 |
|
| 30 |
A feeder is constructed with a parent table (that also provides |
| 31 |
the connection), an insert command, and potentially some options. |
| 32 |
|
| 33 |
Note that the table feeder does *not* do any connection management. |
| 34 |
You have to commit or rollback yourself (or do it properly and go |
| 35 |
through data, which can do connection management). |
| 36 |
""" |
| 37 |
def __init__(self, parent, insertCommand, batchSize=2000, notify=True): |
| 38 |
self.nAffected, self.notify = 0, notify |
| 39 |
table._Feeder.__init__(self, parent) |
| 40 |
self.feedCommand, self.batchSize = insertCommand, batchSize |
| 41 |
self.batchCache = [] |
| 42 |
|
| 43 |
def shipout(self): |
| 44 |
if self.batchCache: |
| 45 |
try: |
| 46 |
execute_batch(self.cursor, |
| 47 |
self.feedCommand, self.batchCache, |
| 48 |
self.batchSize) |
| 49 |
except sqlsupport.IntegrityError: |
| 50 |
base.ui.notifyInfo("One or more of the following rows clashed: "+ |
| 51 |
str(self.batchCache)) |
| 52 |
raise |
| 53 |
except sqlsupport.DataError: |
| 54 |
base.ui.notifyInfo("Bad input. Run with -b1 to pin down offending" |
| 55 |
" record. First rec: %s"%self.batchCache[0]) |
| 56 |
raise |
| 57 |
|
| 58 |
self.nAffected += len(self.batchCache) |
| 59 |
if self.notify: |
| 60 |
base.ui.notifyShipout(len(self.batchCache)) |
| 61 |
self.batchCache = [] |
| 62 |
|
| 63 |
def add(self, data): |
| 64 |
self._assertActive() |
| 65 |
if self.table.validateRows: |
| 66 |
try: |
| 67 |
self.table.tableDef.validateRow(data) |
| 68 |
except rscdef.IgnoreThisRow: |
| 69 |
return |
| 70 |
self.batchCache.append(data) |
| 71 |
if len(self.batchCache)>=self.batchSize: |
| 72 |
self.shipout() |
| 73 |
|
| 74 |
def flush(self): |
| 75 |
self._assertActive() |
| 76 |
self.shipout() |
| 77 |
|
| 78 |
def reset(self): |
| 79 |
self._assertActive() |
| 80 |
self.batchCache = [] |
| 81 |
|
| 82 |
def __enter__(self): |
| 83 |
self.cursor = self.table.connection.cursor() |
| 84 |
return table._Feeder.__enter__(self) |
| 85 |
|
| 86 |
def __exit__(self, *args): |
| 87 |
if not args or args[0] is None: # regular exit, ship out |
| 88 |
try: |
| 89 |
self.shipout() |
| 90 |
# The following sucks, but rowcount seems to be always 1 on insert operations. |
| 91 |
# However, we at least want a chance to catch update operations matching |
| 92 |
# nothing. So, if rowcount is 0, it's a sign something went wrong, and |
| 93 |
# we want to override our initial guess. |
| 94 |
if self.cursor.rowcount==0: |
| 95 |
self.nAffected = 0 |
| 96 |
self.cursor.close() |
| 97 |
except: |
| 98 |
del self.cursor |
| 99 |
table._Feeder.__exit__(self, *sys.exc_info()) |
| 100 |
raise |
| 101 |
if hasattr(self, "cursor"): |
| 102 |
del self.cursor |
| 103 |
table._Feeder.__exit__(self, *args) |
| 104 |
return False |
| 105 |
|
| 106 |
def getAffected(self): |
| 107 |
return self.nAffected |
| 108 |
|
| 109 |
|
| 110 |
class _RaisingFeeder(_Feeder): |
| 111 |
"""is a feeder that will bomb on any attempt to feed data to it. |
| 112 |
|
| 113 |
It is useful for tables that can't be written, specifically, views. |
| 114 |
""" |
| 115 |
def add(self, data): |
| 116 |
raise base.DataError("Attempt to feed to a read-only table") |
| 117 |
|
| 118 |
|
| 119 |
class MetaTableMixin(object): |
| 120 |
"""is a mixin providing methods updating the dc_tables. |
| 121 |
|
| 122 |
It requires a tableDef attribute on the parent, and the parent must |
| 123 |
mix in QuerierMixin. |
| 124 |
""" |
| 125 |
__metaRDId = "__system__/dc_tables" |
| 126 |
|
| 127 |
def _cleanFromSourceTable(self): |
| 128 |
"""removes information about self.tableDef from the tablemeta table. |
| 129 |
""" |
| 130 |
self.connection.execute( |
| 131 |
"DELETE FROM dc.tablemeta WHERE tableName=%(tableName)s", |
| 132 |
{"tableName": self.tableDef.getQName()}) |
| 133 |
|
| 134 |
def _addToSourceTable(self): |
| 135 |
"""adds information about self.tableDef to the tablemeta table. |
| 136 |
""" |
| 137 |
t = DBTable(base.caches.getRD( |
| 138 |
self.__metaRDId).getTableDefById("tablemeta"), |
| 139 |
connection=self.connection) |
| 140 |
t.addRow({"tableName": self.tableDef.getQName(), |
| 141 |
"sourceRD": self.tableDef.rd.sourceId, |
| 142 |
"adql": bool(self.tableDef.adql), |
| 143 |
"tableDesc": base.getMetaText(self.tableDef, "description", |
| 144 |
propagate=False), |
| 145 |
"resDesc": base.getMetaText(self.tableDef.rd, "description", |
| 146 |
propagate=False), |
| 147 |
"nrows": self.tableDef.nrows}) |
| 148 |
|
| 149 |
def addToMeta(self): |
| 150 |
self._addToSourceTable() |
| 151 |
|
| 152 |
def cleanFromMeta(self): |
| 153 |
self._cleanFromSourceTable() |
| 154 |
|
| 155 |
|
| 156 |
class DBMethodsMixin(sqlsupport.QuerierMixin): |
| 157 |
"""is a mixin for on-disk tables. |
| 158 |
|
| 159 |
The parent must have tableDef, tableName (from tabledef.getQName()), |
| 160 |
and connection attributes. |
| 161 |
""" |
| 162 |
|
| 163 |
scripts = None # set by data on import, defined by make |
| 164 |
|
| 165 |
def _definePrimaryKey(self): |
| 166 |
if self.tableDef.primary and not self.hasIndex(self.tableName, |
| 167 |
self.getPrimaryIndexName(self.tableDef.id)): |
| 168 |
if not self.tableDef.system: |
| 169 |
base.ui.notifyIndexCreation("Primary key on %s"%self.tableName) |
| 170 |
try: |
| 171 |
self.connection.execute("ALTER TABLE %s ADD PRIMARY KEY (%s)"%( |
| 172 |
self.tableName, ", ".join(self.tableDef.primary))) |
| 173 |
except sqlsupport.DBError as msg: |
| 174 |
raise base.ui.logOldExc( |
| 175 |
base.DBTableError("Primary key %s could not be added (%s)"%( |
| 176 |
self.tableDef.primary, repr(str(msg))), self.tableName, |
| 177 |
hint="The howDoI documentation text may contain help on" |
| 178 |
" how to find the offending elements.")) |
| 179 |
|
| 180 |
def _dropPrimaryKey(self): |
| 181 |
"""drops a primary key if it exists. |
| 182 |
|
| 183 |
*** Postgres specific *** |
| 184 |
""" |
| 185 |
constraintName = str(self.getPrimaryIndexName(self.tableDef.id)) |
| 186 |
if self.tableDef.primary and self.hasIndex( |
| 187 |
self.tableName, constraintName): |
| 188 |
self.connection.execute("ALTER TABLE %s DROP CONSTRAINT %s"%( |
| 189 |
self.tableName, constraintName)) |
| 190 |
|
| 191 |
def _addForeignKeys(self): |
| 192 |
"""adds foreign key constraints if necessary. |
| 193 |
""" |
| 194 |
for fk in self.tableDef.foreignKeys: |
| 195 |
if not self.tableDef.system: |
| 196 |
base.ui.notifyIndexCreation( |
| 197 |
self.tableDef.expand(fk.getDescription())) |
| 198 |
fk.create(self) |
| 199 |
|
| 200 |
def _dropForeignKeys(self): |
| 201 |
"""drops foreign key constraints if necessary. |
| 202 |
""" |
| 203 |
for fk in self.tableDef.foreignKeys: |
| 204 |
fk.delete(self) |
| 205 |
|
| 206 |
def dropIndices(self): |
| 207 |
if not self.exists(): |
| 208 |
return |
| 209 |
self._dropForeignKeys() |
| 210 |
# Don't drop the primary key for now -- foreign key relationships may |
| 211 |
# depend on it, and postgres doesn't seem to mind if we just create it later. |
| 212 |
# This is presumably still bad if someone changed the primary key. Let's |
| 213 |
# worry about it then. |
| 214 |
# self._dropPrimaryKey() |
| 215 |
for index in reversed(self.tableDef.indices): |
| 216 |
index.drop(self) |
| 217 |
return self |
| 218 |
|
| 219 |
def makeIndices(self): |
| 220 |
"""creates all indices on the table, including any definition of |
| 221 |
a primary key. |
| 222 |
""" |
| 223 |
self.connection.execute("SET maintenance_work_mem=%s000"% |
| 224 |
base.getConfig("db", "indexworkmem")) |
| 225 |
if self.suppressIndex or not self.exists(): |
| 226 |
return |
| 227 |
if self.tableDef.primary: |
| 228 |
self._definePrimaryKey() |
| 229 |
|
| 230 |
for index in self.tableDef.indices: |
| 231 |
index.create(self) |
| 232 |
|
| 233 |
self._addForeignKeys() |
| 234 |
return self |
| 235 |
|
| 236 |
def getDeleteQuery(self, matchCondition, pars={}): |
| 237 |
return "DELETE FROM %s WHERE %s"%( |
| 238 |
self.tableName, matchCondition), pars |
| 239 |
|
| 240 |
def deleteMatching(self, matchCondition, pars={}): |
| 241 |
"""deletes all rows matching matchCondition. |
| 242 |
|
| 243 |
For now, matchCondition a boolean SQL expression. All rows matching |
| 244 |
it will be deleted. |
| 245 |
""" |
| 246 |
self.connection.execute(*self.getDeleteQuery(matchCondition, pars)) |
| 247 |
|
| 248 |
def copyIn(self, inFile, binary=True): |
| 249 |
fmt = " WITH BINARY" if binary else "" |
| 250 |
cursor = self.connection.cursor() |
| 251 |
cursor.copy_expert("COPY %s FROM STDIN %s"%(self.tableName, fmt), inFile) |
| 252 |
cursor.close() |
| 253 |
return self |
| 254 |
|
| 255 |
def copyOut(self, outFile, binary=True): |
| 256 |
fmt = " WITH BINARY" if binary else "" |
| 257 |
cursor = self.connection.cursor() |
| 258 |
cursor.copy_expert("COPY %s TO STDOUT %s"%(self.tableName, fmt), outFile) |
| 259 |
cursor.close() |
| 260 |
return self |
| 261 |
|
| 262 |
def ensureSchema(self): |
| 263 |
"""creates self's schema if necessary. |
| 264 |
""" |
| 265 |
if self.tableDef.temporary: # these never are in a schema |
| 266 |
return |
| 267 |
schemaName = self.tableDef.rd.schema |
| 268 |
if not self.schemaExists(schemaName): |
| 269 |
self.connection.execute("CREATE SCHEMA %(schemaName)s"%locals()) |
| 270 |
self.setSchemaPrivileges(self.tableDef.rd) |
| 271 |
return self |
| 272 |
|
| 273 |
def ensureOnDiskMatches(self, tapSchemaColumns=None): |
| 274 |
"""raises a DataError if the on-disk structure of a table doesn't |
| 275 |
match DaCHS' idea of it. |
| 276 |
|
| 277 |
If the table doesn't exist on disk, this will raise a NotFoundError. |
| 278 |
|
| 279 |
tapSchemaColumns, if given must be a mapping from column names |
| 280 |
to dicts giving unit, ucd, datatype, arraysize and xtype for |
| 281 |
the column. We will then also ensure that that metadata is |
| 282 |
up to date. |
| 283 |
""" |
| 284 |
dbCols = self.getColumnsFromDB(self.tableDef.getQName()) |
| 285 |
mismatches = [] |
| 286 |
if len(self.tableDef.columns)<len(dbCols): |
| 287 |
mismatches.append("extra columns in DB (%s)"%", ".join( |
| 288 |
name for name, _ in dbCols[len(self.tableDef.columns):])) |
| 289 |
|
| 290 |
for index, col in enumerate(self.tableDef): |
| 291 |
try: |
| 292 |
name, type = dbCols[index] |
| 293 |
except IndexError: |
| 294 |
mismatches.append(f"column {col.name}: No matches in DB") |
| 295 |
break |
| 296 |
|
| 297 |
if isinstance(col.name, utils.QuotedName): |
| 298 |
if col.name.name!=name: |
| 299 |
mismatches.append("mismatching delimited name of %s (DB: %s)"%( |
| 300 |
col.name, name)) |
| 301 |
elif col.name.lower()!=name: |
| 302 |
mismatches.append("mismatching name of %s (DB: %s)"%(col.name, name)) |
| 303 |
continue |
| 304 |
try: |
| 305 |
base.sqltypeToPgValidator(col.type)(type) |
| 306 |
except TypeError as ex: |
| 307 |
mismatches.append("type mismatch in column %s (%s)"%( |
| 308 |
col.name, utils.safe_str(ex))) |
| 309 |
|
| 310 |
if tapSchemaColumns: |
| 311 |
mismatches.extend( |
| 312 |
col.validateAgainstTAPSchema( |
| 313 |
tapSchemaColumns.get(col.getTAPName()))) |
| 314 |
|
| 315 |
if mismatches: |
| 316 |
raise base.DataError("Table %s: %s"%( |
| 317 |
self.tableDef.getQName(), "; ".join(mismatches))) |
| 318 |
|
| 319 |
|
| 320 |
class DBTable(DBMethodsMixin, table.BaseTable, MetaTableMixin): |
| 321 |
"""An interface to a table in the database. |
| 322 |
|
| 323 |
These are usually created using ``api.TableForDef(tableDef)`` with a |
| 324 |
table definition obtained, e.g., from an RD, saying ``onDisk=True``. |
| 325 |
|
| 326 |
When constructing a DBTable, it will be created if necessary (unless |
| 327 |
``create=False`` is passed), but indices or primary keys keys will only be |
| 328 |
created on a call to ``importFinished``. |
| 329 |
|
| 330 |
The constructor does not check if the schema of the table on disk matches |
| 331 |
the tableDef. If the two diverge, all kinds of failures are conceivable; |
| 332 |
use ``dachs val -c`` to make sure on-disk structure match the RDs. |
| 333 |
|
| 334 |
You can pass a ``nometa`` boolean kw argument to suppress entering the table |
| 335 |
into the ``dc_tables`` table. |
| 336 |
|
| 337 |
You can pass an exclusive boolean kw argument; if you do, the |
| 338 |
``iterQuery`` (and possibly similar methods in the future) method |
| 339 |
will block concurrent writes to the selected rows ("FOR UPDATE") |
| 340 |
as long as the transaction is active. |
| 341 |
|
| 342 |
DbTables will run preCreation, preIndex, postCreation, and beforeDrop |
| 343 |
scripts, both from the table definition and the make they are being |
| 344 |
created from. No scripts except beforeDrop are run when an existing table is |
| 345 |
operated on from an updating dd. |
| 346 |
|
| 347 |
The main attributes (with API guarantees) include: |
| 348 |
|
| 349 |
* tableDef -- the defining tableDef |
| 350 |
* getFeeder() -- returns a function you can call with rowdicts to |
| 351 |
insert them into the table. |
| 352 |
* importFinished(nImported) -- must be called after you've fed all rows when |
| 353 |
importing data; pass the number of rows fed in. |
| 354 |
* drop() -- drops the table in the database |
| 355 |
* recreate() -- drops the table and generates a new empty one. |
| 356 |
* getTableForQuery(...) -- returns a Table instance built from a query |
| 357 |
over this table (you probably to use ``conn.query*`` and |
| 358 |
``td.getSimpleQuery`` instead). |
| 359 |
""" |
| 360 |
def __init__(self, tableDef, **kwargs): |
| 361 |
self.connection = kwargs.pop("connection", None) |
| 362 |
if self.connection is None: |
| 363 |
raise base.ReportableError("DBTable built without connection.", |
| 364 |
hint="In pre-1.0 DaCHS, database tables could automatically" |
| 365 |
" open and manage connections. This turned out to be much" |
| 366 |
" more trouble than it was worth. See develNotes for how" |
| 367 |
" to do things today.") |
| 368 |
|
| 369 |
self.suppressIndex = kwargs.pop("suppressIndex", False) |
| 370 |
self.tableUpdates = kwargs.pop("tableUpdates", False) |
| 371 |
self.exclusive = kwargs.pop("exclusive", False) |
| 372 |
self.updating = kwargs.pop("updating", False) |
| 373 |
self.commitAfterMeta = kwargs.pop("commitAfterMeta", False) |
| 374 |
table.BaseTable.__init__(self, tableDef, **kwargs) |
| 375 |
|
| 376 |
if self.tableDef.rd is None and not self.tableDef.temporary: |
| 377 |
raise base.ReportableError("TableDefs without resource descriptor" |
| 378 |
" cannot be used to access database tables") |
| 379 |
self.tableName = self.tableDef.getQName() |
| 380 |
self.nometa = (kwargs.get("nometa", False) |
| 381 |
or self.tableDef.temporary or tableDef.rd.schema=="dc") |
| 382 |
|
| 383 |
self.newlyCreated = False |
| 384 |
if kwargs.get("create", False): |
| 385 |
self.createIfNecessary() |
| 386 |
|
| 387 |
if self.tableUpdates: |
| 388 |
self.addCommand = "UPDATE %s SET %s WHERE %s"%( |
| 389 |
self.tableName, |
| 390 |
", ".join("%s=%%(%s)s"%(f.name, f.key) |
| 391 |
for f in self.tableDef), |
| 392 |
" AND ".join("%s=%%(%s)s"%(n, n) for n in self.tableDef.primary)) |
| 393 |
else: |
| 394 |
self.addCommand = ("INSERT INTO %s (%s) VALUES (%s)"%( |
| 395 |
self.tableName, |
| 396 |
", ".join([str(c.name) for c in self.tableDef.columns]), |
| 397 |
", ".join(["%%(%s)s"%c.key for c in self.tableDef.columns]))) |
| 398 |
|
| 399 |
if "rows" in kwargs: |
| 400 |
self.feedRows(kwargs["rows"]) |
| 401 |
|
| 402 |
def __iter__(self): |
| 403 |
# Do we want named cursors by default here? |
| 404 |
cursor = self.connection.cursor() |
| 405 |
cursor.execute("SELECT * FROM %s"%self.tableName) |
| 406 |
for row in cursor: |
| 407 |
yield self.tableDef.makeRowFromTuple(row) |
| 408 |
cursor.close() |
| 409 |
|
| 410 |
def __len__(self): |
| 411 |
return list(self.connection.query("select count(*) from %s"% |
| 412 |
self.tableDef.getQName()))[0][0] |
| 413 |
|
| 414 |
def exists(self): |
| 415 |
return self.getTableType(self.tableDef.getQName()) is not None |
| 416 |
|
| 417 |
def getFeeder(self, **kwargs): |
| 418 |
if "notify" not in kwargs: |
| 419 |
kwargs["notify"] = not self.tableDef.system or not self.tableDef.onDisk |
| 420 |
return _Feeder(self, self.addCommand, **kwargs) |
| 421 |
|
| 422 |
def importFinished(self, nAffected): |
| 423 |
if self.newlyCreated: |
| 424 |
self.runScripts("preIndex") |
| 425 |
self.makeIndices() |
| 426 |
self.runScripts("postCreation") |
| 427 |
else: |
| 428 |
base.ui.notifyDBTableModified(self.tableName) |
| 429 |
|
| 430 |
if nAffected>100: |
| 431 |
# don't run analyze when there's just a few records changed, |
| 432 |
# as when uploading to products. |
| 433 |
self.connection.execute("ANALYZE %s"%self.tableName) |
| 434 |
return self |
| 435 |
|
| 436 |
def importFailed(self, *excInfo): |
| 437 |
# rollback is handled by the feeder. |
| 438 |
return False |
| 439 |
|
| 440 |
def feedRows(self, rows): |
| 441 |
"""Feeds a sequence of rows to the table. |
| 442 |
|
| 443 |
The method returns the number of rows affected. Exceptions are |
| 444 |
handed through upstream, but the connection is rolled back. |
| 445 |
""" |
| 446 |
with self.getFeeder() as feeder: |
| 447 |
for r in rows: |
| 448 |
feeder.add(r) |
| 449 |
return feeder.nAffected |
| 450 |
|
| 451 |
def addRow(self, row): |
| 452 |
"""adds a row to the table. |
| 453 |
|
| 454 |
Use this only to add one or two rows, otherwise go for getFeeder. |
| 455 |
""" |
| 456 |
try: |
| 457 |
self.connection.execute(self.addCommand, row) |
| 458 |
except sqlsupport.IntegrityError: |
| 459 |
raise base.ui.logOldExc( |
| 460 |
base.ValidationError("Row %s cannot be added since it clashes" |
| 461 |
" with an existing record on the primary key"%row, row=row, |
| 462 |
colName="unknown")) |
| 463 |
|
| 464 |
def getRow(self, *key): |
| 465 |
"""returns the row with the primary key key from the table. |
| 466 |
|
| 467 |
This will raise a DataError on tables without primaries. |
| 468 |
""" |
| 469 |
if not self.tableDef.primary: |
| 470 |
raise base.DataError("Table %s has no primary key and thus does" |
| 471 |
" not support getRow"%self.tableName) |
| 472 |
res = list(self.iterQuery(self.tableDef, |
| 473 |
" AND ".join("%s=%%(%s)s"%(n,n) for n in self.tableDef.primary), |
| 474 |
pars=dict(list(zip(self.tableDef.primary, key))))) |
| 475 |
if not res: |
| 476 |
raise KeyError(key) |
| 477 |
return res[0] |
| 478 |
|
| 479 |
def createUniquenessRules(self): |
| 480 |
# these two drop rules and triggers created by old DaCHS |
| 481 |
# versions. I'd say they can be removed ~ 2025, when all |
| 482 |
# tables with such triggers/rules have beeen removed. |
| 483 |
self.connection.execute('DROP TRIGGER IF EXISTS "dropOld_%s"' |
| 484 |
' ON %s'%(self.tableName, self.tableName)) |
| 485 |
self.connection.execute('DROP RULE IF EXISTS updatePolicy' |
| 486 |
' ON %s'%(self.tableName)) |
| 487 |
|
| 488 |
# this is the new trigger used by all policies |
| 489 |
self.connection.execute('DROP TRIGGER IF EXISTS "dupe_policy_%s"' |
| 490 |
' ON %s'%(self.tableName, self.tableName)) |
| 491 |
|
| 492 |
if not self.tableDef.dupePolicy: |
| 493 |
return |
| 494 |
|
| 495 |
def getMatchCondition(): |
| 496 |
return " AND ".join("%s=new.%s"%(n,n) for n in self.tableDef.primary) |
| 497 |
|
| 498 |
# uniqueness checking becomes really slow if primary key definition |
| 499 |
# is delayed until index creation (as usual), so let's do it now. |
| 500 |
self._definePrimaryKey() |
| 501 |
|
| 502 |
args = { |
| 503 |
"table": self.tableName, |
| 504 |
"matchCond": getMatchCondition(), |
| 505 |
"colNames": ",".join(str(c.name) for c in self.tableDef), |
| 506 |
"mungedColNames": ",".join( |
| 507 |
"munged_vals."+str(c.name) for c in self.tableDef)} |
| 508 |
|
| 509 |
if self.tableDef.dupePolicy=="drop": |
| 510 |
self.connection.execute(""" |
| 511 |
CREATE OR REPLACE FUNCTION |
| 512 |
"handle_dupe_%(table)s"() |
| 513 |
RETURNS trigger AS $body$ |
| 514 |
BEGIN |
| 515 |
IF (EXISTS(SELECT 1 FROM %(table)s WHERE %(matchCond)s)) THEN |
| 516 |
RETURN NULL; |
| 517 |
END IF; |
| 518 |
RETURN NEW; |
| 519 |
END |
| 520 |
$body$ LANGUAGE plpgsql"""%args) |
| 521 |
|
| 522 |
elif self.tableDef.dupePolicy=="check": |
| 523 |
# This one is tricky: if the inserted column is *different*, |
| 524 |
# the rule does not fire and we get a pkey violation. |
| 525 |
# Furthermore, special NULL handling is required -- we |
| 526 |
# do not check columns that have NULLs in new or old. |
| 527 |
self.connection.execute(""" |
| 528 |
CREATE OR REPLACE FUNCTION |
| 529 |
"handle_dupe_%(table)s"() |
| 530 |
RETURNS trigger AS $body$ |
| 531 |
BEGIN |
| 532 |
SELECT * INTO OLD FROM %(table)s WHERE %(matchCond)s; |
| 533 |
IF NOT FOUND THEN |
| 534 |
RETURN NEW; |
| 535 |
ELSEIF (OLD IS NOT DISTINCT FROM NEW) THEN |
| 536 |
RETURN NULL; |
| 537 |
ELSE |
| 538 |
RAISE 'Overwrite attempt with different tuple with check policy %%%% %%%%.', OLD, NEW; |
| 539 |
END IF; |
| 540 |
RETURN NEW; |
| 541 |
END |
| 542 |
$body$ LANGUAGE plpgsql"""%args) |
| 543 |
|
| 544 |
elif self.tableDef.dupePolicy=="dropOld": |
| 545 |
self.connection.execute(""" |
| 546 |
CREATE OR REPLACE FUNCTION "handle_dupe_%(table)s"() |
| 547 |
RETURNS trigger AS $body$ |
| 548 |
BEGIN |
| 549 |
IF (EXISTS(SELECT 1 FROM %(table)s WHERE %(matchCond)s)) THEN |
| 550 |
DELETE FROM %(table)s WHERE %(matchCond)s; |
| 551 |
END IF; |
| 552 |
RETURN NEW; |
| 553 |
END $body$ LANGUAGE plpgsql"""%args) |
| 554 |
|
| 555 |
elif self.tableDef.dupePolicy=="overwrite": |
| 556 |
self.connection.execute(""" |
| 557 |
CREATE OR REPLACE FUNCTION "handle_dupe_%(table)s"() |
| 558 |
RETURNS trigger AS $body$ |
| 559 |
DECLARE |
| 560 |
munged_vals RECORD; |
| 561 |
BEGIN |
| 562 |
munged_vals = NEW; |
| 563 |
IF (EXISTS(SELECT 1 FROM %(table)s WHERE %(matchCond)s)) THEN |
| 564 |
UPDATE %(table)s SET (%(colNames)s)=(%(mungedColNames)s) |
| 565 |
WHERE %(matchCond)s; |
| 566 |
RETURN NULL; |
| 567 |
END IF; |
| 568 |
RETURN NEW; |
| 569 |
END $body$ LANGUAGE plpgsql"""%args) |
| 570 |
|
| 571 |
else: |
| 572 |
raise base.DataError("Invalid dupePolicy: %s"%self.tableDef.dupePolicy) |
| 573 |
|
| 574 |
self.connection.execute( |
| 575 |
'CREATE TRIGGER "dupe_policy_%(table)s" BEFORE INSERT' |
| 576 |
' ON %(table)s FOR EACH ROW EXECUTE' |
| 577 |
' PROCEDURE "handle_dupe_%(table)s"()'%args) |
| 578 |
|
| 579 |
def setStatisticsTargets(self): |
| 580 |
for col in self.tableDef: |
| 581 |
if col.hasProperty("statisticsTarget"): |
| 582 |
target = int(col.getProperty("statisticsTarget")) |
| 583 |
self.connection.execute("ALTER TABLE %s ALTER COLUMN %s" |
| 584 |
" SET STATISTICS %d"%(self.tableName, col.name, target)) |
| 585 |
|
| 586 |
def create(self): |
| 587 |
base.ui.notifyDebug("Create DB Table %s"%self.tableName) |
| 588 |
self.ensureSchema() |
| 589 |
self.newlyCreated = True |
| 590 |
self.runScripts("preCreation") |
| 591 |
self.connection.execute(self.tableDef.getDDL()) |
| 592 |
return self.updateMeta() |
| 593 |
|
| 594 |
def updateMeta(self): |
| 595 |
if self.tableDef.temporary: |
| 596 |
return |
| 597 |
self.setTablePrivileges(self.tableDef) |
| 598 |
self.setSchemaPrivileges(self.tableDef.rd) |
| 599 |
self.createUniquenessRules() |
| 600 |
self.setStatisticsTargets() |
| 601 |
|
| 602 |
if not self.nometa: |
| 603 |
self.addToMeta() |
| 604 |
self.runScripts("afterMeta") |
| 605 |
if self.commitAfterMeta: |
| 606 |
self.connection.commit() |
| 607 |
return self |
| 608 |
|
| 609 |
def createIfNecessary(self): |
| 610 |
if not self.exists(): |
| 611 |
self.create() |
| 612 |
return self |
| 613 |
|
| 614 |
def _iterDerivedViews(self): |
| 615 |
"""yields view that contain the current table. |
| 616 |
|
| 617 |
This is in particular used when dropping the table (rather than rely on |
| 618 |
cascade) in order to give view's dropping scripts a chance to run. |
| 619 |
""" |
| 620 |
depNames = set(r[0] for r in self.connection.query(""" |
| 621 |
SELECT DISTINCT v.oid::regclass as table_name |
| 622 |
FROM pg_depend AS d |
| 623 |
JOIN pg_rewrite AS r ON r.oid = d.objid |
| 624 |
JOIN pg_class AS v ON v.oid = r.ev_class |
| 625 |
WHERE v.relkind = 'v' |
| 626 |
AND d.classid = 'pg_rewrite'::regclass |
| 627 |
AND d.refclassid = 'pg_class'::regclass |
| 628 |
AND d.deptype = 'n' |
| 629 |
AND refobjid=%(qname)s::regclass""", |
| 630 |
{"qname": self.tableDef.getQName()})) |
| 631 |
|
| 632 |
if not depNames: |
| 633 |
return |
| 634 |
|
| 635 |
myId = self.tableDef.getFullId() |
| 636 |
for depId in [r[1]+"#"+r[0].split(".")[-1] |
| 637 |
for r in self.connection.query("""SELECT tablename, sourcerd |
| 638 |
FROM dc.tablemeta |
| 639 |
WHERE tablename IN %(depNames)s""", |
| 640 |
locals())]: |
| 641 |
if depId==myId: |
| 642 |
# can't be bothered to figure out why a view apparently |
| 643 |
# depends on itself by the logic above |
| 644 |
continue |
| 645 |
|
| 646 |
try: |
| 647 |
yield base.resolveCrossId(depId) |
| 648 |
except base.NotFoundError: |
| 649 |
base.ui.notifyError("Would have liked to drop %s before" |
| 650 |
" dropping %s, but found its definition gone."%( |
| 651 |
depId, self.tableDef.getQName())) |
| 652 |
|
| 653 |
def drop(self, seenIds=()): |
| 654 |
"""drops the table. |
| 655 |
|
| 656 |
This will recurse into dependent objects. |
| 657 |
""" |
| 658 |
self.runScripts("beforeDrop") |
| 659 |
if self.exists(): |
| 660 |
if seenIds==(): |
| 661 |
seenIds = set() |
| 662 |
|
| 663 |
# if there are any dependent views (known), drop them in a controlled |
| 664 |
# fashion becore CASCADE hits |
| 665 |
for viewDef in self._iterDerivedViews(): |
| 666 |
if id(viewDef) in seenIds: |
| 667 |
continue |
| 668 |
seenIds.add(id(viewDef)) |
| 669 |
|
| 670 |
View( |
| 671 |
viewDef, |
| 672 |
connection=self.connection, |
| 673 |
create=False).drop(seenIds) |
| 674 |
|
| 675 |
self.dropTable(self.tableDef.getQName(), cascade=True) |
| 676 |
if not self.nometa: |
| 677 |
self.cleanFromMeta() |
| 678 |
|
| 679 |
return self |
| 680 |
|
| 681 |
def recreate(self): |
| 682 |
self.drop() |
| 683 |
self.create() |
| 684 |
return self |
| 685 |
|
| 686 |
def query(self, query, data={}): |
| 687 |
"""runs query within this table's connection. |
| 688 |
|
| 689 |
query is macro-expanded within the table definition (i.e., you can, |
| 690 |
e.g., write \\qName to obtain the table's qualified name). |
| 691 |
|
| 692 |
Don't use this in new code; use t.connection.query or execute |
| 693 |
as required. |
| 694 |
""" |
| 695 |
return DBMethodsMixin.query(self, self.expand(query), data) |
| 696 |
|
| 697 |
def getSelectClause(self, resultTableDef): |
| 698 |
"""returns the select clause to come up with resultTableDef. |
| 699 |
""" |
| 700 |
parts = [] |
| 701 |
for of in resultTableDef: |
| 702 |
select = getattr(of, "select", None) |
| 703 |
if select: |
| 704 |
parts.append("%s AS %s"%(select, of.name)) |
| 705 |
else: |
| 706 |
parts.append(of.name) |
| 707 |
return ", ".join(parts) |
| 708 |
|
| 709 |
def getQuery(self, resultTableDef, fragment, pars=None, |
| 710 |
distinct=False, limits=None, groupBy=None, samplePercent=None): |
| 711 |
"""returns a result table definition, query string and a parameters |
| 712 |
dictionary for a query against this table. |
| 713 |
|
| 714 |
See getTableForQuery for the meaning of the arguments. |
| 715 |
""" |
| 716 |
if pars is None: |
| 717 |
pars = {} |
| 718 |
|
| 719 |
if not isinstance(resultTableDef, rscdef.TableDef): |
| 720 |
resultTableDef = base.makeStruct(rscdef.TableDef, |
| 721 |
id="iterQuery", columns=resultTableDef) |
| 722 |
|
| 723 |
query = ["SELECT "] |
| 724 |
if distinct: |
| 725 |
query.append("DISTINCT ") |
| 726 |
query.append(self.getSelectClause(resultTableDef)+" ") |
| 727 |
query.append("FROM %s "%self.tableName) |
| 728 |
if samplePercent: |
| 729 |
query.append("TABLESAMPLE SYSTEM (%f)"%samplePercent) |
| 730 |
|
| 731 |
if fragment and fragment.strip(): |
| 732 |
query.append("WHERE %s "%fragment) |
| 733 |
if groupBy: |
| 734 |
query.append("GROUP BY %s "%groupBy) |
| 735 |
if limits: |
| 736 |
query.append(limits[0]+" ") |
| 737 |
pars.update(limits[1]) |
| 738 |
if self.exclusive: |
| 739 |
query.append("FOR UPDATE ") |
| 740 |
return resultTableDef, "".join(query), pars |
| 741 |
|
| 742 |
def iterQuery(self, resultTableDef=None, fragment="", pars=None, |
| 743 |
distinct=False, limits=None, groupBy=None): |
| 744 |
"""like getTableForQuery, except that an iterator over the |
| 745 |
result rows is returned. |
| 746 |
|
| 747 |
(there is no advantage in using this as we will pull the entire |
| 748 |
thing in memory anyway; use qtables if you need streaming). |
| 749 |
""" |
| 750 |
for row in self.getTableForQuery(resultTableDef, fragment, |
| 751 |
pars, distinct, limits, groupBy).rows: |
| 752 |
yield row |
| 753 |
|
| 754 |
def getTableForQuery(self, resultTableDef=None, fragment="", pars=None, |
| 755 |
distinct=False, limits=None, groupBy=None, samplePercent=None): |
| 756 |
"""returns a Table instance for a query on this table. |
| 757 |
|
| 758 |
resultTableDef is a TableDef with svc.OutputField columns |
| 759 |
(rscdef.Column instances will do), or possibly just a list |
| 760 |
of Columns. Fragment is empty or an SQL |
| 761 |
where-clause with |
| 762 |
dictionary placeholders, pars is the dictionary filling |
| 763 |
fragment, distinct, if True, adds a distinct clause, |
| 764 |
and limits, if given, is a pair of an SQL string to be |
| 765 |
appended to the SELECT clause and parameters filling it. |
| 766 |
queryMeta.asSQL returns what you need here. |
| 767 |
|
| 768 |
pars may be mutated in the process. |
| 769 |
""" |
| 770 |
if resultTableDef is None: |
| 771 |
resultTableDef = self.tableDef.copy(None) |
| 772 |
resultTableDef, query, pars = self.getQuery( |
| 773 |
resultTableDef, |
| 774 |
fragment, |
| 775 |
pars=pars, |
| 776 |
distinct=distinct, |
| 777 |
limits=limits, |
| 778 |
groupBy=groupBy, |
| 779 |
samplePercent=samplePercent) |
| 780 |
return table.InMemoryTable(resultTableDef, |
| 781 |
rows=[resultTableDef.makeRowFromTuple(tupRow) |
| 782 |
for tupRow in self.connection.query(query, pars)]) |
| 783 |
|
| 784 |
def runScripts(self, phase, **kwargs): |
| 785 |
"""runs scripts from both the tableDef and the make. |
| 786 |
|
| 787 |
The reason there's not a single place is mainly historical; on the |
| 788 |
other hand, one day postCreation scripts only run when a table is |
| 789 |
created in a special way might come in handy, so I'll not take away |
| 790 |
table scripts from makes. |
| 791 |
""" |
| 792 |
if self.updating: |
| 793 |
if (not self.newlyCreated |
| 794 |
and phase in {"preImport", "preIndex", "postCreation"}): |
| 795 |
return |
| 796 |
|
| 797 |
self.tableDef.getRunner()(self, phase, **kwargs) |
| 798 |
if self.makeRunning: |
| 799 |
self.makeRunning.getRunner()(self, phase, **kwargs) |
| 800 |
|
| 801 |
|
| 802 |
class View(DBTable): |
| 803 |
"""is a view, i.e., a table in the database you can't add to. |
| 804 |
|
| 805 |
Strictly, I should derive both View and DBTable from a common |
| 806 |
base, but that's currently not worth the effort. |
| 807 |
|
| 808 |
Technically, Views are DBTables with a non-None viewStatement |
| 809 |
(this is what TableForDef checks for when deciding whether to |
| 810 |
construct a DBTable or a View). You can get a feeder for them, |
| 811 |
but trying to actually feed anything will raise a DataError. |
| 812 |
|
| 813 |
On import, views only run postCreation scripts; we assume everything |
| 814 |
else (preIndex, postIndex, preImport, newSource, etc) has run |
| 815 |
in the contributing tables. Materialised views *will* create indices, |
| 816 |
however. |
| 817 |
""" |
| 818 |
|
| 819 |
def __init__(self, *args, **kwargs): |
| 820 |
DBTable.__init__(self, *args, **kwargs) |
| 821 |
del self.addCommand |
| 822 |
|
| 823 |
def addRow(self, row): |
| 824 |
raise base.DataError("You cannot add data to views") |
| 825 |
|
| 826 |
feedRows = addRow |
| 827 |
|
| 828 |
def setStatisticsTargets(self): |
| 829 |
# no statistics on views |
| 830 |
# (we don't even warn since we've probably got this from the table |
| 831 |
# where it's going to happen) |
| 832 |
pass |
| 833 |
|
| 834 |
def getFeeder(self, **kwargs): |
| 835 |
# all kwargs ignored since the feeder will raise an exception on any |
| 836 |
# attempts to feed anyway. |
| 837 |
return _RaisingFeeder(self, None) |
| 838 |
|
| 839 |
def create(self): |
| 840 |
base.ui.notifyDebug("Create DB View %s"%self.tableName) |
| 841 |
self.newlyCreated = True |
| 842 |
self.ensureSchema() |
| 843 |
try: |
| 844 |
self.connection.execute( |
| 845 |
self.tableDef.expand(self.tableDef.viewStatement)) |
| 846 |
return self.updateMeta() |
| 847 |
except base.DBError as msg: |
| 848 |
raise base.ReportableError("View statement of table at %s bad." |
| 849 |
" Postgres error message: %s"%( |
| 850 |
self.tableDef.getSourcePosition(), |
| 851 |
msg)) |
| 852 |
|
| 853 |
def makeIndices(self): |
| 854 |
if self.getTableType(self.tableDef.getQName()) in [ |
| 855 |
"MATERIALIZED VIEW", "BASE TABLE"]: |
| 856 |
super().makeIndices() |
| 857 |
|
| 858 |
def importFinished(self, nImported): |
| 859 |
self.makeIndices() |
| 860 |
self.runScripts("postCreation") |
| 861 |
return self |