DaCHS predefined procedures. Whatever is in here
will also end up in the reference documentation, so that's where you
should look if you just want to use this.
Print the current row to standard output.
This is the equivalent of the printf-debugger. It is much like the
-d command line switch to gavo imp, but you can see the effects
of row filters, var settings, potentially earlier proc applications, etc.
print vars
Give a python debugger prompt.
This drops you in the python debugger. See vars for what's coming
from the grammar, result for what's been mapped at this point.
Type cont to continue.
import pdb; pdb.set_trace()
Fill variables from a simple database query.
The idea is to obtain a set of values from the data base into some
columns within vars (i.e., available for mapping) based on comparing
a single input value against a database column. The query should
always return exactly one row. If more rows are returned, the
first one will be used (which makes the whole thing a bit of a gamble),
if none are returned, a ValidationError is raised.
:}"]]>'<unknown>'
assignments = utils.parseAssignments(assignments)
dbNames, recNames = assignments.keys(), assignments.values()
query = "SELECT %s FROM %s WHERE %s=%%(val)s"%(
", ".join(dbNames), table, column)
def parseDestWithDefault(dest, defRe=re.compile(r"(\w+)\((.*)\)")):
"""returns name, default from dests like bla(0).
This can be used to provide defaulted targets to assignments parsed
with _parseAssignments.
"""
mat = defRe.match(dest)
if mat:
return mat.groups()
else:
return dest, None
")
]]>TrueFalse
from gavo.protocols import simbadinterface
resolver = simbadinterface.Sesame()
Resolve identifiers to simbad positions.
It caches query results (positive as well as negative ones) in
cacheDir. To avoid flooding simbad with repetitive requests, it
raises an error if this directory is not writable.
It leaves J2000.0 positions as floats in the simbadAlpha and
simbadDelta variables.
ra, dec = None, None
try:
ra, dec = resolver.getPositionFor(identifier)
except KeyError:
if logUnknowns:
base.ui.notifyInfo("Identifier did not resolve: %s"%identifier)
if not ignoreUnknowns:
raise base.Error("resolveObject could not resolve object"
" %s."%identifier)
vars["simbadAlpha"] = ra
vars["simbadDelta"] = dec
where source keys is a whitespace-seperated list of values that should
be mapped to target key (sorry the sequence's a bit unusual).
A source key must be encoded quoted-printable. This usually doesn't
matter except when it contains whitespace (a blank becomes =20) or equal
signs (which become =3D).
Here's an example application for a filter that's supposed to translate
some botched object names::
"cleanedObject"True@preObject"flashheros/res/namefixes.txt"
The input could look like this, with a Tab char written as " "
for clarity::
alp Cyg aCyg alphaCyg
Nova Cygni 1992 Nova=20Cygni=20'92 Nova=20Cygni
]]>FalseFalseFalse
map = utils.NameMap(os.path.join(
base.getConfig("inputsDir"), sourceName))
try:
vars[destination] = map.resolve(str(value))
except KeyError:
if logFailures:
base.ui.notifyWarning("Name %s could not be mapped\n"%value)
if failuresAreNone:
vars[destination] = None
elif failuresMapThrough:
vars[destination] = value
else:
raise base.LiteralParseError(destination, value,
hint="It's not in the keys of the underlying map, which are: "+
(" ".join(map.namesDict)))
'<unknown>'
with base.getTableConn() as conn:
cursor = conn.query(query, locals())
keys = [f[0] for f in cursor.description]
res = list(cursor)
if not res:
raise base.ValidationError("Could not find a matching row",
errCol)
vars.update(dict(zip(keys, res[0])))
Maps input values through a dictionary.
The dictionary is given in its python form here. This apply
only operates on the rawdict, i.e., the value in vars is changed,
while nothing is changed in the rowdict.
KeyError
def doTheMap(vars):
newVal = mapping.get(vars[key], default)
if newVal is KeyError:
raise base.ValidationError("dictMap saw %s, which it was"
" not prepared to see."%repr(vars[key]),
colName=key,
hint="This dictMap knows the keys %s"%mapping.keys())
elif newVal is base.NotGiven:
newVal = vars[key]
vars[key] = newVal
doTheMap(vars)
A row processor that produces copies of rows based on integer indices.
The idea is that sometimes rows have specifications like "Star 10
through Star 100". These are a pain if untreated. A RowExpander
could create 90 individual rows from this.
try:
lowerInd = int(row[startName])
upperInd = int(row[endName])
except (ValueError, TypeError): # either one not given
yield row
return
for ind in range(lowerInd, upperInd+1):
newRow = row.copy()
newRow[indName] = ind
yield newRow
Since this is probably only use useful with inputDDs, we will
probably remove this soon unless you protest.
is a row generator to expand time ranges.
The finished dates are left in destination as datetime.datetime
instances
'curTime'24
def _parseTime(val, fieldName):
try:
val = val
if isinstance(val, datetime.datetime):
return val
elif isinstance(val, datetime.date):
return datetime.datetime(val.year, val.month, val.day)
else:
return utils.parseISODT(val)
except Exception, msg:
raise base.ValidationError("Bad date from %s (%s)"%(fieldName,
unicode(msg)), dest)
A row generator that reads comma separated values from a
field and returns one row with a new field for each of them.
src = row[srcField]
if src is not None and src.strip():
for item in src.split(","):
item = item.strip()
if not item:
continue
newRow = row.copy()
newRow[destField] = item
yield newRow
A phraseMaker that makes a pair of inputKeys into a range query,
possibly half-open.
The name of the column queried can be passed in the late parameter
colName; the default is the name of the first inputKey minus the
last four characters. This looks weird but complements the
rangeCondDesc stream below.
inputKeys[0].name[:-4]=%%(%s)s"%(colName,
base.getSQLKey(minKey.name, minVal, outPars))
else:
yield "%s BETWEEN %%(%s)s AND %%(%s)s"%(colName,
base.getSQLKey(minKey.name, minVal, outPars),
base.getSQLKey(maxKey.name, maxVal, outPars))
]]>
A condDesc that expresses a range and has an InputKey each for min
and max.
Specify the following macros when replaying:
* name -- the column name in the core's queried table
* groupdesc -- a terse phrase describing the range. This will be
used in the description of both the input keys and the group
* grouplabel -- a label (include the unit, it is not taken from InputKey)
written in front of the form group
groupdesc has to work after "Range of", "Lower bound of", and
"Upper bound of". Do not include a concluding period.
formkey_minformkey_maxRange of \groupdesc. If you only specify one bound,
you get a half-infinite interval.\grouplabelcompact
A condDesc over a boolean column.
By default, DaCHS does not distinguish between False and NULL when
auto-generating input keys from boolean columns. That is, you can
check a checkbox and will get everything where the column is
true. If you do not check it, however, you will get everything, i.e.,
rows in which the column is any of NULL, True, or False. That's pretty
much the semantics of HTML checkboxes.
However, when you want people to be able to explicitly say “this should
be off“, you need to be a bit more cunning. That is what this
stream does; when you have a boolean column ``my_bool``, you can
have::
<FEED source="//procs#negatableBoolean" column="my_bool"/>
next to your other condDescs in the dbCore. This will then
produce a three-way selection between Yes, No, and ANY.
colName = inputKeys[0].name
val = inPars[colName]
if val=="No":
yield f"NOT {colName}"
elif val=="Yes":
yield f"{colName}"
# Fall though: Ignore the input (that includes the ANY option)
Include this stream with a @what (a short phrase saying what
is released) to make your resource released under Creative
Commons-0 (a.k.a. public domain). This will generate the
rights and rightsURI metadata items. It needs to live in the
toplevel /resource element.
Example::
<FEED source="//procs#license-cc0" what="the HSOY catalogue"/>
\\RSTcc0{\what}
https://spdx.org/licenses/CC0-1.0.html
Include this stream with a @what (a short phrase saying what
is licensed) to make your resource licensed under Creative
Commons Attribution (CC-BY). This will generate the
rights and rightsURI metadata items. It needs to live in the
toplevel /resource element.
Example::
<FEED source="//procs#license-cc-by" what="the HSOY catalogue"/>
\\RSTccby{\what}
https://spdx.org/licenses/CC-BY-4.0.html
Include this stream with a @what (a short phrase saying what
is licensed) to make your resource licensed under Creative
Commons Attribution Share Alike (CC-BY-SA). This will generate
the rights and rightsURI metadata items. It needs
to live in the toplevel /resource element.
Example::
<FEED source="//procs#license-cc-by-sa" what="the HSOY catalogue"/>
\\RSTccbysa{\what}
https://spdx.org/licenses/CC-BY-SA-4.0.html
Tells DaCHS to copy the index declarations from tables a view
derives from (meaning; feeding this probably does not make any sense
outside of a view declaration).
Since DaCHS does not have a good way to guess which tables you derive from
(in the end), you have to give blank-separated RD#id references to them in
the sourceTables attribute.
The proc will declare all indexes over columns that appear to be in the
View (by name). That's a rough heuristics which works in most cases. If
it doesn't work for you, you can always declare the indexes manually.
Note that this will only see columns that are declared lexically
before the FEED; you will thus typically want to include this at
the end of the view definition.
Example::
<FEED source="//procs#declare-indexes-from"
sourceTables="res1/q#table1 res14#othertable"/>
from gavo import rscdef
for td in [
context.resolveId(otherId, forceType=rscdef.TableDef)
for otherId in \quote{\sourceTables}.split()]:
for index in td.indices:
for colName in index.columns:
if colName not in context.replayTarget.columns:
break
else:
# All columns in the index are seen in the view: yield
# the index metadata
if not index.columns:
from gavo import base
base.ui.notifyWarning(
f"While copying indexes from {td.getFullId()}: Index"
f" {index.name} has no columns. Ignoring.")
continue
yield {
"columns": ",".join(index.columns),
"kind": index.kind,
"metaOnly": "True",
}
and you get a reasonably defined column err_ for almost
free. Plus, if one day we have proper annotation for value/error
pairs, DaCHS will spit that out, too.
This stream has the common attributes of column as parameters:
name, type, unit, ucd, tablehead, description, and verbLevel.
Errors are always verbLevel at this point. The minimum you have to
define is name and description.
]]>