| 1 |
""" |
| 2 |
Parsing and translating VOTables to internal data structures. |
| 3 |
|
| 4 |
This is glue code to the more generic votable library. In general, you |
| 5 |
should access this module through formats.votable. |
| 6 |
""" |
| 7 |
|
| 8 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 9 |
#c |
| 10 |
#c This program is free software, covered by the GNU GPL. See the |
| 11 |
#c COPYING file in the source distribution. |
| 12 |
|
| 13 |
|
| 14 |
import gzip |
| 15 |
|
| 16 |
from gavo import base |
| 17 |
from gavo import rsc |
| 18 |
from gavo import rscdef |
| 19 |
from gavo import utils |
| 20 |
from gavo import votable |
| 21 |
from gavo.base import valuemappers |
| 22 |
from gavo.grammars import votablegrammar |
| 23 |
from gavo.votable import V |
| 24 |
from gavo.votable import modelgroups |
| 25 |
|
| 26 |
MS = base.makeStruct |
| 27 |
|
| 28 |
class QuotedNameMaker(object): |
| 29 |
"""A name maker for makeTableDefForVOTable implementing TAP's requirements. |
| 30 |
""" |
| 31 |
def __init__(self): |
| 32 |
self.index, self.seenNames = 0, set() |
| 33 |
|
| 34 |
def makeName(self, field): |
| 35 |
self.index += 1 |
| 36 |
res = getattr(field, "name", None) |
| 37 |
if res is None: |
| 38 |
raise base.ValidationError("Field without name in upload.", |
| 39 |
"UPLOAD") |
| 40 |
if res in self.seenNames: |
| 41 |
raise base.ValidationError("Duplicate column name illegal in" |
| 42 |
" uploaded tables (%s)"%res, "UPLOAD") |
| 43 |
self.seenNames.add(res) |
| 44 |
return utils.QuotedName(res) |
| 45 |
|
| 46 |
|
| 47 |
_PG_RESERVED_COLUMN_NAMES = set([ |
| 48 |
"oid", "tableoid", "xmin", "cmin", "xmax", "cmax", "ctid"]) |
| 49 |
class _ChangedName(str): |
| 50 |
"""a sentinel class to tell upstream that a name has been |
| 51 |
changed in a way that must be reflected in a query. |
| 52 |
""" |
| 53 |
|
| 54 |
|
| 55 |
class AutoQuotedNameMaker(object): |
| 56 |
"""A name maker for makeTableDefForVOTable quoting names as necessary. |
| 57 |
|
| 58 |
This is for PostgreSQL; it will also avoid PG's reserved column names (oid |
| 59 |
and friends); hence, this is what you should be using to put VOTables |
| 60 |
into postgres tables. |
| 61 |
|
| 62 |
This will break on duplicate names right now. I expect I'll change |
| 63 |
that behaviour to just renaming away name clashes at some point. |
| 64 |
""" |
| 65 |
def __init__(self, forRowmaker=False): |
| 66 |
self.seenNames = set() |
| 67 |
|
| 68 |
def makeName(self, field): |
| 69 |
name = getattr(field, "name", None) |
| 70 |
if name is None: |
| 71 |
raise base.ValidationError("Field without name in upload.", |
| 72 |
"UPLOAD") |
| 73 |
|
| 74 |
if valuemappers.needsQuoting(name): |
| 75 |
if name in self.seenNames: |
| 76 |
raise base.ValidationError("Duplicate column name illegal in" |
| 77 |
" uploaded tables (%s)"%name, "UPLOAD") |
| 78 |
self.seenNames.add(name) |
| 79 |
return utils.QuotedName(name) |
| 80 |
|
| 81 |
elif name.lower() in _PG_RESERVED_COLUMN_NAMES: |
| 82 |
name = name.lower()+"_" |
| 83 |
while name in self.seenNames: |
| 84 |
name = name+"_" |
| 85 |
self.seenNames.add(name) |
| 86 |
return _ChangedName(name) |
| 87 |
|
| 88 |
else: |
| 89 |
if name.lower() in self.seenNames: |
| 90 |
raise base.ValidationError("Duplicate column name illegal in" |
| 91 |
" uploaded tables (%s)"%name, "UPLOAD") |
| 92 |
self.seenNames.add(name.lower()) |
| 93 |
return name |
| 94 |
|
| 95 |
|
| 96 |
def _defuseUploadedText(s): |
| 97 |
"""removes stuff from s that our machinery might not like. |
| 98 |
|
| 99 |
For now, we just throw out everything that could cause a macro |
| 100 |
expansion. |
| 101 |
""" |
| 102 |
if isinstance(s, str): |
| 103 |
return s.replace('\\', "_") |
| 104 |
return s |
| 105 |
|
| 106 |
|
| 107 |
def _getValuesFromField(votField): |
| 108 |
"""returns None or an rscdef.Values instance for whatever is given |
| 109 |
in votField. |
| 110 |
""" |
| 111 |
valArgs = {} |
| 112 |
for valSpec in votField.iterChildrenOfType(V.VALUES): |
| 113 |
|
| 114 |
if valSpec.null is not None: |
| 115 |
valArgs["nullLiteral"] = _defuseUploadedText(valSpec.null) |
| 116 |
|
| 117 |
for minSpec in valSpec.iterChildrenOfType(V.MIN): |
| 118 |
valArgs["min"] = _defuseUploadedText(minSpec.value) |
| 119 |
|
| 120 |
for maxSpec in valSpec.iterChildrenOfType(V.MAX): |
| 121 |
valArgs["max"] = _defuseUploadedText(maxSpec.value) |
| 122 |
|
| 123 |
options = [] |
| 124 |
for optSpec in valSpec.iterChildrenOfType(V.OPTION): |
| 125 |
# We don't support nested options in rscdef. |
| 126 |
consArgs = {"content_": _defuseUploadedText(optSpec.value)} |
| 127 |
if optSpec.name: |
| 128 |
consArgs["title"] = _defuseUploadedText(optSpec.name) |
| 129 |
options.append(base.makeStruct(rscdef.Option, **consArgs)) |
| 130 |
if options: |
| 131 |
valArgs["options"] = options |
| 132 |
if valArgs: |
| 133 |
return base.makeStruct(rscdef.Values, **valArgs) |
| 134 |
|
| 135 |
|
| 136 |
def _getColArgs(votInstance, name): |
| 137 |
"""returns constructor arguments for an RD column or param from |
| 138 |
a VOTable FIELD or PARAM. |
| 139 |
""" |
| 140 |
kwargs = {"name": name, |
| 141 |
"tablehead": name.capitalize(), |
| 142 |
"id": getattr(votInstance, "ID", None), |
| 143 |
"type": base.voTableToSQLType( |
| 144 |
votInstance.datatype, votInstance.arraysize, votInstance.xtype)} |
| 145 |
|
| 146 |
for attName in ["ucd", "unit", "xtype"]: |
| 147 |
if getattr(votInstance, attName, None) is not None: |
| 148 |
kwargs[attName] = getattr(votInstance, attName) |
| 149 |
|
| 150 |
if getattr(votInstance, "value", None) is not None: |
| 151 |
kwargs["content_"] = votInstance.value |
| 152 |
values = _getValuesFromField(votInstance) |
| 153 |
if values: |
| 154 |
kwargs["values"] = values |
| 155 |
|
| 156 |
for desc in votInstance.iterChildrenOfType(V.DESCRIPTION): |
| 157 |
kwargs["description"] = _defuseUploadedText(desc.text_) |
| 158 |
|
| 159 |
for k in kwargs: |
| 160 |
kwargs[k] = _defuseUploadedText(kwargs[k]) |
| 161 |
|
| 162 |
return kwargs |
| 163 |
|
| 164 |
|
| 165 |
def makeTableDefForVOTable(tableId, votTable, nameMaker=None, rd=None, |
| 166 |
**moreArgs): |
| 167 |
"""returns a TableDef for a Table element parsed from a VOTable. |
| 168 |
|
| 169 |
Pass additional constructor arguments for the table in moreArgs. |
| 170 |
stcColumns is a dictionary mapping IDs within the source VOTable |
| 171 |
to pairs of stc and utype. |
| 172 |
|
| 173 |
nameMaker is an optional argument; if given, it must be an object |
| 174 |
having a makeName(field) -> string or utils.QuotedName method. |
| 175 |
It must return unique objects from VOTable fields and do that |
| 176 |
reproducibly, i.e., for a given field the same name is returned. |
| 177 |
|
| 178 |
The default is valuemappers.VOTNameMaker. When building TDs for Postgres, |
| 179 |
use AutoQuotedNameMaker to generate valid column names. |
| 180 |
|
| 181 |
As an extra service, in particular for ADQL name resolving, the column |
| 182 |
objects returned here have an attribute originalName containing |
| 183 |
whatever was originally in a FIELD's @name. |
| 184 |
|
| 185 |
If unique "main" positions are given, a spatial q3c index will be |
| 186 |
added. |
| 187 |
""" |
| 188 |
if nameMaker is None: |
| 189 |
nameMaker = valuemappers.VOTNameMaker() |
| 190 |
|
| 191 |
# make columns |
| 192 |
columns = [] |
| 193 |
for f in votTable.iterChildrenOfType(V.FIELD): |
| 194 |
newName = nameMaker.makeName(f) |
| 195 |
columns.append(MS(rscdef.Column, |
| 196 |
**_getColArgs(f, newName))) |
| 197 |
# tell the ADQL machinery if we've significantly modified the |
| 198 |
# name (i.e., more than just quoting). |
| 199 |
if isinstance(newName, _ChangedName): |
| 200 |
columns[-1].originalName = f.name |
| 201 |
|
| 202 |
# make params |
| 203 |
params = [] |
| 204 |
for f in votTable.iterChildrenOfType(V.PARAM): |
| 205 |
try: |
| 206 |
params.append(MS(rscdef.Param, **_getColArgs(f, f.name))) |
| 207 |
except Exception as ex: # never die because of failing params |
| 208 |
base.ui.notifyError("Unsupported PARAM ignored (%s)"%ex) |
| 209 |
|
| 210 |
# Create the table definition |
| 211 |
tableDef = MS(rscdef.TableDef, id=tableId, columns=columns, |
| 212 |
params=params, parent_=rd, **moreArgs) |
| 213 |
|
| 214 |
# Build STC info |
| 215 |
for colInfo, ast in modelgroups.unmarshal_STC(votTable): |
| 216 |
for colId, utype in colInfo.items(): |
| 217 |
try: |
| 218 |
col = tableDef.getColumnById(colId) |
| 219 |
col.stcUtype = utype |
| 220 |
col.stc = ast |
| 221 |
except utils.NotFoundError: # ignore broken STC |
| 222 |
pass |
| 223 |
|
| 224 |
return tableDef |
| 225 |
|
| 226 |
|
| 227 |
def makeDDForVOTable(tableId, vot, gunzip=False, rd=None, **moreArgs): |
| 228 |
"""returns a DD suitable for uploadVOTable. |
| 229 |
|
| 230 |
moreArgs are additional keywords for the construction of the target |
| 231 |
table. |
| 232 |
|
| 233 |
Only the first resource will be turned into a DD. Currently, |
| 234 |
only the first table is used. This probably has to change. |
| 235 |
""" |
| 236 |
tableDefs = [] |
| 237 |
for res in vot.iterChildrenOfType(V.RESOURCE): |
| 238 |
for table in res.iterChildrenOfType(V.TABLE): |
| 239 |
tableDefs.append( |
| 240 |
makeTableDefForVOTable(tableId, table, rd=rd, **moreArgs)) |
| 241 |
break |
| 242 |
break |
| 243 |
if tableDefs: |
| 244 |
makes = [MS(rscdef.Make, table=tableDefs[0])] |
| 245 |
else: |
| 246 |
makes = [] |
| 247 |
return MS(rscdef.DataDescriptor, |
| 248 |
grammar=MS(votablegrammar.VOTableGrammar, gunzip=gunzip), |
| 249 |
makes=makes) |
| 250 |
|
| 251 |
|
| 252 |
def _getRowMaker(table): |
| 253 |
"""returns a function turning a VOTable tuple to a database row |
| 254 |
for table. |
| 255 |
|
| 256 |
This is mainly just building a row dictionary, except we also |
| 257 |
parse xtyped columns. |
| 258 |
""" |
| 259 |
from gavo.base.literals import parseDefaultDatetime #noflake: code gen |
| 260 |
from gavo.stc import parseSimpleSTCS, simpleSTCSToPolygon #noflake: code gen |
| 261 |
|
| 262 |
parts = [] |
| 263 |
for colInd, col in enumerate(table.tableDef): |
| 264 |
valCode = "row[%d]"%colInd |
| 265 |
parts.append("%s: %s"%(repr(col.key), valCode)) |
| 266 |
|
| 267 |
return utils.compileFunction( |
| 268 |
"def makeRow(row):\n return {%s}"%(", ".join(parts)), |
| 269 |
"makeRow", |
| 270 |
locals()) |
| 271 |
|
| 272 |
|
| 273 |
def uploadVOTable(tableId, srcFile, connection, gunzip=False, |
| 274 |
rd=None, **tableArgs): |
| 275 |
"""creates a temporary table with tableId containing the first |
| 276 |
table in the VOTable in srcFile. |
| 277 |
|
| 278 |
The function returns a DBTable instance for the new file. |
| 279 |
|
| 280 |
srcFile must be an open file object (or some similar object). |
| 281 |
""" |
| 282 |
if gunzip: |
| 283 |
srcFile = gzip.GzipFile(fileobj=srcFile, mode="r") |
| 284 |
|
| 285 |
try: |
| 286 |
tuples = next(votable.parse(srcFile, raiseOnInvalid=False)) |
| 287 |
except StopIteration: # no table contained; bomb out |
| 288 |
raise ValueError("Cannot parse VOTable (or no table contained)") |
| 289 |
|
| 290 |
args = {"onDisk": True, "temporary": True} |
| 291 |
args.update(tableArgs) |
| 292 |
td = makeTableDefForVOTable(tableId, tuples.tableDefinition, |
| 293 |
rd=rd, **args) |
| 294 |
|
| 295 |
table = rsc.TableForDef(td, connection=connection, create=True) |
| 296 |
makeRow = _getRowMaker(table) |
| 297 |
with table.getFeeder() as feeder: |
| 298 |
for tuple in tuples: |
| 299 |
feeder.add(makeRow(tuple)) |
| 300 |
|
| 301 |
table.importFinished(1000) |
| 302 |
return table |