| 1 |
""" |
| 2 |
Serialising table rows. |
| 3 |
|
| 4 |
The main class in this module is the SerManager, which knows about |
| 5 |
a target table and figures out how to turn the values in the table |
| 6 |
rows into strings. |
| 7 |
|
| 8 |
This is used by formats.votablewrite and the HTML table serialisation. |
| 9 |
|
| 10 |
utils.serializers has once been a part of this module. To save migration |
| 11 |
effort, for now it reproduces that module's interface. |
| 12 |
""" |
| 13 |
|
| 14 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 15 |
#c |
| 16 |
#c This program is free software, covered by the GNU GPL. See the |
| 17 |
#c COPYING file in the source distribution. |
| 18 |
|
| 19 |
|
| 20 |
import functools |
| 21 |
import re |
| 22 |
|
| 23 |
from gavo import utils |
| 24 |
from gavo.utils.serializers import ( #noflake: for (compatibility) export |
| 25 |
ValueMapperFactoryRegistry, defaultMFRegistry, AnnotatedColumn, |
| 26 |
registerDefaultMF) |
| 27 |
|
| 28 |
from gavo.utils.dachstypes import (cast, TYPE_CHECKING, |
| 29 |
BaseTable, Callable, Dict, Iterator, List, Optional, Set, Tuple, Union) |
| 30 |
|
| 31 |
if TYPE_CHECKING: |
| 32 |
from gavo.votable.model import VOTable |
| 33 |
|
| 34 |
|
| 35 |
class SerManager(utils.IdManagerMixin): |
| 36 |
"""A wrapper for the serialisation of table data. |
| 37 |
|
| 38 |
SerManager instances keep information on what values certain columns can |
| 39 |
assume and how to map them to concrete values in VOTables, HTML, or ASCII. |
| 40 |
|
| 41 |
They are constructed with a BaseTable instance. |
| 42 |
|
| 43 |
You can additionally give: |
| 44 |
|
| 45 |
- withRanges -- ignored, going away |
| 46 |
- acquireSamples -- ignored, going away |
| 47 |
- idManager -- an object mixing in utils.IdManagerMixin. This is important |
| 48 |
if the ids we are assigning here end up in a larger document. In that |
| 49 |
case, pass in the id manager of that larger document. Default is the |
| 50 |
SerManager itself |
| 51 |
- mfRegistry -- a map factory registry. Default is the defaltMFRegistry, |
| 52 |
which is suitable for VOTables. |
| 53 |
|
| 54 |
Iterate over a SerManager to retrieve the annotated columns. |
| 55 |
""" |
| 56 |
# Filled out on demand |
| 57 |
_nameDict = None |
| 58 |
|
| 59 |
def __init__(self, |
| 60 |
table: BaseTable, |
| 61 |
withRanges: bool = True, |
| 62 |
acquireSamples: bool = True, |
| 63 |
idManager: Optional[utils.IdManagerMixin] = None, |
| 64 |
mfRegistry: ValueMapperFactoryRegistry = defaultMFRegistry) -> None: |
| 65 |
self.table = table |
| 66 |
if idManager is not None: |
| 67 |
self.cloneFrom(idManager) |
| 68 |
self.notes: Dict[str, str] = {} |
| 69 |
self._makeAnnotatedColumns() |
| 70 |
self._makeMappers(mfRegistry) |
| 71 |
|
| 72 |
def __iter__(self) -> Iterator[AnnotatedColumn]: |
| 73 |
return iter(self.annCols) |
| 74 |
|
| 75 |
def _makeAnnotatedColumns(self) -> None: |
| 76 |
self.annCols = [] |
| 77 |
for column in self.table.tableDef: |
| 78 |
self.annCols.append( |
| 79 |
AnnotatedColumn(column, self.table.votCasts.get(column.name))) |
| 80 |
|
| 81 |
# We unconditionally generate IDs for FIELDs since rev ~4368 |
| 82 |
# If a column actually got included twice in a VOTable, its id |
| 83 |
# would occur twice in the VOTable; I guess that would need |
| 84 |
# handling in xmlstan |
| 85 |
colId = self.getOrMakeIdFor(column, column.id or column.key) |
| 86 |
if colId is not None: |
| 87 |
self.annCols[-1]["id"] = colId |
| 88 |
|
| 89 |
# if column refers to a note, remember the note |
| 90 |
if column.note: |
| 91 |
try: |
| 92 |
self.notes[column.note.tag] = column.note |
| 93 |
self.annCols[-1]["note"] = column.note |
| 94 |
except (ValueError, utils.NotFoundError): |
| 95 |
pass # don't worry about missing notes, but don't display them either |
| 96 |
|
| 97 |
self.byName: Dict[str, AnnotatedColumn] = dict( |
| 98 |
(cast(str, annCol["name"]), annCol) for annCol in self.annCols) |
| 99 |
|
| 100 |
def _makeMappers(self, mfRegistry: ValueMapperFactoryRegistry) -> None: |
| 101 |
"""returns a sequence of functions mapping our columns. |
| 102 |
|
| 103 |
As a side effect, column properties may change (in particular, |
| 104 |
datatypes). |
| 105 |
""" |
| 106 |
mappers = [] |
| 107 |
for annCol in self: |
| 108 |
mappers.append(mfRegistry.getMapper(annCol)) |
| 109 |
self.mappers = tuple(mappers) |
| 110 |
|
| 111 |
def getColumnByName(self, name: str) -> AnnotatedColumn: |
| 112 |
"""returns an AnnotatedColumn element for name. |
| 113 |
|
| 114 |
To help out in case name has gone through postgres, this will try |
| 115 |
name lowercased if it doesn't match in normal case. |
| 116 |
|
| 117 |
This will raise a KeyError if name can't be found anyway. |
| 118 |
""" |
| 119 |
try: |
| 120 |
return self.byName[name] |
| 121 |
except: |
| 122 |
return self.byName[name.lower()] |
| 123 |
|
| 124 |
def _compileMapFunction(self, funcLines: List[str]) -> Callable: |
| 125 |
"""helps _make(Dict|Tuple)Factory. |
| 126 |
""" |
| 127 |
return utils.compileFunction( |
| 128 |
"\n".join(funcLines), "buildRec", |
| 129 |
useGlobals=dict(("map%d"%index, mapper) |
| 130 |
for index, mapper in enumerate(self.mappers))) |
| 131 |
|
| 132 |
def _makeDictFactory(self) -> Callable[[Dict], Dict]: |
| 133 |
"""returns a function that returns a dictionary of mapped values |
| 134 |
for a row dictionary. |
| 135 |
""" |
| 136 |
colLabels = [str(c["name"]) for c in self] |
| 137 |
funDef = ["def buildRec(rowDict):"] |
| 138 |
for index, label in enumerate(colLabels): |
| 139 |
if self.mappers[index] is not utils.identity: |
| 140 |
funDef.append("\trowDict[%r] = map%d(rowDict[%r])"%( |
| 141 |
label, index, label)) |
| 142 |
funDef.append("\treturn rowDict") |
| 143 |
return self._compileMapFunction(funDef) |
| 144 |
|
| 145 |
def _makeTupleFactory(self) -> Callable[[Dict], Tuple]: |
| 146 |
"""returns a function that returns a tuple of mapped values |
| 147 |
for a row dictionary. |
| 148 |
""" |
| 149 |
funDef = ["def buildRec(rowDict):", "\treturn ("] |
| 150 |
for index, cd in enumerate(self): |
| 151 |
if self.mappers[index] is utils.identity: |
| 152 |
funDef.append("\t\trowDict[%r],"%cd["name"]) |
| 153 |
else: |
| 154 |
funDef.append("\t\tmap%d(rowDict[%r]),"%(index, cd["name"])) |
| 155 |
funDef.append("\t)") |
| 156 |
return self._compileMapFunction(funDef) |
| 157 |
|
| 158 |
def _iterWithMaps(self, buildRec: Union[ |
| 159 |
Callable[[Dict], Dict], |
| 160 |
Callable[[Dict], Tuple]], |
| 161 |
) -> Iterator[Union[Dict, Tuple]]: |
| 162 |
"""helps getMapped(Values|Tuples). |
| 163 |
""" |
| 164 |
colLabels = [f.name for f in self.table.tableDef] |
| 165 |
if not colLabels: |
| 166 |
yield () |
| 167 |
return |
| 168 |
for row in self.table: |
| 169 |
yield buildRec(row) |
| 170 |
|
| 171 |
def getMappedValues(self) -> Iterator[Dict]: |
| 172 |
"""iterates over the table's rows as dicts with mapped values. |
| 173 |
""" |
| 174 |
# the polymorphism of _iterWithMaps is too hard to explain |
| 175 |
return self._iterWithMaps(self._makeDictFactory()) # type: ignore |
| 176 |
|
| 177 |
def getMappedTuples(self) -> Iterator[Tuple]: |
| 178 |
"""iterates over the table's rows as tuples with mapped values. |
| 179 |
""" |
| 180 |
# the polymorphism of _iterWithMaps is too hard to explain |
| 181 |
return self._iterWithMaps(self._makeTupleFactory()) # type:ignore |
| 182 |
|
| 183 |
|
| 184 |
def needsQuoting(identifier: str, forRowmaker: bool = False) -> bool: |
| 185 |
"""returns True if identifier needs quoting in an SQL statement. |
| 186 |
""" |
| 187 |
if utils.identifierPattern.match(identifier) is None: |
| 188 |
return True |
| 189 |
# extra rule for standards SQL 92 |
| 190 |
if identifier.startswith("_"): |
| 191 |
return True |
| 192 |
|
| 193 |
if identifier.lower() in getNameBlacklist(forRowmaker): |
| 194 |
return True |
| 195 |
return False |
| 196 |
|
| 197 |
|
| 198 |
@functools.cache |
| 199 |
def getADQLReservedWords() -> Set[str]: |
| 200 |
# as a cached function because the adql module wants a fully initialised |
| 201 |
# database connection (in ufunctions), and we may not have that when |
| 202 |
# valuemappers is imported. |
| 203 |
from gavo import adql |
| 204 |
return adql.ALL_RESERVED_WORDS |
| 205 |
|
| 206 |
|
| 207 |
@functools.cache |
| 208 |
def getNameBlacklist(forRowmaker: bool = False) -> frozenset: |
| 209 |
"""returns a set of names not suitable for table column names. |
| 210 |
|
| 211 |
This comprises SQL reserved words in lower case and, if forRowmaker |
| 212 |
is true, also some names damaging row makers (e.g. python reserved |
| 213 |
words). |
| 214 |
""" |
| 215 |
res = set(k.lower() for k in getADQLReservedWords()) |
| 216 |
if forRowmaker: |
| 217 |
import keyword |
| 218 |
from gavo.rscdef import rmkfuncs |
| 219 |
res = (res |
| 220 |
| set(["result_", "rowdict_"]) |
| 221 |
| set(k.lower() for k in keyword.kwlist) |
| 222 |
| set(k.lower() for k in dir(rmkfuncs))) |
| 223 |
return frozenset(res) |
| 224 |
|
| 225 |
|
| 226 |
class VOTNameMaker(object): |
| 227 |
"""A class for generating db-unique names from VOTable fields. |
| 228 |
|
| 229 |
This is important to avoid all kinds of weird names the remaining |
| 230 |
infrastructure will not handle. "Normal" TableDefs assume unquoted |
| 231 |
SQL identifiers as names, and want all names unique. |
| 232 |
|
| 233 |
Using this class ensures these expectations are met in a reproducible |
| 234 |
way (i.e., given the same table, the same names will be assigned). |
| 235 |
""" |
| 236 |
def __init__(self) -> None: |
| 237 |
self.knownNames, self.index = set(getNameBlacklist(True)), 0 |
| 238 |
|
| 239 |
def makeName(self, field: "VOTable.FIELD") -> str: |
| 240 |
preName = re.sub(r"[^\w]+", "x", (getattr(field, "name", None) |
| 241 |
or getattr(field, "ID", None) |
| 242 |
or "field%02d"%self.index)) |
| 243 |
if not re.match("[A-Za-z_]", preName): |
| 244 |
preName = "col_"+preName |
| 245 |
while preName.lower() in self.knownNames: |
| 246 |
preName = preName+"_" |
| 247 |
self.knownNames.add(preName.lower()) |
| 248 |
self.index += 1 |
| 249 |
return preName |