Debian Codegraph @

gavo/svcs/vizierexprs.py

raw
1 """
2 Classes and methods to support vizier-type specifications on 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 datetime
12 import re
13
14
15 from gavo import base
16 from gavo import stc
17 from gavo import utils
18 from gavo.base import literals
19 from gavo.base import sqlmunge
20 from gavo.base import typesystems
21 from gavo.utils.parsetricks import (Word, Literal, Optional, Forward,
22 ZeroOrMore, Suppress, ParseException, StringEnd, Regex,
23 OneOrMore, CharsNotIn, pyparsingWhitechars)
24
25
26 class ParseNode(object):
27 """is a parse node, consisting of an operator and children.
28
29 The parse trees returned by the various parse functions are built from
30 these.
31
32 This is an abstract class.
33 """
34 def __init__(self, children, operator):
35 self.children = children
36 self.operator = operator
37
38 def __str__(self):
39 return "(%s %s)"%(self.operator, " ".join([str(c) for c in self.children]))
40
41 def __repr__(self):
42 return "(%r %r)"%(self.operator, " ".join([str(c) for c in self.children]))
43
44 def getSQLKey(self, name, item, sqlPars):
45 """wraps base.getSQLKey and can be overridden in case operand
46 mangling is necessary.
47
48 Do not call base.getSQLKey directly from within ParseNodes.
49 """
50 return base.getSQLKey(name, item, sqlPars)
51
52 def insertChild(self, index, field, sqlPars):
53 """inserts children[index] into sqlPars with a unique key and returns
54 the key.
55
56 children[index] must be atomic (i.e., no ParseNode).
57 """
58 item = self.children[index]
59 if item is None:
60 return None
61 assert not isinstance(item, ParseNode)
62 if getattr(field, "scaling", None):
63 item *= field.scaling
64 return self.getSQLKey(field.name, item, sqlPars)
65
66
67
68 class NumericNode(ParseNode):
69 """A node containing numeric operands (floats or dates).
70 """
71
72
73 class DateNode(ParseNode):
74 """A node containing date operands (datetime objects, as a rule).
75
76 As an extension to VizieR, we interpret floats as well, where
77 1000 .. 3000 is a julian year, 10000 ... 100000 is an MJD and
78 2000000 .. 4000000 is a JD.
79 """
80
81
82 class MJDNode(DateNode):
83 def getSQLKey(self, name, item, sqlPars):
84 if (isinstance(item, datetime.datetime)
85 or isinstance(item, datetime.date)):
86 item = stc.dateTimeToMJD(item)
87 return base.getSQLKey(name, item, sqlPars)
88
89
90 class StringNode(ParseNode):
91 """A node containing string operands.
92 """
93
94
95 def _getNodeFactory(op, nodeClass):
96 def _(s, loc, toks):
97 return nodeClass(toks, op)
98 return _
99
100
101 def _makeNotNodeFactory(nodeClass):
102 def _makeNotNode(s, loc, toks):
103 if len(toks)==1:
104 return toks[0]
105 elif len(toks)==2:
106 return nodeClass(toks[1:], "NOT")
107 else: # Can't happen :-)
108 raise Exception("Busted by not")
109 return _makeNotNode
110
111
112 def makePmNode(s, loc, toks):
113 return NumericNode([toks[0]-toks[1], toks[0]+toks[1]], "..")
114
115
116 def makeDatePmNode(s, loc, toks):
117 """returns a +/- node for dates, i.e., toks[1] is a float in days.
118 """
119 days = datetime.timedelta(days=toks[1])
120 return DateNode([toks[0]-days, toks[0]+days], "..")
121
122 def makeMJDPmNode(s, loc, toks):
123 """returns a +/- node for MJDs, i.e., toks[1] is a float in days, and
124 an MJDNode must be returned.
125 """
126 days = datetime.timedelta(days=toks[1])
127 return MJDNode([toks[0]-days, toks[0]+days], "..")
128
129
130 def _getBinopFactory(op, nodeClass):
131 def _(s, loc, toks):
132 if len(toks)==1:
133 return toks[0]
134 else:
135 return nodeClass(toks, op)
136 return _
137
138
139 def _simpleExprFactory(nodeClass):
140 def _makeSimpleExprNode(s, loc, toks):
141 if len(toks)==1:
142 return nodeClass(toks[0:], "=")
143 else:
144 return nodeClass(toks[1:], toks[0])
145 return _makeSimpleExprNode
146
147
148 def getComplexGrammar(baseLiteral, pmBuilder, errorLiteral=None,
149 nodeClass=NumericNode):
150 """returns the root element of a grammar parsing numeric vizier-like
151 expressions.
152
153 This is used for both dates and floats, use baseLiteral to match the
154 operand terminal. The trouble with dates is that the +/- operator
155 has a simple float as the second operand, and that's why you can
156 pass in an errorLiteral and and pmBuilder.
157 """
158 if errorLiteral is None:
159 errorLiteral = baseLiteral
160
161 with pyparsingWhitechars(" \t"):
162 preOp = Literal("=") | Literal(">=") | Literal(">"
163 ) | Literal("<=") | Literal("<")
164 rangeOp = Literal("..")
165 pmOp = Literal("+/-") | Literal("\xb1")
166 orOp = Literal("|")
167 andOp = Literal("&")
168 notOp = Literal("!")
169 commaOp = Literal(",")
170
171 preopExpr = Optional(preOp) + baseLiteral
172 rangeExpr = baseLiteral + Suppress(rangeOp) + baseLiteral
173 valList = baseLiteral + OneOrMore( Suppress(commaOp) + baseLiteral)
174 pmExpr = baseLiteral + Suppress(pmOp) + errorLiteral
175 simpleExpr = rangeExpr | pmExpr | valList | preopExpr
176
177 expr = Forward()
178
179 notExpr = Optional(notOp) + simpleExpr
180 andExpr = notExpr + ZeroOrMore( Suppress(andOp) + notExpr )
181 orExpr = andExpr + ZeroOrMore( Suppress(orOp) + expr)
182 expr << orExpr
183 exprInString = expr + StringEnd()
184
185 rangeExpr.setName("rangeEx")
186 rangeOp.setName("rangeOp")
187 notExpr.setName("notEx")
188 andExpr.setName("andEx")
189 andOp.setName("&")
190 orExpr.setName("orEx")
191 expr.setName("expr")
192 simpleExpr.setName("simpleEx")
193
194 preopExpr.addParseAction(_simpleExprFactory(nodeClass))
195 rangeExpr.addParseAction(_getNodeFactory("..", nodeClass))
196 pmExpr.addParseAction(pmBuilder)
197 valList.addParseAction(_getNodeFactory(",", nodeClass))
198 notExpr.addParseAction(_makeNotNodeFactory(nodeClass))
199 andExpr.addParseAction(_getBinopFactory("AND", nodeClass))
200 orExpr.addParseAction(_getBinopFactory("OR", nodeClass))
201
202 return exprInString
203
204
205 def parseFloat(s, pos, tok):
206 # If something looks like an int, return it as an int.
207 # Otherwise, postgres won't use int-indices
208 try:
209 return int(tok[0])
210 except ValueError:
211 return float(tok[0])
212
213
214 def parseDateTime(s, pos, tok):
215 """returns a datetime from a date/time spec.
216
217 This can be an ISO string or a julian year, JD, or MJD by
218 heuristics (see DateNode for details).
219 """
220 assert len(tok)==1
221 try:
222 floatVal = float(tok[0])
223 if 1000<=floatVal<=3000:
224 return utils.roundToSeconds(stc.jYearToDateTime(floatVal))
225 elif 10000<=floatVal<=100000:
226 return utils.roundToSeconds(stc.mjdToDateTime(floatVal))
227 elif 2e6<=floatVal<=4e6:
228 return utils.roundToSeconds(stc.jdnToDateTime(floatVal))
229 else:
230 raise base.ParseException("Floats as dates must be "
231 " credible years (1000..2000), MJDs (1e4 .. 1e5), or"
232 " JDs (2e6 .. 4e6)")
233 except ValueError:
234 return literals.parseDefaultDatetime(tok[0])
235
236
237 floatLiteral = Regex(utils.floatRE).addParseAction(parseFloat)
238
239 _DATE_REGEX = r"\d\d\d\d-\d\d-\d\d(T\d\d:\d\d:\d\d(\.\d*)?)?|(\d+(\.\d*)?)"
240 _DATE_LITERAL_DT = Regex(_DATE_REGEX).addParseAction(parseDateTime)
241
242
243 def parseNumericExpr(str, baseSymbol=getComplexGrammar(floatLiteral,
244 makePmNode)):
245 """returns a parse tree for vizier-like expressions over floats.
246 """
247 return utils.pyparseString(baseSymbol, str)[0]
248
249
250 def parseDateExpr(str, baseSymbol=getComplexGrammar(_DATE_LITERAL_DT,
251 makeDatePmNode, floatLiteral, DateNode)):
252 """returns a parse tree for vizier-like expressions over ISO dates.
253
254 Note that the semantic validity of the date (like, month<13) is not
255 checked by the grammar.
256 """
257 return utils.pyparseString(baseSymbol, str)[0]
258
259
260 def parseDateExprToMJD(str, baseSymbol=getComplexGrammar(_DATE_LITERAL_DT,
261 makeMJDPmNode, floatLiteral, MJDNode)):
262 """returns a parse tree for vizier-like expression of ISO dates with
263 parsed values in MJD.
264 """
265 return utils.pyparseString(baseSymbol, str)[0]
266
267
268 def _makeOpNode(s, loc, toks):
269 return StringNode(toks[1:], toks[0])
270
271
272 def getStringGrammar():
273 """returns a grammar for parsing vizier-like string expressions.
274 """
275 # XXX TODO: should we cut at =| (which is currently parsed as = |)?
276 with pyparsingWhitechars(" \t"):
277 simpleOperator = Literal("==") | Literal("!=") | Literal(">=") |\
278 Literal(">") | Literal("<=") | Literal("<") | Literal("=~") |\
279 Literal("=,")
280 simpleOperand = Regex(r"[^\s].*|")
281 # XXX probably a bug in pyparsing: White shouldn't be necessary here
282 White = Word(" \t")
283 simpleExpr = simpleOperator + Optional( White ) + simpleOperand
284
285 commaOperand = Regex("[^,]+")
286 barOperand = Regex("[^|]+")
287 commaEnum = Literal("=,") + commaOperand + ZeroOrMore(
288 Suppress(",") + commaOperand)
289 exclusionEnum = Literal("!=,") + commaOperand + ZeroOrMore(
290 Suppress(",") + commaOperand)
291 barEnum = Literal("=|") + barOperand + ZeroOrMore(
292 Suppress("|") + barOperand)
293 enumExpr = exclusionEnum | commaEnum | barEnum
294
295 patLiterals = CharsNotIn("[*?")
296 wildStar = Literal("*")
297 wildQmark = Literal("?")
298 setElems = CharsNotIn("]")
299 setSpec = Suppress("[") + setElems + Suppress("]")
300 pattern = OneOrMore(setSpec | wildStar | wildQmark | patLiterals)
301
302 patternOperator = Literal("~") | Literal("=") | Literal("!~") |\
303 Literal("!")
304 patternExpr = patternOperator + Optional( White ) + pattern
305 nakedExpr = Regex("[^=!~|><]") + Optional( simpleOperand )
306
307 stringExpr = enumExpr | simpleExpr | patternExpr | nakedExpr
308
309 doc = stringExpr + StringEnd()
310
311 stringExpr.setName("StringExpr")
312 enumExpr.setName("EnumExpr")
313 simpleOperand.setName("Operand")
314 simpleOperator.setName("Operator")
315 nakedExpr.setName("SingleOperand")
316
317 debug = False
318 stringExpr.setDebug(debug)
319 enumExpr.setDebug(debug)
320 patLiterals.setDebug(debug)
321 simpleOperand.setDebug(debug)
322 simpleOperator.setDebug(debug)
323 nakedExpr.setDebug(debug)
324
325 simpleExpr.addParseAction(_makeOpNode)
326 patternExpr.addParseAction(_makeOpNode)
327 enumExpr.addParseAction(_makeOpNode)
328 makeDefaultExpr = _getNodeFactory("==", StringNode)
329 nakedExpr.addParseAction(lambda s,p,toks: makeDefaultExpr(s,p,
330 ["".join(toks)]))
331 wildStar.addParseAction(_makeOpNode)
332 wildQmark.addParseAction(_makeOpNode)
333 setElems.addParseAction(_getNodeFactory("[", StringNode))
334
335 return doc
336
337
338 def parseStringExpr(str, baseSymbol=getStringGrammar()):
339 return utils.pyparseString(baseSymbol, str)[0]
340
341
342 class _Flattener:
343 """An abstract base class for things turning our parse trees into SQL.
344
345 Concrete derivations need to define a set _standardOperators containing the
346 normal binary operators for their types and a dictionary _sqlEmitters
347 containing functions returning SQL fragments; of course, they
348 can also completey override getSQLFor.
349 """
350 def getSQLFor(self, node, field, sqlPars):
351 """returns SQL for a parse node node over an InputKey field.
352
353 sqlPars is the dict that is later passed to conn.execute and
354 will be modified here.
355 """
356 if node.operator in self._standardOperators:
357 return "{} {} %({})s".format(
358 field.name,
359 node.operator,
360 node.insertChild(0, field, sqlPars))
361 else:
362 return self._sqlEmitters[node.operator](
363 self, node, field, sqlPars)
364
365
366 class NumericFlattener(_Flattener):
367 """A _Flattener for float- and int-valued columns.
368 """
369 def _emitBinop(self, node, field, sqlPars):
370 return base.joinOperatorExpr(node.operator,
371 [self.getSQLFor(c, field, sqlPars) for c in node.children])
372
373 def _emitUnop(self, node, field, sqlPars):
374 operand = self.getSQLFor(node.children[0], field, sqlPars)
375 if operand:
376 return "{} ({})".format(node.operator, operand)
377
378 def _emitEnum(self, node, field, sqlPars):
379 return "{} IN ({})".format(
380 field.name,
381 ", ".join("%({})s".format(node.insertChild(i, field, sqlPars))
382 for i in range(len(node.children))))
383
384 _standardOperators = set(["=", ">=", ">", "<=", "<"])
385 _sqlEmitters = {
386 '..': lambda self, node, field, sqlPars:
387 "{} BETWEEN %({})s AND %({})s".format(
388 field.name,
389 node.insertChild(0, field, sqlPars),
390 node.insertChild(1, field, sqlPars)),
391 'AND': _emitBinop,
392 'OR': _emitBinop,
393 'NOT': _emitUnop,
394 ',': _emitEnum,
395 }
396
397
398 class NumericIntervalFlattener(NumericFlattener):
399 """A _Flattener for matching against min/max pairs of columns.
400
401 Here, field is this (min_column, max_column) pair.
402
403 This currently isn't used anywhere in DaCHS itself. You can use
404 it in custom phraseMakers, though; cf. :samplerd:`obsform/q`
405 """
406 def _emitEnum(self, node, field, sqlPars):
407 return base.joinOperatorExpr("OR",
408 [self._emitEquality(node, field, sqlPars, useChild=childInd)
409 for childInd, _ in enumerate(node.children)])
410
411 def _emitInterval(self, node, field, sqlPars):
412 # interval condition: overlaps
413 return ("{h1}>=%({l2})s AND %({h2})s>={l1}"
414 " AND {l1}<={h1} AND %({l2})s<=%({h2})s").format(
415 l1=field[0].name,
416 h1=field[1].name,
417 l2=node.insertChild(0, field[0], sqlPars),
418 h2=node.insertChild(1, field[1], sqlPars))
419
420 def _emitEquality(self, node, field, sqlPars, useChild=0):
421 # equality is interpreted as "contains" here
422 return "%({})s BETWEEN {} AND {}".format(
423 node.insertChild(useChild, field[0], sqlPars),
424 field[0].name,
425 field[1].name)
426
427 def _emitLarger(self, node, field, sqlPars):
428 # larger/larger equal is, perhaps a bit funkily, larger than
429 # upper/lower bound.
430 if "=" in node.operator:
431 limitField = field[1]
432 else:
433 limitField = field[0]
434
435 return "{} > %({})s".format(
436 limitField.name,
437 node.insertChild(0, limitField, sqlPars))
438
439 def _emitSmaller(self, node, field, sqlPars):
440 # smaller/smaller equal is, perhaps a bit funkily, smaller than
441 # lower/upper bound.
442 if "=" in node.operator:
443 limitField = field[0]
444 else:
445 limitField = field[1]
446
447 return "{} < %({})s".format(
448 limitField.name,
449 node.insertChild(0, limitField, sqlPars))
450
451 _standardOperators = set()
452 _sqlEmitters = {
453 '..': _emitInterval,
454 '=': _emitEquality,
455 '>=': _emitLarger,
456 '>': _emitLarger,
457 '<': _emitSmaller,
458 '<=': _emitSmaller,
459 'AND': NumericFlattener._emitBinop,
460 'OR': NumericFlattener._emitBinop,
461 'NOT': NumericFlattener._emitUnop,
462 ',': _emitEnum,
463 }
464
465
466 class DateFlattener(_Flattener):
467 """A _Flattener producing SQL for data-like columns.
468
469 This is supposed to work for timestamp-valued and MJD-valued columns
470 alike. The difference is handled on the level of nodes (DateNode
471 vs. MJDNode).
472 """
473 def _expandDate(self, arg):
474 # returns the last second of arg if it looks like a day (i.e., hms=0)
475 # this is to fix postgres' behaviour when comparing timestamps and
476 # dates (e.g., 1990-01-01 < 1990-01-01T00:00:01).
477 if arg.hour==arg.minute==arg.second==0:
478 return arg.replace(hour=23,
479 minute=59, second=59)
480 return arg
481
482 def _emitBinop(self, node, field, sqlPars):
483 return base.joinOperatorExpr(node.operator,
484 [self.getSQLFor(c, field, sqlPars) for c in node.children])
485
486 def _emitUnop(self, node, field, sqlPars):
487 operand = self.getSQLFor(node.children[0], field, sqlPars)
488 if operand:
489 return "%s (%s)"%(node.operator, operand)
490
491 def _emitRange(self, node, field, sqlPars):
492 return "{} BETWEEN %({})s AND %({})s".format(
493 field.name,
494 node.insertChild(0, field, sqlPars),
495 node.insertChild(1, field, sqlPars))
496
497 def _emitEnum(self, node, field, sqlPars):
498 return base.joinOperatorExpr("OR",
499 [self.getSQLFor(node.__class__([child], "="), field, sqlPars)
500 for child in node.children])
501
502 def _emitSimple(self, node, field, sqlPars):
503 # return a simple comparison with the date itself
504 return "{} {} %({})s".format(field.name, node.operator,
505 node.insertChild(0, field, sqlPars))
506
507 def _emitEqual(self, node, field, sqlPars):
508 if node.children[0].hour==node.children[0].minute==0:
509 # expand this to a condition covering the whole day
510 return "{} BETWEEN %({})s AND %({})s".format(
511 field.name,
512 node.getSQLKey(field.name, node.children[0], sqlPars),
513 node.getSQLKey(field.name,
514 self._expandDate(node.children[0]), sqlPars))
515
516 else:
517 return self._emitSimple(node, field, sqlPars)
518
519 def _emitExpanded(self, node, field, sqlPars):
520 # return a simple comparison with date's midnight
521 node.children[0] = self._expandDate(node.children[0])
522 return "{} {} %({})s".format(
523 field.name,
524 node.operator,
525 node.insertChild(0, field, sqlPars))
526
527 _standardOperators = set()
528 _sqlEmitters = {
529 '..': _emitRange,
530 'AND': _emitBinop,
531 'OR': _emitBinop,
532 'NOT': _emitUnop,
533 ',': _emitEnum,
534 "=": _emitEqual,
535 ">=": _emitSimple,
536 "<=": _emitExpanded,
537 "<": _emitSimple,
538 ">": _emitExpanded,
539 "<=": _emitExpanded,
540 }
541
542
543 class StringFlattener(_Flattener):
544 """A _Flattener turning String-like Vizier expressions into
545 SQL conditions against string-valued columns.
546 """
547 _metaEscapes = {
548 "|": r"\|",
549 "*": r"\*",
550 "+": r"\+",
551 "(": r"\(",
552 ")": r"\)",
553 "[": r"\[",
554 "%": r"\%",
555 "_": r"\_",
556 "\\\\": "\\\\",
557 }
558 _escapeRE = re.compile("[%s]"%"".join(list(_metaEscapes.keys())))
559 # The backslash in _metaEscapes is escaped to make _escapeRE work,
560 # but of course I need to replace the unescaped version.
561 _metaEscapes.update({"\\": "\\\\"})
562
563 def _escapeSpecials(self, aString):
564 """returns aString with SQL RE metacharacters escaped.
565 """
566 return self._escapeRE.sub(
567 lambda mat: self._metaEscapes[mat.group()],
568 aString)
569
570 def _makePattern(self, node, field, sqlPars):
571 parts = []
572 for child in node.children:
573 if isinstance(child, str):
574 parts.append(self._escapeSpecials(child))
575 else:
576 parts.append(self.getSQLFor(child, field, sqlPars))
577 return "^%s$"%("".join(parts))
578
579 _patOps = {
580 "~": "~*",
581 "=": "~",
582 "!~": "!~*",
583 "!": "!~",
584 "=~": "~*",
585 }
586 def _emitPatOp(self, node, field, sqlPars):
587 pattern = self._makePattern(node, field, sqlPars)
588 return "{} {} %({})s".format(
589 field.name,
590 self._patOps[node.operator],
591 node.getSQLKey(field.name, pattern, sqlPars))
592
593 def _emitEnum(self, node, field, sqlPars):
594 query = "{} IN ({})".format(
595 field.name,
596 ", ".join(
597 "%({})s".format(node.insertChild(i, field, sqlPars))
598 for i in range(len(node.children))))
599
600 if node.operator=="!=,":
601 query = "NOT ({})".format(query)
602 return query
603
604 _translatedOps = {
605 "==": "=",
606 }
607 def _emitTranslatedOp(self, node, field, sqlPars):
608 return "{} = %({})s".format(field.name,
609 node.insertChild(0, field, sqlPars))
610
611 _nullOperators = {"*": ".*", "?": "."}
612 _standardOperators = set(["<", ">", "<=", ">=", "!="])
613 _sqlEmitters = {
614 "~": _emitPatOp,
615 "=": _emitPatOp,
616 "!~": _emitPatOp,
617 "!": _emitPatOp,
618 "=~": _emitPatOp, # this happens to work because of pattern escaping
619 "=,": _emitEnum,
620 "=|": _emitEnum,
621 "!=,": _emitEnum,
622 "==": _emitTranslatedOp,
623 }
624
625 def getSQLFor(self, node, field, sqlPars):
626 if node.operator=="[":
627 return "[%s]"%node.children[0]
628 if node.operator in self._nullOperators:
629 return self._nullOperators[node.operator]
630 else:
631 return _Flattener.getSQLFor(self, node, field, sqlPars)
632
633
634 def _makeFactory(parser, flattener):
635 def factory(field, val, sqlPars):
636 try:
637 tree = parser(val)
638 return flattener.getSQLFor(tree, field, sqlPars)
639 except ParseException:
640 raise base.ui.logOldExc(utils.ValidationError(
641 "Invalid input for type %s (see help for valid type literals)"%
642 field.type, field.name))
643 return factory
644
645
646 _dateFlattener = DateFlattener()
647
648 sqlmunge.registerSQLFactory("vexpr-float",
649 _makeFactory(parseNumericExpr, NumericFlattener()))
650 sqlmunge.registerSQLFactory("vexpr-date",
651 _makeFactory(parseDateExpr, _dateFlattener))
652 sqlmunge.registerSQLFactory("vexpr-mjd",
653 _makeFactory(parseDateExprToMJD, _dateFlattener))
654 sqlmunge.registerSQLFactory("vexpr-string",
655 _makeFactory(parseStringExpr, StringFlattener()))
656
657
658 class ToVexprConverter(typesystems.FromSQLConverter):
659 typeSystem = "vizierexpr"
660 simpleMap = {
661 "smallint": "vexpr-float",
662 "integer": "vexpr-float",
663 "int": "vexpr-float",
664 "bigint": "vexpr-float",
665 "real": "vexpr-float",
666 "float": "vexpr-float",
667 "double precision": "vexpr-float",
668 "double": "vexpr-float",
669 "text": "vexpr-string",
670 "unicode": "vexpr-string",
671 "char": "vexpr-string",
672 "date": "vexpr-date",
673 "timestamp": "vexpr-date",
674 "vexpr-date": "vexpr-date",
675 "vexpr-float": "vexpr-float",
676 "vexpr-string": "vexpr-string",
677 }
678
679 def mapComplex(self, sqlType, length):
680 if sqlType=="char":
681 return "vexpr-string"
682 if sqlType=="varchar":
683 return "vexpr-string"
684
685 getVexprFor = ToVexprConverter().convert
686
687
688 def makeConeSearchFor(inputKey):
689 """returns an //scs#makeSpointCD condDesc tailored for inputKey.
690 """
691 from gavo.svcs import standardcores
692 return base.parseFromString(standardcores.CondDesc, """
693 <FEED source="//scs#makeSpointCD"
694 tablehead=%s
695 matchColumn=%s/>
696 """%(
697 utils.escapeAttrVal(inputKey.tablehead),
698 utils.escapeAttrVal(inputKey.name)))
699
700
701 def format_placeholder(min_val, max_val, formatter):
702 """returns a placeholder string for a possibly open interval.
703
704 ``*_val`` may be None, formatter has to accept a non-None value
705 and return the proper representation for the placeholder string.
706
707 If no placeholder can be generated, this function returns None.
708 """
709 if min_val is None:
710 if max_val is None:
711 return None
712 else:
713 return "< %s"%formatter(max_val)
714 else:
715 if max_val is None:
716 return "> %s"%formatter(min_val)
717 else:
718 return "%s .. %s"%(
719 formatter(min_val), formatter(max_val))
720
721
722 def getPlaceholderFor(inputKey, values):
723 """returns a placeholder (suggested input) for inputKey, where values
724 is the original values element.
725
726 This will currently be None unless we do a numeric input.
727 """
728 if not values:
729 return
730
731 if inputKey.type=="vexpr-float":
732 scaling = inputKey.scaling or 1
733 return format_placeholder(values.min_typed, values.max_typed,
734 lambda val: "%s"%(val/scaling))
735
736 elif inputKey.type=="vexpr-mjd":
737 # date with underlying MJD column
738 return format_placeholder(values.min_typed, values.max_typed,
739 lambda val: "%s"%utils.formatISODT(stc.mjdToDateTime(val)))
740
741 elif inputKey.type=="vexpr-date":
742 # date with underlying timestamp column
743 return format_placeholder(values.min_typed, values.max_typed,
744 lambda val: "%s"%utils.formatISODT(val))
745
746 # fall through to None if no placeholder can be make
747
748
749 def adaptInputKey(inputKey):
750 """returns ik changed to generate SQL for Vizier-like expressions.
751
752 This is used for buildFrom on CondDescs and renderers having
753 parameterStyle form.
754 """
755 res, oldValues = inputKey, inputKey.values
756
757 # manually check for things that need to change the whole condDesc.
758 if inputKey.type=='spoint':
759 raise base.Replace(makeConeSearchFor(inputKey))
760 elif inputKey.xtype=="mjd":
761 res = inputKey.change(type="vexpr-mjd", unit="", parent_=None)
762 elif inputKey.isEnumerated():
763 res = inputKey
764
765 else:
766
767 try:
768 changes = {
769 "type": getVexprFor(inputKey.type),
770 "values": None,
771 "parent_": None}
772
773 if inputKey.displayHint.get("displayUnit") and \
774 inputKey.displayHint["displayUnit"]!=inputKey.unit:
775 changes["inputUnit"] = inputKey.displayHint["displayUnit"]
776
777 res = inputKey.change(**changes)
778 except base.ConversionError: # No vexpr type, leave things
779 pass
780
781 res.setProperty("placeholder",
782 getPlaceholderFor(res, oldValues))
783
784 return res
785
786
787 if __name__=="__main__": # pragma: no cover
788 import doctest
789 doctest.testmod()