| 1 |
""" |
| 2 |
Writing tabular data within VOTables. |
| 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 io |
| 12 |
|
| 13 |
from gavo import utils |
| 14 |
from gavo.utils import stanxml |
| 15 |
from gavo.votable import coding |
| 16 |
from gavo.votable import common |
| 17 |
from gavo.votable import enc_binary |
| 18 |
from gavo.votable import enc_binary2 |
| 19 |
from gavo.votable import enc_tabledata |
| 20 |
from gavo.votable.model import VOTable as V |
| 21 |
|
| 22 |
from gavo.utils.dachstypes import ( |
| 23 |
Any, BytesWritable, Dict, Iterable, Iterator, |
| 24 |
ModuleType, Optional, Type, Union) |
| 25 |
|
| 26 |
_encoders: dict[Type[V._VOTElement], ModuleType] = { |
| 27 |
V.TABLEDATA: enc_tabledata, |
| 28 |
V.BINARY: enc_binary, |
| 29 |
V.BINARY2: enc_binary2, |
| 30 |
} |
| 31 |
|
| 32 |
|
| 33 |
def write( |
| 34 |
root: V.VOTABLE | V.INFO, |
| 35 |
outputFile: BytesWritable, |
| 36 |
xmlDecl: bool = True |
| 37 |
) -> None: |
| 38 |
"""writes a VOTable to outputFile. |
| 39 |
|
| 40 |
This is a compatibility function that's in this place mainly for historical |
| 41 |
reasons. It's basically utils.xmlwrite, except that the prefix of the root |
| 42 |
element will be the empty prefix. |
| 43 |
|
| 44 |
The INFO as root is only relevant when writing the overflow element below; |
| 45 |
There's no expectation that you can write standalone INFO-s. |
| 46 |
""" |
| 47 |
utils.xmlwrite(root, |
| 48 |
outputFile, |
| 49 |
xmlDecl=xmlDecl, |
| 50 |
prefixForEmpty=root._prefix) |
| 51 |
|
| 52 |
|
| 53 |
def asBytes(root: V.VOTABLE, xmlDecl: bool=False): |
| 54 |
"""returns the V.VOTABLE root as a string. |
| 55 |
""" |
| 56 |
res = io.BytesIO() |
| 57 |
try: |
| 58 |
write(root, res, xmlDecl=xmlDecl) |
| 59 |
except Exception: |
| 60 |
# something bad happened while generating the VOTable. We probably |
| 61 |
# have unwound the element stack and left an error INFO, so probably |
| 62 |
# the document is all right. Let's return it, but try to report an |
| 63 |
# error anyway if there's the infrastructure to do that |
| 64 |
utils.sendUIEvent("Error", "Exception during VOTable write (delivering" |
| 65 |
" the document anyway)") |
| 66 |
return res.getvalue() |
| 67 |
|
| 68 |
|
| 69 |
class OverflowElement(stanxml.Stub): |
| 70 |
"""A container for VOTable elements that are written when it is |
| 71 |
likely that a query has overflowed the limit. |
| 72 |
|
| 73 |
This is for use with DelayedTable. Instances of this can be |
| 74 |
passed into overflowElement. |
| 75 |
|
| 76 |
OverflowElements are constructed with the row limit and VOTable |
| 77 |
material to be inserted when exactly row limit (or more) rows |
| 78 |
have been written to the table. |
| 79 |
|
| 80 |
All automatic namespace processing is turned off for the overflow |
| 81 |
element. This should not be a problem if you're embedding VOTable |
| 82 |
elements into VOTables. |
| 83 |
""" |
| 84 |
def __init__(self, rowLimit: int, overflowStan: V.INFO) -> None: |
| 85 |
self.rowLimit, self.overflowStan = rowLimit, overflowStan |
| 86 |
self.rowsDelivered: int = -1 # pseudo NULL for type-cleanliness |
| 87 |
# disable namespace generation for write (ugly; fix this when |
| 88 |
# we've improved XML generation in xmlstan) |
| 89 |
self.overflowStan._fixedTagMaterial = "" # type: ignore # free attr |
| 90 |
|
| 91 |
def __repr__(self) -> str: |
| 92 |
return "<Uninstanciated Overflow Warning>" |
| 93 |
|
| 94 |
def setRowsDelivered(self, numRows: int) -> None: |
| 95 |
self.rowsDelivered = numRows |
| 96 |
|
| 97 |
def write(self, outputFile: BytesWritable) -> None: |
| 98 |
if self.rowLimit<=self.rowsDelivered: |
| 99 |
write(self.overflowStan, outputFile, xmlDecl=False) |
| 100 |
|
| 101 |
|
| 102 |
def DelayedTable( |
| 103 |
tableDefinition: V.TABLE, |
| 104 |
rowIterator: Iterable[Dict[str, Any]], |
| 105 |
contentElement: Union[Type[V.TABLEDATA], Type[V.BINARY], Type[V.BINARY2]], |
| 106 |
overflowElement: Optional[OverflowElement] = None, |
| 107 |
**attrs: Any |
| 108 |
) -> V.TABLE: |
| 109 |
"""returns tableDefinition such that when serialized, it contains |
| 110 |
the data from rowIterator |
| 111 |
|
| 112 |
rowIterator is an iterator yielding all rows from the table to be encoded, |
| 113 |
tableDefinition is the TABLE element, and ContentElement is one of the |
| 114 |
permitted DATA children from VOTable. |
| 115 |
|
| 116 |
See the OverflowElement class for overflowElement. |
| 117 |
|
| 118 |
attrs are optional attributes to the content element. |
| 119 |
""" |
| 120 |
if contentElement not in _encoders: |
| 121 |
raise common.VOTableError("Unsupported content element %s"%contentElement, |
| 122 |
hint="Try something like TABLEDATA or BINARY") |
| 123 |
encodeRow = coding.buildEncoder(tableDefinition, _encoders[contentElement]) |
| 124 |
|
| 125 |
def iterSerialized() -> Iterator[Union[bytes, str]]: |
| 126 |
numRows = 0 |
| 127 |
for row in rowIterator: |
| 128 |
numRows += 1 |
| 129 |
yield encodeRow(row) |
| 130 |
if overflowElement is not None: |
| 131 |
overflowElement.setRowsDelivered(numRows) |
| 132 |
|
| 133 |
content = contentElement(**attrs) |
| 134 |
content.text_ = "Placeholder for real data" |
| 135 |
content.iterSerialized = iterSerialized # type: ignore # dynamic attribute |
| 136 |
|
| 137 |
return tableDefinition[ |
| 138 |
V.DATA[content]] |
| 139 |
# In a way, we'd like to have an overflow element here, assuming that |
| 140 |
# the table comes from a db query. We could have that writing: |
| 141 |
# overflowElement] |
| 142 |
# -- but TAP wants the overflow at the resource level. So, we |
| 143 |
# put it there. It will reflect the state of affairs for the last |
| 144 |
# table (which is probably as good as anything else). |