| 1 |
""" |
| 2 |
Description of columns (and I/O fields). |
| 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 functools |
| 12 |
import math |
| 13 |
|
| 14 |
from gavo import base |
| 15 |
from gavo import dm |
| 16 |
from gavo import votable |
| 17 |
from gavo import utils |
| 18 |
from gavo.base import typesystems |
| 19 |
from gavo.utils import codetricks |
| 20 |
|
| 21 |
|
| 22 |
# A set of database type names that need explicit null values when |
| 23 |
# they are serialized into VOTables. We don't check array types |
| 24 |
# here at all, since that's another can of worms entirely. |
| 25 |
EXPLICIT_NULL_TYPES = set([ |
| 26 |
"smallint", "integer", "bigint", "char", "boolean", "bytea"]) |
| 27 |
|
| 28 |
|
| 29 |
class TypeNameAttribute(base.AtomicAttribute): |
| 30 |
"""An attribute with values constrained to types we understand. |
| 31 |
""" |
| 32 |
@property |
| 33 |
def typeDesc_(self): |
| 34 |
return ("a type name; the internal type system is similar to SQL's" |
| 35 |
" with some restrictions and extensions. The known atomic types" |
| 36 |
" include: %s"%(", ".join(typesystems.ToPythonConverter.simpleMap))) |
| 37 |
|
| 38 |
def parse(self, value): |
| 39 |
try: |
| 40 |
typesystems.sqltypeToVOTable(value) |
| 41 |
except base.Error: |
| 42 |
raise base.ui.logOldExc(base.LiteralParseError(self.name_, value, |
| 43 |
hint="A supported SQL type was expected here. If in doubt," |
| 44 |
" check base/typeconversions.py, in particular ToPythonCodeConverter.")) |
| 45 |
return value |
| 46 |
|
| 47 |
def unparse(self, value): |
| 48 |
return value |
| 49 |
|
| 50 |
|
| 51 |
class ParamNameAttribute(base.UnicodeAttribute): |
| 52 |
"""An attribute containing a param or column name. |
| 53 |
|
| 54 |
These, in DaCHS, have to match identifierPat (essentially, like |
| 55 |
python identifiers). For compatibility with columns, they do |
| 56 |
allow the quoted/ prefix, but the only place this is really supported |
| 57 |
is in query generation. |
| 58 |
""" |
| 59 |
@property |
| 60 |
def typeDesc_(self): |
| 61 |
return ("A name for a table or service parameter. These have to match" |
| 62 |
" ``%s``." |
| 63 |
)%utils.identifierPattern.pattern |
| 64 |
|
| 65 |
def parse(self, value): |
| 66 |
if value.startswith("quoted/"): |
| 67 |
return utils.QuotedName(value[7:]) |
| 68 |
|
| 69 |
if not utils.identifierPattern.match(value): |
| 70 |
raise base.StructureError( |
| 71 |
f"'{value}' is not a valid column identifier") |
| 72 |
return value |
| 73 |
|
| 74 |
|
| 75 |
@functools.lru_cache(None) |
| 76 |
def _getReservedWords(): |
| 77 |
"""returns column names that need quoting. |
| 78 |
|
| 79 |
That's really adql.ALL_RESERVED_WORDS at this point, but I want |
| 80 |
to defer importing adql to when I actually need it. |
| 81 |
""" |
| 82 |
from gavo import adql |
| 83 |
return adql.ALL_RESERVED_WORDS |
| 84 |
|
| 85 |
|
| 86 |
class ColumnNameAttribute(ParamNameAttribute): |
| 87 |
"""An attribute containing a name suitable for SQL table names. |
| 88 |
|
| 89 |
Column names are special in that you can prefix them with "quoted/" |
| 90 |
and then get a delimited identifier. This is something you probably |
| 91 |
shouldn't use. |
| 92 |
|
| 93 |
Using ADQL/SQL reserved words (without quoting) here yields a warning. |
| 94 |
""" |
| 95 |
@property |
| 96 |
def typeDesc_(self): |
| 97 |
return ("a column name within an SQL table. These have to match the" |
| 98 |
" SQL regular_identifier production." |
| 99 |
" In a desperate pinch, you can generate delimited identifiers" |
| 100 |
" (that can contain anything) by prefixing the name with 'quoted/'") |
| 101 |
|
| 102 |
def parse(self, value): |
| 103 |
value = utils.QuotedName.parse(value) |
| 104 |
|
| 105 |
if not isinstance(value, utils.QuotedName): |
| 106 |
# do sanity checks to make sure we work as regular SQL identifiers |
| 107 |
value = ParamNameAttribute.parse(self, value) |
| 108 |
if value.upper() in _getReservedWords(): |
| 109 |
base.ui.notifyWarning("Column name '%s' coincides with a" |
| 110 |
" ADQL/SQL reserved name. This may lead to serious trouble" |
| 111 |
" later. Please consider changing the name, or prepend quoted/" |
| 112 |
" to make it a delimited identifier."%value) |
| 113 |
|
| 114 |
return value |
| 115 |
|
| 116 |
def unparse(self, value): |
| 117 |
if isinstance(value, utils.QuotedName): |
| 118 |
return "quoted/"+value.name |
| 119 |
else: |
| 120 |
return value |
| 121 |
|
| 122 |
|
| 123 |
class _AttBox(object): |
| 124 |
"""A helper for TableManagedAttribute. |
| 125 |
|
| 126 |
When a TableManagedAttribute ships off its value into an event |
| 127 |
it packs its value into an _AttBox. That way, the receiver |
| 128 |
can tell whether the value comes from another TableManagedAttribute |
| 129 |
(which is ok) or comes from an XML parser (which is forbidden). |
| 130 |
""" |
| 131 |
def __init__(self, payload): |
| 132 |
self.payload = payload |
| 133 |
|
| 134 |
|
| 135 |
class TableManagedAttribute(base.AttributeDef): |
| 136 |
"""An attribute not settable from XML for holding information |
| 137 |
managed by the parent table. |
| 138 |
|
| 139 |
That's stc and stcUtype here, currently. |
| 140 |
|
| 141 |
Do not use this in new code. This should go when the stc element |
| 142 |
can safely be replaced by gavo-dm-based stuff (here: DmRoles). |
| 143 |
""" |
| 144 |
typeDesc_ = "non-settable internally used value" |
| 145 |
|
| 146 |
def feed(self, ctx, instance, value): |
| 147 |
if isinstance(value, _AttBox): |
| 148 |
# synthetic event during object copying, accept |
| 149 |
self.feedObject(instance, value.payload) |
| 150 |
else: |
| 151 |
# do not let people set that stuff directly |
| 152 |
raise base.StructureError("Cannot set %s attributes from XML"%self.name_) |
| 153 |
|
| 154 |
def feedObject(self, instance, value): |
| 155 |
setattr(instance, self.name_, value) |
| 156 |
|
| 157 |
def iterEvents(self, instance): |
| 158 |
val = getattr(instance, self.name_) |
| 159 |
if val!=self.default_: |
| 160 |
yield ("value", self.name_, _AttBox(val)) |
| 161 |
|
| 162 |
def getCopy(self, instance, newParent, ctx): |
| 163 |
# these never get copied; the values are potentially shared |
| 164 |
# between many objects, so the must not be changed anyway. |
| 165 |
return getattr(instance, self.name_) |
| 166 |
|
| 167 |
|
| 168 |
class OldRoles(object): |
| 169 |
"""A sentinel class for Table to signal non-adapted DM roles on a column |
| 170 |
or param. |
| 171 |
""" |
| 172 |
def __init__(self, oldRoles): |
| 173 |
if isinstance(oldRoles, OldRoles): |
| 174 |
self.oldRoles = oldRoles.oldRoles |
| 175 |
else: |
| 176 |
self.oldRoles = oldRoles |
| 177 |
|
| 178 |
def __bool__(self): |
| 179 |
return bool(self.oldRoles) |
| 180 |
|
| 181 |
|
| 182 |
class DMRolesAttribute(base.AttributeDef): |
| 183 |
"""An attribute managing DM roles. |
| 184 |
|
| 185 |
It is not set directly from XML but filled when a table parses |
| 186 |
DM annotation. When copying around columns between tables, this |
| 187 |
is used to build the new annotation; the value is an oldAnnotations |
| 188 |
instance rather than a list as usual until the new parent table has |
| 189 |
started constructing its own DM annotations. |
| 190 |
""" |
| 191 |
typeDesc_ = "read-only list of roles played by this column in DMs" |
| 192 |
|
| 193 |
def __init__(self, name, description="Undocumented"): |
| 194 |
base.AttributeDef.__init__(self, |
| 195 |
name, default=base.Computed, description=description, |
| 196 |
copyable=True) |
| 197 |
|
| 198 |
@property |
| 199 |
def default_(self): |
| 200 |
return [] |
| 201 |
|
| 202 |
def feedObject(self, instance, value): |
| 203 |
setattr(instance, self.name_, value) |
| 204 |
|
| 205 |
def iterEvents(self, instance): |
| 206 |
# these are entirely externally managed |
| 207 |
if False: |
| 208 |
yield None |
| 209 |
|
| 210 |
def getCopy(self, instance, newParent, ctx): |
| 211 |
# Wrap the previous contents into a container that will prevent |
| 212 |
# accidental changes and lets the new parent table figure out |
| 213 |
# that the roles haven't been updated |
| 214 |
val = getattr(instance, self.name_) |
| 215 |
if val: |
| 216 |
return OldRoles(val) |
| 217 |
else: |
| 218 |
return [] |
| 219 |
|
| 220 |
|
| 221 |
class RoEmptyDict(dict): |
| 222 |
"""is a read-only standin for a dict. |
| 223 |
|
| 224 |
It's hashable, though, since it's always empty... This is used here |
| 225 |
for a default for displayHint. |
| 226 |
""" |
| 227 |
def __setitem__(self, what, where): |
| 228 |
raise TypeError("RoEmptyDicts are immutable") |
| 229 |
|
| 230 |
_roEmptyDict = RoEmptyDict() |
| 231 |
|
| 232 |
|
| 233 |
class DisplayHintAttribute(base.AtomicAttribute): |
| 234 |
"""is a display hint. |
| 235 |
|
| 236 |
Display hint literals are comma-separated key=value sequences. |
| 237 |
Keys are up to the application and evaluated by htmltable, votable, etc. |
| 238 |
|
| 239 |
The parsed values are simply dictionaries mapping strings to strings, i.e., |
| 240 |
value validation cannot be performed here (yet -- do we want this? |
| 241 |
A central repository of display hints would be kinda useful...) |
| 242 |
""" |
| 243 |
typeDesc_ = "Display hint" |
| 244 |
|
| 245 |
def __init__(self, name, description, **kwargs): |
| 246 |
base.AtomicAttribute.__init__(self, name, default=_roEmptyDict, |
| 247 |
description=description, **kwargs) |
| 248 |
|
| 249 |
def parse(self, value): |
| 250 |
if not value.strip(): |
| 251 |
return _roEmptyDict |
| 252 |
try: |
| 253 |
return dict([f.split("=") for f in value.split(",")]) |
| 254 |
except (ValueError, TypeError): |
| 255 |
raise base.ui.logOldExc(base.LiteralParseError(self.name_, value, |
| 256 |
hint="DisplayHints have a format like tag=value{,tag=value}")) |
| 257 |
|
| 258 |
def unparse(self, value): |
| 259 |
return ",".join( |
| 260 |
["%s=%s"%(k,v) for k,v in value.items()]) |
| 261 |
|
| 262 |
|
| 263 |
class Option(base.Structure): |
| 264 |
"""A value for enumerated columns. |
| 265 |
|
| 266 |
For presentation purposes, an option can have a title, defaulting to |
| 267 |
the option's value. |
| 268 |
""" |
| 269 |
name_ = "option" |
| 270 |
|
| 271 |
_title = base.UnicodeAttribute("title", |
| 272 |
description="A Label for presentation purposes; defaults to val.", |
| 273 |
default=base.NotGiven, |
| 274 |
copyable=True) |
| 275 |
_val = base.DataContent( |
| 276 |
description="The value of the option; this is what is used in," |
| 277 |
" e.g., queries and the like.", |
| 278 |
copyable=True) |
| 279 |
_freq = base.FloatAttribute("freq", |
| 280 |
default=None, |
| 281 |
description="The relative frequency of this value in, say, a table" |
| 282 |
" column. You would not usually set this manually.", |
| 283 |
copyable=True) |
| 284 |
|
| 285 |
def __repr__(self): |
| 286 |
# may occur in user messages from formal, so we use title. |
| 287 |
return self.title |
| 288 |
|
| 289 |
def __str__(self): |
| 290 |
return repr(self) |
| 291 |
|
| 292 |
def completeElement(self, ctx): |
| 293 |
if self.title is base.NotGiven: |
| 294 |
self.title = str(self.content_) |
| 295 |
super().completeElement(ctx) |
| 296 |
|
| 297 |
|
| 298 |
def makeOptions(*args): |
| 299 |
"""returns a list of Option instances with values given in args. |
| 300 |
""" |
| 301 |
return [base.makeStruct(Option, content_=arg) for arg in args] |
| 302 |
|
| 303 |
|
| 304 |
def makeOptionsFromDist(freqDict): |
| 305 |
"""returns a list of Option instances with freq set. |
| 306 |
|
| 307 |
freqDict must map values to relative frequencies. |
| 308 |
""" |
| 309 |
return [base.makeStruct(Option, content_=k, freq=v) |
| 310 |
for k, v in freqDict.items()] |
| 311 |
|
| 312 |
|
| 313 |
class Values(base.Structure): |
| 314 |
"""Information on a column's values, in particular its domain. |
| 315 |
|
| 316 |
This is quite like the values element in a VOTable. In particular, |
| 317 |
to accommodate VOTable usage, we require nullLiteral to be a valid literal |
| 318 |
for the parent's type. |
| 319 |
|
| 320 |
Note that DaCHS does not validate for constraints from values on |
| 321 |
table import. This is mainly because before ``dachs limits`` has run, |
| 322 |
values may not represent the new dataset in semiautomatic values. |
| 323 |
|
| 324 |
With HTTP parameters, values validation does take place (but again, |
| 325 |
that's mostly not too helpful because there are query languages |
| 326 |
sitting in between most of the time). |
| 327 |
|
| 328 |
Hence, the main utility of values is metadata declaration, both |
| 329 |
in the form renderer (where they become placeholders) and in datalink |
| 330 |
(where they are communicated as VOTable values). |
| 331 |
""" |
| 332 |
name_ = "values" |
| 333 |
|
| 334 |
_min = base.UnicodeAttribute("min", default=None, |
| 335 |
description="Minimum acceptable" |
| 336 |
" value as a datatype literal", copyable=True) |
| 337 |
_max = base.UnicodeAttribute("max", default=None, |
| 338 |
description="Maximum acceptable" |
| 339 |
" value as a datatype literal", copyable=True) |
| 340 |
_options = base.StructListAttribute("options", |
| 341 |
childFactory=Option, |
| 342 |
description="List of acceptable values (if set)", copyable=True) |
| 343 |
_default = base.UnicodeAttribute("default", default=None, |
| 344 |
description="A default" |
| 345 |
" value (currently only used for options).", copyable=True) |
| 346 |
_nullLiteral = base.UnicodeAttribute("nullLiteral", default=None, |
| 347 |
description= |
| 348 |
"An appropriate value representing a NULL for this column in VOTables" |
| 349 |
" and similar places. You usually should only set it for integer" |
| 350 |
" types and chars. Note that rowmakers make no use of this nullLiteral," |
| 351 |
" i.e., you can and should choose null values independently of" |
| 352 |
" your source. Again, for reals, floats and (mostly) text you probably" |
| 353 |
" do not want to do this.", copyable=True) |
| 354 |
_multiOk = base.BooleanAttribute("multiOk", False, "Deprecated, use" |
| 355 |
" multiplicity=multiple on input keys instead.", copyable=True) |
| 356 |
_fromDB = base.ActionAttribute("fromdb", "_evaluateFromDB", description= |
| 357 |
"A query fragment returning just one column to fill options from (will" |
| 358 |
" add to options if some are given). Do not write SELECT or anything," |
| 359 |
" just the column name and the where clause. Do not do this for" |
| 360 |
" large tables even if there are reasonably few values, because" |
| 361 |
" there is no good way to speed up this kind of query using indices.") |
| 362 |
_caseless = base.BooleanAttribute("caseless", |
| 363 |
description="When validating, ignore the case of string values." |
| 364 |
" For non-string types, behaviour is undefined (i.e., DaCHS is" |
| 365 |
" going to spit on you).", |
| 366 |
default=False, |
| 367 |
copyable=True) |
| 368 |
_actual = base.BooleanAttribute("actual", |
| 369 |
description="Do not use the options to validate columns. You" |
| 370 |
" want this if you just declare column statistics rather" |
| 371 |
" than all potential values that could occur.", |
| 372 |
default=False, |
| 373 |
copyable=True) |
| 374 |
|
| 375 |
_percentile03 = base.UnicodeAttribute("percentile03", |
| 376 |
default=None, |
| 377 |
description="Value at the 3rd percentile of the distribution of this" |
| 378 |
" column.", |
| 379 |
copyable=True) |
| 380 |
_percentile97 = base.UnicodeAttribute("percentile97", |
| 381 |
default=None, |
| 382 |
description="Value at the 97rd percentile of the distribution of this" |
| 383 |
" column.", |
| 384 |
copyable=True) |
| 385 |
_median = base.UnicodeAttribute("median", |
| 386 |
default=None, |
| 387 |
description="Median of the distribution of this column.", |
| 388 |
copyable=True) |
| 389 |
_fillFactor = base.UnicodeAttribute("fillFactor", |
| 390 |
default=None, |
| 391 |
description="Ratio of non-NULL values to the number of rows in the" |
| 392 |
" embedding table.", |
| 393 |
copyable=True) |
| 394 |
|
| 395 |
_original = base.OriginalAttribute() |
| 396 |
|
| 397 |
validValues = None |
| 398 |
|
| 399 |
@classmethod |
| 400 |
def fromOptions(cls, labels): |
| 401 |
"""returns Values with the elements of labels as valid options. |
| 402 |
""" |
| 403 |
return base.makeStruct(cls, |
| 404 |
options=[base.makeStruct(Option, content_=l) for l in labels]) |
| 405 |
|
| 406 |
@property |
| 407 |
def min_typed(self): |
| 408 |
if not hasattr(self, "_min_type_cache"): |
| 409 |
self._min_type_cache = self.makePythonVal( |
| 410 |
self.min, typesystems.scalarify(self.parent.type)) |
| 411 |
return self._min_type_cache |
| 412 |
|
| 413 |
@property |
| 414 |
def max_typed(self): |
| 415 |
if not hasattr(self, "_max_type_cache"): |
| 416 |
self._max_type_cache = self.makePythonVal( |
| 417 |
self.max, typesystems.scalarify(self.parent.type)) |
| 418 |
return self._max_type_cache |
| 419 |
|
| 420 |
def makePythonVal(self, literal, sqltype): |
| 421 |
if literal is None: |
| 422 |
return None |
| 423 |
return typesystems.sqltypeToPython(sqltype)(literal) |
| 424 |
|
| 425 |
def _evaluateFromDB(self, ctx): |
| 426 |
if not getattr(ctx, "doQueries", True): |
| 427 |
return |
| 428 |
try: |
| 429 |
with base.getTableConn() as conn: |
| 430 |
for row in conn.query(self.parent.parent.expand( |
| 431 |
"SELECT DISTINCT %s"%(self.fromdb))): |
| 432 |
if row[0] is None: |
| 433 |
# a NULL here would be about the same as required=False; |
| 434 |
# dealing with it properly in constraints is hard. Let's |
| 435 |
# see how well we get away with ignoring it. |
| 436 |
continue |
| 437 |
self._options.feedObject(self, base.makeStruct(Option, |
| 438 |
content_=row[0])) |
| 439 |
except base.DBError: # Table probably doesn't exist yet, ignore. |
| 440 |
base.ui.notifyWarning("Values fromdb '%s' failed, ignoring"%self.fromdb) |
| 441 |
|
| 442 |
def onParentComplete(self): |
| 443 |
"""converts options, the nullLiteral, and the default from |
| 444 |
string literals to python values. |
| 445 |
""" |
| 446 |
dataField = self.parent |
| 447 |
if self.options: |
| 448 |
dbt = dataField.type |
| 449 |
for opt in self.options: |
| 450 |
opt.content_ = self.makePythonVal(opt.content_, dbt) |
| 451 |
self.validValues = set(o.content_ for o in self.options) |
| 452 |
if self.caseless: |
| 453 |
self.validValues = set(o and o.lower() for o in self.validValues) |
| 454 |
|
| 455 |
if self.nullLiteral: |
| 456 |
try: |
| 457 |
self.makePythonVal(self.nullLiteral, dataField.type) |
| 458 |
except ValueError: |
| 459 |
raise base.LiteralParseError("nullLiteral", self.nullLiteral, |
| 460 |
hint="If you want to *parse* whatever you gave into a NULL," |
| 461 |
" use the parseWithNull function in a rowmaker. The null" |
| 462 |
" literal gives what value will be used for null values" |
| 463 |
" when serializing to VOTables and the like.") |
| 464 |
|
| 465 |
if self.default and isinstance(self.default, str): |
| 466 |
type, arraysize, xtype = dataField._getVOTableType() |
| 467 |
self.default = votable.getVOTParser(type, arraysize, xtype)( |
| 468 |
self.default) |
| 469 |
|
| 470 |
def setFromStatRow(self, statRow, ctx): |
| 471 |
"""fills statistics data from one of our statistics rows. |
| 472 |
|
| 473 |
This will not overwrite values already given to let people |
| 474 |
manually give statistics. |
| 475 |
""" |
| 476 |
for srcKey, destKey in [ |
| 477 |
("min_value", "min"), |
| 478 |
("max_value", "max"), |
| 479 |
("percentile03", "percentile03"), |
| 480 |
("percentile97", "percentile97"), |
| 481 |
("median", "median"), |
| 482 |
("fill_factor", "fillFactor"), |
| 483 |
]: |
| 484 |
if srcKey in statRow: |
| 485 |
if (getattr(self, destKey, None) is None |
| 486 |
and statRow[srcKey] is not None): |
| 487 |
self.feed(destKey, str(statRow[srcKey]), ctx) |
| 488 |
|
| 489 |
def setOptionsFromDict(self, dist, ctx): |
| 490 |
"""sets Options from the keys of the dict dist. |
| 491 |
|
| 492 |
This is primarily for injection of values from the DB into the RD. |
| 493 |
It will hence not change anything if there are already options |
| 494 |
defined (which are presumably manually set). |
| 495 |
""" |
| 496 |
if self.options: |
| 497 |
# fiddle in frequencies; we discard incoming stats for which |
| 498 |
# there are no options |
| 499 |
for o in self.options: |
| 500 |
o.freq = dist.get(str(o.content_)) |
| 501 |
|
| 502 |
else: |
| 503 |
self.options = makeOptionsFromDist(dist) |
| 504 |
|
| 505 |
def _validateOptions(self, value): |
| 506 |
"""returns False if value is not consistent with our |
| 507 |
enumerated options. |
| 508 |
|
| 509 |
Various null values always validate here; non-null checking is done |
| 510 |
by the column on its required attribute. |
| 511 |
""" |
| 512 |
if value=="None": |
| 513 |
assert False, "Literal 'None' passed as a value to validateOptions" |
| 514 |
|
| 515 |
if self.validValues is None: |
| 516 |
return True |
| 517 |
if self.caseless and value: |
| 518 |
value = value.lower() |
| 519 |
return value in self.validValues |
| 520 |
|
| 521 |
def _validateAtom(self, value): |
| 522 |
"""raises a ValidationError if value is incompatible with our constraints. |
| 523 |
""" |
| 524 |
if self.options and not self._validateOptions(value): |
| 525 |
raise base.ValidationError("Value '%s' is not consistent with" |
| 526 |
" legal values (%s)"%(value, ", ".join( |
| 527 |
sorted(str(o.content_) for o in self.options))), |
| 528 |
self.parent.name) |
| 529 |
|
| 530 |
# +/- Inf (and perhaps NaN) have special meanings and aren't |
| 531 |
# type cheked. |
| 532 |
if isinstance(value, float) and not math.isfinite(value): |
| 533 |
return |
| 534 |
|
| 535 |
if self.min and value<self.min_typed: |
| 536 |
raise base.ValidationError( |
| 537 |
f"{value} too small (must be at least {self.min})", |
| 538 |
self.parent.name) |
| 539 |
if self.max and value>self.max_typed: |
| 540 |
raise base.ValidationError( |
| 541 |
f"{value} too large (must be less than {self.max})", |
| 542 |
self.parent.name) |
| 543 |
|
| 544 |
def _validateInterval(self, value): |
| 545 |
"""raises a ValidationError if value doesn't have overlap with |
| 546 |
our min/max. |
| 547 |
""" |
| 548 |
if self.min and self.max and len(value)==2: |
| 549 |
# anything else should be caught elsewhere |
| 550 |
vmin, vmax = value |
| 551 |
if not (self.max_typed>=vmin and vmax>=self.min_typed): |
| 552 |
raise base.ValidationError(f"[{vmin}, {vmax}] has no overlaps" |
| 553 |
f" with {self.parent.name}'s range [{self.min_typed}," |
| 554 |
f" {self.max_typed}]", self.parent.name) |
| 555 |
return True |
| 556 |
return False |
| 557 |
|
| 558 |
def _validateCircle(self, value): |
| 559 |
"""raises a ValidationError if value doesn't have overlap with |
| 560 |
our circle limit. |
| 561 |
""" |
| 562 |
if self.max: |
| 563 |
p1, p2, radius = [float(v) for v in self.max.split()] |
| 564 |
# TODO: see if there's any overlap at all (by computing |
| 565 |
# the spherical distance and seeing if it's larger than r1+r2). |
| 566 |
# Me, I'm too grumpy right now. |
| 567 |
return True |
| 568 |
return False |
| 569 |
|
| 570 |
def _validatePolygon(self, value): |
| 571 |
"""raises a ValidationError if value doesn't have overlap with |
| 572 |
our polygon (max) limit. |
| 573 |
""" |
| 574 |
if self.max: |
| 575 |
# TODO: No, I won't compute polygon overlaps here. Sigh. |
| 576 |
return True |
| 577 |
return False |
| 578 |
|
| 579 |
def _validateXtype(self, value): |
| 580 |
"""raises a ValidationError if value isn't xtype-consistent with |
| 581 |
our constraints, and returns True if we believe we have validated |
| 582 |
anything at all. |
| 583 |
""" |
| 584 |
if self.parent.xtype=="interval": |
| 585 |
return self._validateInterval(value) |
| 586 |
elif self.parent.xtype=="circle": |
| 587 |
return self._validateCircle(value) |
| 588 |
elif self.parent.xtype=="polygon": |
| 589 |
return self._validatePolygon(value) |
| 590 |
return False |
| 591 |
|
| 592 |
def validateValue(self, value): |
| 593 |
"""raises a ValidationError if value is not consistent with our |
| 594 |
constraints. |
| 595 |
""" |
| 596 |
if self.actual: |
| 597 |
return |
| 598 |
|
| 599 |
# NULL checking is not our business (required is an attribute of |
| 600 |
# param/column). |
| 601 |
if value is None: |
| 602 |
return |
| 603 |
|
| 604 |
# The syntax-rich vexpr- and pql-types cannot be validated here. |
| 605 |
if (self.parent.type.startswith("pql-") |
| 606 |
or self.parent.type.startswith("vexpr-")): |
| 607 |
return |
| 608 |
|
| 609 |
if self._validateXtype(value): |
| 610 |
return |
| 611 |
|
| 612 |
if isinstance(value, (list, tuple, set)): |
| 613 |
for item in value: |
| 614 |
self._validateAtom(item) |
| 615 |
else: |
| 616 |
self._validateAtom(value) |
| 617 |
|
| 618 |
|
| 619 |
class ColumnBase(base.Structure, base.MetaMixin): |
| 620 |
"""A base class for columns, parameters, output fields, etc. |
| 621 |
|
| 622 |
Actually, right now there's far too much cruft in here that |
| 623 |
should go into Column proper or still somewhere else. Hence: |
| 624 |
XXX TODO: Refactor. |
| 625 |
|
| 626 |
See also Column for a docstring that still applies to all we've in |
| 627 |
here. |
| 628 |
""" |
| 629 |
_name = ParamNameAttribute("name", default=base.Undefined, |
| 630 |
description="Name of the param", |
| 631 |
copyable=True, before="type") |
| 632 |
_type = TypeNameAttribute("type", default="real", description= |
| 633 |
"datatype for the column (SQL-like type system)", |
| 634 |
copyable=True, before="unit") |
| 635 |
_unit = base.UnicodeAttribute("unit", default="", description= |
| 636 |
"Unit of the values. Use VOUnits syntax and use single quotes when" |
| 637 |
" you use custom units (you should avoid that).", |
| 638 |
copyable=True, before="ucd", strip=True) |
| 639 |
_ucd = base.UnicodeAttribute("ucd", default="", description= |
| 640 |
"UCD of the column", copyable=True, before="description") |
| 641 |
_description = base.NWUnicodeAttribute("description", |
| 642 |
default="", copyable=True, |
| 643 |
description="A short (one-line) description of the values in this column.") |
| 644 |
_tablehead = base.UnicodeAttribute("tablehead", default=None, |
| 645 |
description="Terse phrase to put into table headers for this" |
| 646 |
" column", copyable=True) |
| 647 |
_utype = base.UnicodeAttribute("utype", default=None, description= |
| 648 |
"utype for this column", copyable=True) |
| 649 |
_required = base.BooleanAttribute("required", default=False, |
| 650 |
description="Record becomes invalid when this column is NULL", |
| 651 |
copyable=True) |
| 652 |
_displayHint = DisplayHintAttribute("displayHint", |
| 653 |
description="Suggested presentation; the format is " |
| 654 |
" <kw>=<value>{,<kw>=<value>}, where what is interpreted depends" |
| 655 |
" on the output format. See, e.g., documentation on HTML renderers" |
| 656 |
" and the formatter child of outputFields.", copyable=True) |
| 657 |
_verbLevel = base.IntAttribute("verbLevel", default=20, |
| 658 |
description="Minimal verbosity level at which to include this column", |
| 659 |
copyable=True) |
| 660 |
_values = base.StructAttribute("values", default=None, |
| 661 |
childFactory=Values, description="Specification of legal values", |
| 662 |
copyable=True) |
| 663 |
_fixup = base.UnicodeAttribute("fixup", description= |
| 664 |
"A python expression the value of which will replace this column's" |
| 665 |
" value on database reads. Write a ___ to access the original" |
| 666 |
' value. You can use macros for the embedding table.' |
| 667 |
' This is for, e.g., simple URL generation' |
| 668 |
' (fixup="\'\\internallink{/this/svc}\'+___").' |
| 669 |
' It will *only* kick in when tuples are deserialized from the' |
| 670 |
" database, i.e., *not* for values taken from tables in memory.", |
| 671 |
default=None, copyable=True) |
| 672 |
_note = base.UnicodeAttribute("note", description="Reference to a note meta" |
| 673 |
" on this table explaining more about this column", default=None, |
| 674 |
copyable=True) |
| 675 |
_xtype = base.UnicodeAttribute("xtype", description="VOTable xtype giving" |
| 676 |
" the serialization form; you usually do *not* want to set this," |
| 677 |
" as the xtypes actually used are computed from database type." |
| 678 |
" DaCHS xtypes are only used for a few unsavoury, hopefully temporary," |
| 679 |
" hacks", default=None, copyable=True) |
| 680 |
_stc = TableManagedAttribute("stc", description="Internally used" |
| 681 |
" STC information for this column (do not assign to unless instructed" |
| 682 |
" to do so)", |
| 683 |
default=None, copyable=True) |
| 684 |
_stcUtype = TableManagedAttribute("stcUtype", description="Internally used" |
| 685 |
" STC information for this column (do not assign to)", |
| 686 |
default=None, copyable=True) |
| 687 |
_dmRoles = DMRolesAttribute("dmRoles", |
| 688 |
description="Roles played by this column; cannot be assigned to.") |
| 689 |
_properties = base.PropertyAttribute(copyable=True) |
| 690 |
_original = base.OriginalAttribute() |
| 691 |
|
| 692 |
restrictedMode = False |
| 693 |
|
| 694 |
def __repr__(self): |
| 695 |
return "<Column %s>"%repr(self.name) |
| 696 |
|
| 697 |
def setParent(self, parent): |
| 698 |
# overridden to turn off automatic meta parenting from MetaMixin. |
| 699 |
# This does not upcall on purpose. |
| 700 |
self.parent = parent |
| 701 |
|
| 702 |
def setMetaParent(self, parent): |
| 703 |
# columns should *not* take part in meta inheritance. The reason is |
| 704 |
# that there are usually many columns to a table, and there's no |
| 705 |
# way I can see that any piece of metadata should be repeated in |
| 706 |
# all of them. On the other hand, for votlinks (to name an example), |
| 707 |
# meta inheritance would have disastrous consequences. |
| 708 |
# So, we bend the rules a bit. |
| 709 |
raise base.StructureError("Columns may not have meta parents.", |
| 710 |
hint="The rationale for this is explained in rscdef/column.py," |
| 711 |
" look for setMetaParent.") |
| 712 |
|
| 713 |
def onParentComplete(self): |
| 714 |
# we need to resolve note on construction since columns are routinely |
| 715 |
# copied to other tables and meta info does not necessarily follow. |
| 716 |
if isinstance(self.note, str): |
| 717 |
try: |
| 718 |
self.note = self.parent.getNote(self.note) |
| 719 |
except base.NotFoundError: # non-existing notes silently ignored |
| 720 |
self.note = None |
| 721 |
|
| 722 |
def completeElement(self, ctx): |
| 723 |
self.restrictedMode = getattr(ctx, "restricted", False) |
| 724 |
if isinstance(self.name, utils.QuotedName): |
| 725 |
self.key = self.name.name |
| 726 |
if ')' in self.key: |
| 727 |
# No '()' allowed in key for that breaks the %()s syntax (sigh!). |
| 728 |
# Work around with the following quick hack that would break |
| 729 |
# if people carefully chose proper names. Anyone using delim. |
| 730 |
# ids in SQL deserves a good spanking anyway. |
| 731 |
self.key = self.key.replace(')', "__").replace('(', "__") |
| 732 |
else: |
| 733 |
self.key = self.name |
| 734 |
super().completeElement(ctx) |
| 735 |
|
| 736 |
def isEnumerated(self): |
| 737 |
return self.values and self.values.options |
| 738 |
|
| 739 |
def validate(self): |
| 740 |
super().validate() |
| 741 |
if self.restrictedMode and self.fixup: |
| 742 |
raise base.RestrictedElement("fixup") |
| 743 |
if self.xtype=="adql:TIMESTAMP": |
| 744 |
base.ui.notifyWarning("At %s: Do not use adql:TIMESTAMP xtype any more." |
| 745 |
" Simply drop xtype for timestamp and date-typed columns."%( |
| 746 |
self.getSourcePosition())) |
| 747 |
|
| 748 |
def validateValue(self, value): |
| 749 |
"""raises a ValidationError if value does not match the constraints |
| 750 |
given here. |
| 751 |
""" |
| 752 |
if value is None: |
| 753 |
if self.required: |
| 754 |
raise base.ValidationError( |
| 755 |
"Field %s is empty but non-optional"%self.name, self.name) |
| 756 |
return |
| 757 |
|
| 758 |
# Only validate these if we're not a database column |
| 759 |
if not isinstance(self, Column): |
| 760 |
if self.values: |
| 761 |
self.values.validateValue(value) |
| 762 |
|
| 763 |
|
| 764 |
def isIndexed(self): |
| 765 |
"""returns a set of index kinds if this column is indexed, False if |
| 766 |
it isn't or None if we don't know because we don't have a proper parent. |
| 767 |
|
| 768 |
In other words: it's a true value if the thing is indexed, a false |
| 769 |
one if it is. All further refinements are probably only there |
| 770 |
for more informed ADQL query morphing. |
| 771 |
""" |
| 772 |
if self.parent and hasattr(self.parent, "indexedColumns"): |
| 773 |
# parent is something like a TableDef |
| 774 |
return self.parent.indexedColumns.get(self.name, False) |
| 775 |
|
| 776 |
def isPrimary(self): |
| 777 |
"""returns a guess as to whether this column is a primary key of the |
| 778 |
embedding table. |
| 779 |
|
| 780 |
This may return True, False, or None (unknown). |
| 781 |
""" |
| 782 |
if self.parent and hasattr(self.parent, "primary"): |
| 783 |
# parent is something like a TableDef |
| 784 |
if self.name in self.parent.primary: |
| 785 |
return True |
| 786 |
else: |
| 787 |
return False |
| 788 |
|
| 789 |
def isScalar(self): |
| 790 |
"""returns true if we consider the array's values as scalar. |
| 791 |
|
| 792 |
A single string is scalar for us. |
| 793 |
""" |
| 794 |
type, arraysize, _ = self._getVOTableType() |
| 795 |
if type=="char" or type=="unicodeChar": |
| 796 |
return "x" not in arraysize |
| 797 |
else: |
| 798 |
return arraysize is None |
| 799 |
|
| 800 |
_indexedCleartext = { |
| 801 |
True: "indexed", |
| 802 |
False: "notIndexed", |
| 803 |
None: "unknown", |
| 804 |
} |
| 805 |
|
| 806 |
def asInfoDict(self): |
| 807 |
"""returns a dictionary of certain, "user-interesting" properties |
| 808 |
of the data field, in a dict of strings. |
| 809 |
""" |
| 810 |
return { |
| 811 |
"name": str(self.name), |
| 812 |
"type": self.type, |
| 813 |
"description": self.description or "N/A", |
| 814 |
"tablehead": self.getLabel(), |
| 815 |
"unit": self.unit or "N/A", |
| 816 |
"ucd": self.ucd or "N/A", |
| 817 |
"verbLevel": self.verbLevel, |
| 818 |
"indexState": self._indexedCleartext[bool(self.isIndexed())], |
| 819 |
"note": self.note, |
| 820 |
} |
| 821 |
|
| 822 |
def getDDL(self): |
| 823 |
"""returns an SQL fragment describing this column ready for |
| 824 |
inclusion in a DDL statement. |
| 825 |
""" |
| 826 |
type = base.sqltypeToPG(self.type) |
| 827 |
|
| 828 |
# The "str" does magic for delimited identifiers, so it's important. |
| 829 |
items = [str(self.name), type] |
| 830 |
if self.required: |
| 831 |
items.append("NOT NULL") |
| 832 |
return " ".join(items) |
| 833 |
|
| 834 |
def getDisplayHintAsString(self): |
| 835 |
return self._displayHint.unparse(self.displayHint) |
| 836 |
|
| 837 |
def getLabel(self): |
| 838 |
"""returns a short label for this column. |
| 839 |
|
| 840 |
The label is either the tablehead or, missing it, the capitalized |
| 841 |
column name. |
| 842 |
""" |
| 843 |
if self.tablehead is not None: |
| 844 |
return self.tablehead |
| 845 |
return str(self.key).capitalize() |
| 846 |
|
| 847 |
def getTAPName(self): |
| 848 |
"""returns self's name lowercased or with quotes, as is necessary |
| 849 |
for inclusion into the TAP schema. |
| 850 |
""" |
| 851 |
if isinstance(self.name, utils.QuotedName): |
| 852 |
return str(self.name) |
| 853 |
else: |
| 854 |
return self.name.lower() |
| 855 |
|
| 856 |
def _getVOTableType(self): |
| 857 |
"""returns the VOTable type, arraysize and xtype for this |
| 858 |
column-like thing. |
| 859 |
""" |
| 860 |
type, arraysize, xtype = base.sqltypeToVOTable(self.type) |
| 861 |
|
| 862 |
if self.type=="date": |
| 863 |
xtype = "dachs:DATE" |
| 864 |
|
| 865 |
return type, arraysize, xtype |
| 866 |
|
| 867 |
|
| 868 |
@base.buildstructure |
| 869 |
class Column(ColumnBase): |
| 870 |
"""A database column. |
| 871 |
|
| 872 |
Columns contain almost all metadata to describe a column in a database |
| 873 |
table or a VOTable (the exceptions are for column properties that may |
| 874 |
span several columns, most notably indices). |
| 875 |
|
| 876 |
Note that the type system adopted by the DaCHS is a subset |
| 877 |
of postgres' type system. Thus when defining types, you have to |
| 878 |
specify basically SQL types. Types for other type systems (like |
| 879 |
VOTable, XSD, or the software-internal representation in python values) |
| 880 |
are inferred from them. |
| 881 |
|
| 882 |
Columns can have delimited identifiers as names. Don't do this, it's |
| 883 |
no end of trouble. For this reason, however, you should not use name |
| 884 |
but rather key to programmatially obtain field's values from rows. |
| 885 |
|
| 886 |
Properties evaluated: |
| 887 |
|
| 888 |
- std -- set to 1 to tell the tap schema importer to have the column's |
| 889 |
std column in TAP_SCHEMA 1 (it's 0 otherwise). |
| 890 |
- statisticsTarget -- an integer to be set as this column's |
| 891 |
statistics-gathering target. Set this to something between 100 and |
| 892 |
10000 on postgres if you have large tables and columns with strongly |
| 893 |
non-uniform distributions. Set to -1 to revert to the system default. |
| 894 |
gavo imp -m will apply changes here; you'll manually have to run |
| 895 |
``analyze <tablename>`` after that. |
| 896 |
- statistics -- set this to "no" to keep DaCHS from using this column |
| 897 |
in dachs limits. Set this to "enumerate" to make DaCHS collect |
| 898 |
the discrete values allowed (currently only supported for strings). |
| 899 |
- targetType -- for a column containing a URL, the media type of the |
| 900 |
resource pointed at. This is for producing extra annotation for |
| 901 |
Aladin and friends as per |
| 902 |
http://mail.ivoa.net/pipermail/dal/2018-May/008017.html |
| 903 |
- targetTitle -- if you give targetType, use this to set the link |
| 904 |
title (defaults to "Link"). |
| 905 |
""" |
| 906 |
name_ = "column" |
| 907 |
|
| 908 |
_name = ColumnNameAttribute("name", default=base.Undefined, |
| 909 |
description="Name of the column", |
| 910 |
copyable=True, before="type") |
| 911 |
_hidden = base.BooleanAttribute("hidden", default=False, |
| 912 |
description="Hide the column from most of the user interface" |
| 913 |
" (specifically, you can't use it in TAP queries or results," |
| 914 |
" and it won't be in TAP_SCHEMA). You typically want this for" |
| 915 |
" internal, administrative columns.", copyable=True) |
| 916 |
_ignored = base.DataContent(description="Columns admit data" |
| 917 |
" content but ignore it. This is exclusively a convenience" |
| 918 |
" for building columns from params and should not be used for" |
| 919 |
" anything else.", copyable=False) |
| 920 |
|
| 921 |
def validate(self): |
| 922 |
super().validate() |
| 923 |
# Now check if we can serialize the column safely in VOTables. |
| 924 |
# I only want to hear about this when the column may end up in |
| 925 |
# a VOTable; |
| 926 |
if self.type in EXPLICIT_NULL_TYPES: |
| 927 |
if not self.required and not ( |
| 928 |
self.values and self.values.nullLiteral): |
| 929 |
try: |
| 930 |
pos = codetricks.stealVar("context").pos |
| 931 |
base.ui.notifyWarning("Somewhere near %s: " |
| 932 |
" Column %s may be null but has no explicit" |
| 933 |
" null value."%(pos, self.name)) |
| 934 |
except (ValueError, AttributeError): |
| 935 |
# This is stealVar's ValueError, we have no context in stack (or |
| 936 |
# it's a context var not from our parsing code). |
| 937 |
# Seems we're not parsing from a file, so the user probably |
| 938 |
# can't help it anyway. Don't complain. |
| 939 |
pass |
| 940 |
|
| 941 |
def getAnnotation(self, roleName, container, instance): |
| 942 |
if self.parent==container: |
| 943 |
return dm.ColumnAnnotation(roleName, self, instance) |
| 944 |
else: |
| 945 |
raise base.ReportableError("You cannot use columns from" |
| 946 |
" other tables in your DM annotations directly.", |
| 947 |
hint="If you really need something like this, you need to" |
| 948 |
" define a datatype corresponding to what's in the other table" |
| 949 |
" and reference a corresponding dm declaration.") |
| 950 |
|
| 951 |
def updateFromContext(self, tableId, columnName, ctx): |
| 952 |
"""pulls the injected column metadata from the context into our values. |
| 953 |
|
| 954 |
This is being called from table's completeElement -- only then |
| 955 |
is everything we depend on reasonably complete, and table |
| 956 |
knows better if we should even bother. |
| 957 |
""" |
| 958 |
statRow = ctx.getInjected(f"colstats:{tableId}:{columnName}", None) |
| 959 |
discDist = ctx.getInjected( |
| 960 |
f"discrete-strings:{tableId}:{columnName}", None) |
| 961 |
|
| 962 |
if not statRow and not discDist: |
| 963 |
return |
| 964 |
if not self.values: |
| 965 |
self.values = base.makeStruct(Values) |
| 966 |
|
| 967 |
if statRow: |
| 968 |
self.values.setFromStatRow(statRow, ctx) |
| 969 |
if discDist: |
| 970 |
self.values.setOptionsFromDict(discDist, ctx) |
| 971 |
|
| 972 |
def getStatistics(self): |
| 973 |
"""returns a dict with statistical information in this column's values. |
| 974 |
|
| 975 |
The values of this, for now, are strings, even for columns of other |
| 976 |
types. I think we should change this and parse these values according |
| 977 |
to the types. But is it worth it? |
| 978 |
""" |
| 979 |
res = {} |
| 980 |
if not self.values: |
| 981 |
return res |
| 982 |
|
| 983 |
for attName, colstatsName in [ |
| 984 |
("min", "minValue"), |
| 985 |
("max", "maxValue"), |
| 986 |
("median", "median"), |
| 987 |
("percentile03", "percentile03"), |
| 988 |
("percentile97", "percentile97"), |
| 989 |
("fillFactor", "fillFactor"),]: |
| 990 |
val = getattr(self.values, attName) |
| 991 |
if val is not None and val!="": |
| 992 |
res[colstatsName] = val |
| 993 |
|
| 994 |
return res |
| 995 |
|
| 996 |
def validateAgainstTAPSchema(self, tapDesc): |
| 997 |
"""yields mismatches between self's metdatadata and |
| 998 |
what is given in tapDesc. |
| 999 |
|
| 1000 |
tapDesc is a dict mapping to TAP_SCHEMA.columns-compliant |
| 1001 |
unit, ucd, datatype, arraysize and xtype. |
| 1002 |
|
| 1003 |
Special rule: if tapDesc is None, it will just report a missing column. |
| 1004 |
""" |
| 1005 |
if self.hidden: |
| 1006 |
# we are not in TAP_SCHEMA, so there is nothing to compare. |
| 1007 |
return |
| 1008 |
|
| 1009 |
if self.xtype=='adql:REGION': |
| 1010 |
# That's pathological. I'm hoping it'll die out and hence not |
| 1011 |
# monkey around with it. |
| 1012 |
return |
| 1013 |
|
| 1014 |
if not tapDesc: |
| 1015 |
yield f"Column {self.name} missing in TAP_SCHEMA" |
| 1016 |
return |
| 1017 |
|
| 1018 |
type, arraysize, xtype = base.sqltypeToVOTable(self.type) |
| 1019 |
for toCheck, attrName in [ |
| 1020 |
(type, "datatype"), |
| 1021 |
(arraysize, "arraysize"), |
| 1022 |
(xtype, "xtype"), |
| 1023 |
(self.ucd, "ucd"), |
| 1024 |
(self.unit, "unit")]: |
| 1025 |
if toCheck!=tapDesc[attrName]: |
| 1026 |
yield "Column {}: tap_schema {}!={}".format( |
| 1027 |
self.name, attrName, repr(toCheck)) |
| 1028 |
|
| 1029 |
|
| 1030 |
class ParamBase(ColumnBase): |
| 1031 |
"""A basic parameter. |
| 1032 |
|
| 1033 |
This is the base for both Param and InputKey. |
| 1034 |
""" |
| 1035 |
_value = base.DataContent(description="The value of parameter." |
| 1036 |
" It is parsed according to the param's type using the default" |
| 1037 |
" parser for the type VOTable tabledata.", default=base.NotGiven, |
| 1038 |
copyable=True, expand=True) |
| 1039 |
|
| 1040 |
_valueCache = base.Undefined |
| 1041 |
__contentStore = base.NotGiven |
| 1042 |
|
| 1043 |
nullLiteral = "" |
| 1044 |
|
| 1045 |
unprocessedTypes = set(["raw", "file"]) |
| 1046 |
|
| 1047 |
def __repr__(self): |
| 1048 |
try: |
| 1049 |
contentSer = repr(self.content_) |
| 1050 |
except: |
| 1051 |
contentSer = "<not serialisable>" |
| 1052 |
return f"<{self.__class__.__name__}, {self.name}={contentSer}>" |
| 1053 |
|
| 1054 |
def __set_content(self, val): |
| 1055 |
self.__contentStore = val |
| 1056 |
|
| 1057 |
def __get_content(self): |
| 1058 |
if (self.__contentStore is base.NotGiven |
| 1059 |
and self._valueCache is not base.Undefined): |
| 1060 |
self.__contentStore = self._unparse(self._valueCache) |
| 1061 |
return self.__contentStore |
| 1062 |
|
| 1063 |
content_ = property(__get_content, __set_content) |
| 1064 |
|
| 1065 |
def expand(self, value): |
| 1066 |
"""hands up macro expansion requests to a parent, if there is one |
| 1067 |
and it can handle expansions. |
| 1068 |
""" |
| 1069 |
if hasattr(self.parent, "expand"): |
| 1070 |
return self.parent.expand(value) |
| 1071 |
return value |
| 1072 |
|
| 1073 |
def completeElement(self, ctx): |
| 1074 |
if not self.values: |
| 1075 |
self.values = base.makeStruct(Values, parent_=self) |
| 1076 |
super().completeElement(ctx) |
| 1077 |
|
| 1078 |
def onElementComplete(self): |
| 1079 |
super().onElementComplete() |
| 1080 |
if self.content_ is base.NotGiven: |
| 1081 |
if self.values.default is not None: |
| 1082 |
self.set(self.values.default) |
| 1083 |
else: |
| 1084 |
self.set(self.content_) |
| 1085 |
|
| 1086 |
@property |
| 1087 |
def value(self): |
| 1088 |
"""returns a typed value for the parameter. |
| 1089 |
|
| 1090 |
Unset items give None here. |
| 1091 |
""" |
| 1092 |
if self._valueCache is base.Undefined: |
| 1093 |
if self.content_ is base.NotGiven: |
| 1094 |
self._valueCache = None |
| 1095 |
else: |
| 1096 |
self._valueCache = self._parse(self.content_) |
| 1097 |
return self._valueCache |
| 1098 |
|
| 1099 |
def getStringValue(self): |
| 1100 |
"""returns a string serialisation of the value. |
| 1101 |
|
| 1102 |
This is what would reproduce the value if embedded in an XML |
| 1103 |
serialisation of the param. |
| 1104 |
""" |
| 1105 |
if self.type in self.unprocessedTypes: |
| 1106 |
return "(Unrepresentable %s)"%self.type |
| 1107 |
return self.content_ |
| 1108 |
|
| 1109 |
def set(self, val): |
| 1110 |
"""sets this parameter's value. |
| 1111 |
|
| 1112 |
val can be a python value, or string literal. In the second |
| 1113 |
case, this string literal will be preserved in string serializations |
| 1114 |
of this param. |
| 1115 |
|
| 1116 |
If val is an invalid value for this item, a ValidationError is |
| 1117 |
raised and the item's value will be Undefined. |
| 1118 |
""" |
| 1119 |
if isinstance(val, str): |
| 1120 |
self.content_ = val |
| 1121 |
else: |
| 1122 |
self.content_ = base.NotGiven |
| 1123 |
try: |
| 1124 |
newVal = self._parse(val) |
| 1125 |
self._valueCache = newVal |
| 1126 |
except votable.BadVOTableLiteral as ex: |
| 1127 |
raise base.ui.logOldExc(base.ValidationError( |
| 1128 |
f"Invalid literal for {self.name}: {val} ({ex})", |
| 1129 |
self.name)) |
| 1130 |
|
| 1131 |
|
| 1132 |
def _parse(self, literal, atom=False): |
| 1133 |
"""parses literal using the default value parser for this param's |
| 1134 |
type. |
| 1135 |
|
| 1136 |
If literal is not a string, it will be returned unchanged. |
| 1137 |
|
| 1138 |
The method also makes sure literal matches any constraints |
| 1139 |
set by a values child and raises a ValidationError if not. |
| 1140 |
""" |
| 1141 |
if self.type in self.unprocessedTypes: |
| 1142 |
return literal |
| 1143 |
|
| 1144 |
elif not isinstance(literal, str): |
| 1145 |
return literal |
| 1146 |
|
| 1147 |
elif literal=="__NULL__" or literal=="": |
| 1148 |
value = None |
| 1149 |
|
| 1150 |
elif ((self.type=="text" or self.type=="unicode") |
| 1151 |
and literal=="__EMPTY__"): |
| 1152 |
value = "" |
| 1153 |
|
| 1154 |
else: |
| 1155 |
if literal==self.values.nullLiteral: |
| 1156 |
value = None |
| 1157 |
else: |
| 1158 |
try: |
| 1159 |
type, arraysize, xtype = self._getVOTableType() |
| 1160 |
if atom: |
| 1161 |
arraysize = None |
| 1162 |
|
| 1163 |
if type not in ["char", "unicodeChar"]: |
| 1164 |
literal = literal.strip() |
| 1165 |
|
| 1166 |
if self.xtype=="interval": |
| 1167 |
# prefer interval datatype over anything user-specified, |
| 1168 |
# and do special magic on xtype collision |
| 1169 |
if self.type=="timestamp": |
| 1170 |
type = "timestamp-interval" |
| 1171 |
else: |
| 1172 |
xtype = xtype or self.xtype |
| 1173 |
else: |
| 1174 |
xtype = self.xtype or xtype |
| 1175 |
|
| 1176 |
value = votable.getVOTParser(type, arraysize, xtype)(literal) |
| 1177 |
# make NaNs NULL here for consistent VOTable practice |
| 1178 |
if value!=value: |
| 1179 |
value = None |
| 1180 |
except ValueError: |
| 1181 |
raise base.ValidationError("%s is not a valid literal for %s"%( |
| 1182 |
repr(literal), self.name), self.name) |
| 1183 |
|
| 1184 |
self.values.validateValue(value) |
| 1185 |
|
| 1186 |
# unify NULL value representation to the empty string |
| 1187 |
if value is None: |
| 1188 |
self.content_ = "" |
| 1189 |
|
| 1190 |
return value |
| 1191 |
|
| 1192 |
def _unparse(self, value): |
| 1193 |
"""returns a string representation of value appropriate for this |
| 1194 |
type. |
| 1195 |
|
| 1196 |
Actually, for certain types only handled internally (like file or raw), |
| 1197 |
this is not a string representation at all but just the python stuff. |
| 1198 |
|
| 1199 |
Plus, right now, for sequences we're not doing anything. We probably |
| 1200 |
should; but we'll need to be much more careful in ContextGramar then. |
| 1201 |
""" |
| 1202 |
if self.type in self.unprocessedTypes: |
| 1203 |
return value |
| 1204 |
|
| 1205 |
if value is None: |
| 1206 |
return "" |
| 1207 |
else: |
| 1208 |
type, arraysize, xtype = self._getVOTableType() |
| 1209 |
|
| 1210 |
# deal as gracefully as possible with xtype collisions, and |
| 1211 |
# prefer manually set xtype if possible |
| 1212 |
if xtype and not "interval" in xtype: |
| 1213 |
xtype = self.xtype or xtype |
| 1214 |
else: |
| 1215 |
xtype = xtype or self.xtype |
| 1216 |
|
| 1217 |
val = votable.getVOTSerializer(type, arraysize, xtype)(value) |
| 1218 |
return val |
| 1219 |
|
| 1220 |
|
| 1221 |
class Param(ParamBase): |
| 1222 |
"""A table parameter. |
| 1223 |
|
| 1224 |
This is like a column, except that it conceptually applies to all |
| 1225 |
rows in the table. In VOTables, params will be rendered as |
| 1226 |
PARAMs. |
| 1227 |
|
| 1228 |
While we validate the values passed using the DaCHS default parsers, |
| 1229 |
at least the VOTable params will be literal copies of the string |
| 1230 |
passed in. |
| 1231 |
|
| 1232 |
You can obtain a parsed value from the value attribute. |
| 1233 |
|
| 1234 |
Null value handling is a bit tricky with params. An empty param (like |
| 1235 |
``<param name="x"/>)`` is always NULL (None in python). |
| 1236 |
In order to allow setting NULL even where syntactially something has |
| 1237 |
to stand, we also turn any __NULL__ to None. |
| 1238 |
|
| 1239 |
For floats, NaN will also yield NULLs. For integers, you can also |
| 1240 |
use |
| 1241 |
|
| 1242 |
<param name="x" type="integer"><values nullLiteral="-1"/>-1</params> |
| 1243 |
|
| 1244 |
For arrays, floats, and strings, the interpretation of values is |
| 1245 |
undefined. Following VOTable practice, we do not tell empty strings and |
| 1246 |
NULLs apart; for internal usage, there is a little hack: __EMPTY__ as literal |
| 1247 |
does set an empty string. This is to allow defaulting of empty strings -- in |
| 1248 |
VOTables, these cannot be distinguished from "true" NULLs. |
| 1249 |
""" |
| 1250 |
name_ = "param" |
| 1251 |
|
| 1252 |
_hidden = base.BooleanAttribute("hidden", default=False, |
| 1253 |
description="Ignored on params, just present for constructor compatibility" |
| 1254 |
" with column") |
| 1255 |
|
| 1256 |
def validate(self): |
| 1257 |
super().validate() |
| 1258 |
if self.content_ is base.NotGiven: |
| 1259 |
self.set(None) |
| 1260 |
|
| 1261 |
if self.required and self.value is None: |
| 1262 |
raise base.StructureError("Required value not given for param" |
| 1263 |
" %s"%self.name) |
| 1264 |
|
| 1265 |
try: |
| 1266 |
# the value property will bomb on malformed literals |
| 1267 |
self.value |
| 1268 |
except ValueError as msg: |
| 1269 |
raise base.LiteralParseError(self.name, self.content_, |
| 1270 |
hint="Param content must be parseable as in VOTable TABLEDATA." |
| 1271 |
" The value you passed caused the error: %s"%msg) |
| 1272 |
|
| 1273 |
def set(self, val): |
| 1274 |
"""sets the value of the parameter. |
| 1275 |
|
| 1276 |
Macros will be expanded if the parent object supports macro |
| 1277 |
expansion. |
| 1278 |
""" |
| 1279 |
if (isinstance(val, str) |
| 1280 |
and "\\" in val |
| 1281 |
and hasattr(self.parent, "expand")): |
| 1282 |
val = self.parent.expand(val) |
| 1283 |
return ParamBase.set(self, val) |
| 1284 |
|
| 1285 |
def getAnnotation(self, roleName, container, instance): |
| 1286 |
"""returns a dm annotation for this param (i.e., a paramRef). |
| 1287 |
""" |
| 1288 |
# TODO: Figure out how to make sure that this param actually |
| 1289 |
# ends up in the target VOTable. Or do we want to enforce |
| 1290 |
# params to be within the table? |
| 1291 |
return dm.ParamAnnotation(roleName, self, instance) |
| 1292 |
|
| 1293 |
def copy(self, parent, ctx=None): |
| 1294 |
# overridden so we can set originalParent, which in turn we need |
| 1295 |
# in DM serialisation to VOTables |
| 1296 |
newInstance = super().copy(parent, ctx) |
| 1297 |
newInstance.originalParam = self |
| 1298 |
return newInstance |