| 1 |
""" |
| 2 |
Encoding to tabledata. |
| 3 |
|
| 4 |
These are functions returning pieces of code that are assembled |
| 5 |
into an encoding function. This still returns a normal string. |
| 6 |
The encoding into utf-8 only takes place in model's TABLEDATA element. |
| 7 |
|
| 8 |
Most functions here deal with both FIELD-s and PARAM-s, as the PARAM's |
| 9 |
@value attribute contains tabledata-serialised values. |
| 10 |
""" |
| 11 |
|
| 12 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 13 |
#c |
| 14 |
#c This program is free software, covered by the GNU GPL. See the |
| 15 |
#c COPYING file in the source distribution. |
| 16 |
|
| 17 |
|
| 18 |
import datetime #noflake: used in generated code |
| 19 |
import json #noflake: used in generated code |
| 20 |
|
| 21 |
|
| 22 |
from gavo import utils #noflake: used in generated code |
| 23 |
from gavo.utils import stanxml |
| 24 |
from gavo.utils import pgsphere #noflake: used in generated code |
| 25 |
from gavo.votable import coding |
| 26 |
from gavo.votable import common |
| 27 |
from gavo.votable.model import VOTable |
| 28 |
|
| 29 |
from gavo.utils.dachstypes import Any, Callable, Dict, List, Optional |
| 30 |
|
| 31 |
|
| 32 |
def _getArrayShapingCode(field: VOTable.TypedElement, padder: str |
| 33 |
) -> List[str]: |
| 34 |
"""returns common code for almost all array serialization. |
| 35 |
|
| 36 |
Field must describe an array (as opposed to a single value). |
| 37 |
|
| 38 |
padder must be python-source for whatever is used to pad |
| 39 |
arrays that are too short. |
| 40 |
""" |
| 41 |
base = [ |
| 42 |
"if val is None: val = []"] |
| 43 |
if field.isMultiDim(): |
| 44 |
# it's an n-d array (n>1): flatten out all values |
| 45 |
base.append("val = coding.ravel(val)") |
| 46 |
if field.hasVarLength(): |
| 47 |
return base |
| 48 |
else: |
| 49 |
return base+["val = coding.trim(val, %s, %s)"%( |
| 50 |
field.getLength(), padder)] |
| 51 |
|
| 52 |
|
| 53 |
def _addNullvalueCode( |
| 54 |
field: VOTable.TypedElement, |
| 55 |
src: List[str], |
| 56 |
validator: Callable[[Any], Any], |
| 57 |
defaultNullValue: Optional[str] = None) -> List[str]: |
| 58 |
"""adds code handle null values where not default representation exists. |
| 59 |
""" |
| 60 |
nullvalue = coding.getNullvalue(field, validator) |
| 61 |
if nullvalue is None: |
| 62 |
if defaultNullValue is None: |
| 63 |
action = (" raise common.BadVOTableData('None passed for field" |
| 64 |
" that has no NULL value', None, '%s', hint='Integers in VOTable" |
| 65 |
" have no natural serializations for missing values. You need to" |
| 66 |
" define one using values null to allow for NULL in integer columns')" |
| 67 |
)%field.getDesignation() |
| 68 |
else: |
| 69 |
action = (" tokens.append(%r)"%stanxml.escapePCDATA(defaultNullValue)) |
| 70 |
else: |
| 71 |
action = " tokens.append(%r)"%stanxml.escapePCDATA(nullvalue) |
| 72 |
return [ |
| 73 |
'if val is None:', |
| 74 |
action, |
| 75 |
'else:']+common.indentList(src, " ") |
| 76 |
|
| 77 |
|
| 78 |
def _makeFloatEncoder(field: VOTable.TypedElement) -> List[str]: |
| 79 |
return [ |
| 80 |
"if val is None or val!=val:", # NaN is a null value, too |
| 81 |
" tokens.append('NaN')", |
| 82 |
"else:", |
| 83 |
" tokens.append(repr(float(val)))"] |
| 84 |
|
| 85 |
|
| 86 |
def _makeComplexEncoder(field: VOTable.TypedElement) -> List[str]: |
| 87 |
return [ |
| 88 |
"if val is None:", |
| 89 |
" tokens.append('NaN NaN')", |
| 90 |
"else:", |
| 91 |
" try:", |
| 92 |
" tokens.append('%s %s'%(repr(val.real), repr(val.imag)))", |
| 93 |
" except AttributeError:", |
| 94 |
" tokens.append(repr(val))",] |
| 95 |
|
| 96 |
|
| 97 |
def _makeBooleanEncoder(field: VOTable.TypedElement) -> List[str]: |
| 98 |
return [ |
| 99 |
"if val is None:", |
| 100 |
" tokens.append('?')", |
| 101 |
"elif val:", |
| 102 |
" tokens.append('1')", |
| 103 |
"else:", |
| 104 |
" tokens.append('0')",] |
| 105 |
|
| 106 |
|
| 107 |
def _makeUByteEncoder(field: VOTable.TypedElement) -> List[str]: |
| 108 |
return _addNullvalueCode(field, [ |
| 109 |
"if isinstance(val, int):", |
| 110 |
' tokens.append(str(val))', |
| 111 |
"else:", |
| 112 |
' tokens.append(str(ord(val[:1])))',], |
| 113 |
common.validateVOTInt, "") |
| 114 |
|
| 115 |
|
| 116 |
def _makeIntEncoder(field: VOTable.TypedElement) -> List[str]: |
| 117 |
return _addNullvalueCode(field, [ |
| 118 |
"tokens.append(str(val))"], |
| 119 |
common.validateVOTInt) |
| 120 |
|
| 121 |
|
| 122 |
def _makeCharEncoder(field: VOTable.TypedElement) -> List[str]: |
| 123 |
src = [] |
| 124 |
|
| 125 |
src.extend(common.getXtypeEncoderCode(field)) |
| 126 |
src.append("val = coding.trimString(val, %s)"%repr(field.arraysize)) |
| 127 |
|
| 128 |
if field.datatype=="char": |
| 129 |
# we're not supposed to put non-ascii into chars. |
| 130 |
src.extend([ |
| 131 |
'if isinstance(val, str):', |
| 132 |
' val = val.encode("ascii", "replace").decode("ascii")']) |
| 133 |
|
| 134 |
src.extend([ |
| 135 |
"tokens.append(stanxml.escapePCDATA(val))"]) |
| 136 |
|
| 137 |
return _addNullvalueCode(field, src, lambda _: True, "") |
| 138 |
|
| 139 |
|
| 140 |
_encoders: Dict[str, Callable[[VOTable.TypedElement], List[str]]] = { |
| 141 |
'boolean': _makeBooleanEncoder, |
| 142 |
'bit': _makeIntEncoder, |
| 143 |
'unsignedByte': _makeUByteEncoder, |
| 144 |
'short': _makeIntEncoder, |
| 145 |
'int': _makeIntEncoder, |
| 146 |
'long': _makeIntEncoder, |
| 147 |
'char': _makeCharEncoder, |
| 148 |
'unicodeChar': _makeCharEncoder, |
| 149 |
'float': _makeFloatEncoder, |
| 150 |
'double': _makeFloatEncoder, |
| 151 |
'floatComplex': _makeComplexEncoder, |
| 152 |
'doubleComplex': _makeComplexEncoder, |
| 153 |
} |
| 154 |
|
| 155 |
|
| 156 |
def _getArrayEncoderLinesNotNULL(field: VOTable.TypedElement) -> List[str]: |
| 157 |
"""returns python lines to encode array values of field. |
| 158 |
|
| 159 |
Again, the specs are a bit nuts, so we end up special casing almost |
| 160 |
everything. |
| 161 |
|
| 162 |
For fixed-length arrays we enforce the given length by |
| 163 |
cropping or adding nulls (except, currently, for bit and char arrays). |
| 164 |
""" |
| 165 |
type = field.datatype |
| 166 |
# bit array literals are integers, real special handling |
| 167 |
if type=="bit": |
| 168 |
return ['tokens.append(utils.toBinary(val))'] |
| 169 |
# char array literals are strings, real special handling |
| 170 |
if type=='char' or type=='unicodeChar': |
| 171 |
return _makeCharEncoder(field) |
| 172 |
|
| 173 |
src = common.getXtypeEncoderCode(field) |
| 174 |
src.extend(_getArrayShapingCode(field, '[None]')) |
| 175 |
src.extend([ # Painful name juggling to avoid functions |
| 176 |
'fullTokens = tokens', |
| 177 |
'tokens = []', |
| 178 |
'arr = val']) |
| 179 |
|
| 180 |
src.extend(['for val in coding.ravel(arr):']+common.indentList( |
| 181 |
_encoders[type](field), " ")) |
| 182 |
src.append("fullTokens.append(' '.join(tokens))") |
| 183 |
src.append("tokens = fullTokens") |
| 184 |
return src |
| 185 |
|
| 186 |
|
| 187 |
def _getArrayEncoderLines(field: VOTable.TypedElement) -> List[str]: |
| 188 |
"""returns python lines to encode array values of field. |
| 189 |
|
| 190 |
This will encode NULL array as empty strings. |
| 191 |
""" |
| 192 |
return [ |
| 193 |
"if val is None:", |
| 194 |
" tokens.append('')", |
| 195 |
"else:",]+common.indentList(_getArrayEncoderLinesNotNULL(field), " ") |
| 196 |
|
| 197 |
|
| 198 |
def getLinesFor(field: VOTable.TypedElement) -> List[str]: |
| 199 |
"""returns a sequence of python source lines to encode values described |
| 200 |
by field into tabledata. |
| 201 |
""" |
| 202 |
if field.isScalar(): |
| 203 |
return _encoders[field.datatype](field) |
| 204 |
else: |
| 205 |
return _getArrayEncoderLines(field) |
| 206 |
|
| 207 |
|
| 208 |
def getPostamble(tableDefinition: VOTable.TABLE) -> List[str]: |
| 209 |
return [ |
| 210 |
"return '<TR>%s</TR>'%(''.join('<TD>%s</TD>'%v for v in tokens))"] |
| 211 |
|
| 212 |
|
| 213 |
def getGlobals(tableDefinition: Optional[VOTable.TABLE]) -> Dict[str, Any]: |
| 214 |
return globals() |