| 1 |
""" |
| 2 |
Code to support PQL syntax (as found in various DAL protocols). |
| 3 |
|
| 4 |
PQL range-list syntax is |
| 5 |
|
| 6 |
valSep ::= "," |
| 7 |
rangeSep ::= "/" |
| 8 |
qualSep ::= ";" |
| 9 |
step ::= somethingMagicallyDefined |
| 10 |
range ::= [literal] rangeSep literal | literal rangeSep |
| 11 |
steppedRange ::= range [rangeSep step] |
| 12 |
qualification ::= qualSep somethingMagicallyDefined |
| 13 |
listItem ::= steppedRange | literal |
| 14 |
rangeList ::= listItem {valSep listItem} [qualification] |
| 15 |
|
| 16 |
This defines a regular language, and we're going to slaughter it using |
| 17 |
REs and ad hoccing. |
| 18 |
|
| 19 |
Since the actually allowed grammar depends on the type of the parameter |
| 20 |
(e.g., steps make no sense for strings, and have a special grammar for |
| 21 |
dates), parsing is done by the specific PQLPar types (fromLiteral). See |
| 22 |
the PQLPar docstring for further info. |
| 23 |
""" |
| 24 |
|
| 25 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 26 |
#c |
| 27 |
#c This program is free software, covered by the GNU GPL. See the |
| 28 |
#c COPYING file in the source distribution. |
| 29 |
|
| 30 |
|
| 31 |
import datetime |
| 32 |
import functools |
| 33 |
import re |
| 34 |
import urllib.request, urllib.parse, urllib.error |
| 35 |
|
| 36 |
from gavo import base |
| 37 |
from gavo import stc |
| 38 |
from gavo import utils |
| 39 |
from gavo.base import literals |
| 40 |
from gavo.base import sqlmunge |
| 41 |
from gavo.base import typesystems |
| 42 |
from gavo.utils import DEG, pgsphere |
| 43 |
|
| 44 |
|
| 45 |
QUALIFIER_RE = re.compile("([^;]*)(;[^;]*)?$") |
| 46 |
LIST_RE = re.compile("([^,]*),") |
| 47 |
RANGE_RE = re.compile("([^/]*)(/[^/]*)?(/[^/]*)?$") |
| 48 |
|
| 49 |
|
| 50 |
def _raiseNoSteps(val): |
| 51 |
raise ValueError("Step/stride specification not allowed here.") |
| 52 |
|
| 53 |
|
| 54 |
def _parsePQLValue(val, valInd=0, vp=str): |
| 55 |
if not val or not val[valInd:]: |
| 56 |
return None |
| 57 |
else: |
| 58 |
return vp(urllib.parse.unquote(val[valInd:])) |
| 59 |
|
| 60 |
|
| 61 |
class PQLRange(object): |
| 62 |
"""a representation of a PQL range. |
| 63 |
|
| 64 |
PQLRanges have a value attribute that is non-None when there is |
| 65 |
only a single value. |
| 66 |
|
| 67 |
For ranges, there is start, stop and step, all of which may be |
| 68 |
None. |
| 69 |
|
| 70 |
The attributes contain whatever the parent's valParser (or stepParser) |
| 71 |
functions return. |
| 72 |
""" |
| 73 |
def __init__(self, value=None, start=None, stop=None, step=None): |
| 74 |
self.start, self.stop, self.step = start, stop, step |
| 75 |
self.value = value |
| 76 |
if (self.step is not None |
| 77 |
and (self.start is None or self.stop is None)): |
| 78 |
raise ValueError("Open intervals cannot have steps") |
| 79 |
if (self.value is None |
| 80 |
and (self.start is None and self.stop is None)): |
| 81 |
raise ValueError("Doubly open intervals are not allowed") |
| 82 |
|
| 83 |
def __eq__(self, other): |
| 84 |
return (isinstance(other, PQLRange) |
| 85 |
and self.value==other.value |
| 86 |
and self.start==other.start |
| 87 |
and self.stop==other.stop |
| 88 |
and self.step==other.step) |
| 89 |
|
| 90 |
def __repr__(self): |
| 91 |
return "%s(%s, %s, %s, %s)"%(self.__class__.__name__, |
| 92 |
repr(self.value), |
| 93 |
repr(self.start), |
| 94 |
repr(self.stop), |
| 95 |
repr(self.step)) |
| 96 |
|
| 97 |
def __str__(self): |
| 98 |
if self.value is not None: |
| 99 |
return urllib.parse.quote(str(self.value)) |
| 100 |
else: |
| 101 |
def e(v): |
| 102 |
if v is None: |
| 103 |
return "" |
| 104 |
else: |
| 105 |
return urllib.parse.quote(str(v)) |
| 106 |
return "/".join(e(v) for v in (self.start, self.stop, self.step)) |
| 107 |
|
| 108 |
@classmethod |
| 109 |
def fromLiteral(cls, literal, destName, valParser, stepParser): |
| 110 |
"""creates a PQLRange from a PQL range literal. |
| 111 |
|
| 112 |
For the meaning of the arguments, see PQLPar.fromLiteral. |
| 113 |
""" |
| 114 |
if literal=="": |
| 115 |
return cls(value="") |
| 116 |
mat = RANGE_RE.match(literal) |
| 117 |
if not mat: |
| 118 |
raise base.LiteralParseError(destName, literal, |
| 119 |
hint="PQL ranges roughly have the form [start][/stop[/stop]]." |
| 120 |
" Literal slashes need to be escaped (as %2f).") |
| 121 |
vals = mat.groups() |
| 122 |
|
| 123 |
try: |
| 124 |
if vals[1] is None and vals[2] is None: |
| 125 |
return cls(value=_parsePQLValue(vals[0], vp=valParser)) |
| 126 |
else: |
| 127 |
start, stop, step = vals |
| 128 |
return cls( |
| 129 |
start=_parsePQLValue(start, vp=valParser), |
| 130 |
stop=_parsePQLValue(stop, 1, vp=valParser), |
| 131 |
step=_parsePQLValue(step, 1, vp=stepParser)) |
| 132 |
except ValueError as ex: |
| 133 |
raise base.LiteralParseError("range within %s"%destName, literal, |
| 134 |
hint=str(ex)) |
| 135 |
|
| 136 |
def getValuesAsSet(self): |
| 137 |
"""returns a set containing all values matching the PQL condition if |
| 138 |
they form a discrete set or raises a ValueError if not. |
| 139 |
""" |
| 140 |
if self.value is not None: |
| 141 |
return set([self.value]) |
| 142 |
elif (self.step is not None \ |
| 143 |
and self.start is not None |
| 144 |
and self.stop is not None): |
| 145 |
if (self.stop-self.start)/abs(self.step)+1e-10>2000: |
| 146 |
raise ValueError("Too many steps; will not check discretely") |
| 147 |
res, val = set(), self.start |
| 148 |
while val<=self.stop: |
| 149 |
res.add(val) |
| 150 |
val = val+self.step |
| 151 |
return res |
| 152 |
raise ValueError("No set representation for non-stepped or open ranges.") |
| 153 |
|
| 154 |
def getSQL(self, colName, sqlPars, cmpExpr=None): |
| 155 |
"""returns an SQL boolean expression for representing this constraint. |
| 156 |
|
| 157 |
cmpExpr, if given, will be an expression that is compared |
| 158 |
against. It defaults to colName, but this is, of course, intended |
| 159 |
to allow stuff like LOWER(colName). |
| 160 |
""" |
| 161 |
if cmpExpr is None: |
| 162 |
cmpExpr = colName |
| 163 |
|
| 164 |
# Single Value |
| 165 |
if self.value is not None: |
| 166 |
return "%s = %%(%s)s"%(cmpExpr, |
| 167 |
base.getSQLKey(colName, self.value, sqlPars)) |
| 168 |
|
| 169 |
# Discrete Set |
| 170 |
try: |
| 171 |
return "%s IN %%(%s)s"%(cmpExpr, base.getSQLKey(colName, |
| 172 |
self.getValuesAsSet(), sqlPars)) |
| 173 |
except ValueError: # Not a discrete set |
| 174 |
pass |
| 175 |
|
| 176 |
# At least one half-open or non-stepped range |
| 177 |
if self.start is None and self.stop is not None: |
| 178 |
return "%s <= %%(%s)s"%(cmpExpr, |
| 179 |
base.getSQLKey(colName, self.stop, sqlPars)) |
| 180 |
elif self.start is not None and self.stop is None: |
| 181 |
return "%s >= %%(%s)s"%(cmpExpr, |
| 182 |
base.getSQLKey(colName, self.start, sqlPars)) |
| 183 |
else: |
| 184 |
assert self.start is not None and self.stop is not None |
| 185 |
return "%s BETWEEN %%(%s)s AND %%(%s)s "%(cmpExpr, |
| 186 |
base.getSQLKey(colName, self.start, sqlPars), |
| 187 |
base.getSQLKey(colName, self.stop, sqlPars)) |
| 188 |
|
| 189 |
def getSQLForInterval(self, lowerColName, upperColName, sqlPars): |
| 190 |
"""returns an SQL boolean expression for representing this constraint |
| 191 |
against an upper, lower interval in the DB table. |
| 192 |
|
| 193 |
This will silently discard any step specification. |
| 194 |
""" |
| 195 |
# Single Value |
| 196 |
if self.value is not None: |
| 197 |
return "%%(%s)s BETWEEN %s AND %s"%( |
| 198 |
base.getSQLKey("val", self.value, sqlPars), |
| 199 |
lowerColName, upperColName) |
| 200 |
else: |
| 201 |
constraints = [] |
| 202 |
if self.stop is not None: |
| 203 |
constraints.append("%%(%s)s>%s"%( |
| 204 |
base.getSQLKey("val", self.stop, sqlPars), |
| 205 |
lowerColName)) |
| 206 |
if self.start is not None: |
| 207 |
constraints.append("%%(%s)s<%s"%( |
| 208 |
base.getSQLKey("val", self.start, sqlPars), |
| 209 |
upperColName)) |
| 210 |
return "(%s)"%" AND ".join(constraints) |
| 211 |
|
| 212 |
def covers(self, value): |
| 213 |
"""returns True if value is covered by this interval. |
| 214 |
|
| 215 |
value must be type-true, i.e. in whatever type value, start, and stop |
| 216 |
have. |
| 217 |
""" |
| 218 |
# try a single value |
| 219 |
if self.value is not None: |
| 220 |
return value==self.value |
| 221 |
|
| 222 |
# try a discrete set ("step" has been specified) |
| 223 |
try: |
| 224 |
return value in self.getValuesAsSet() |
| 225 |
except ValueError: # not a discrete set |
| 226 |
pass |
| 227 |
|
| 228 |
# interval, possibly half-open |
| 229 |
covers = True |
| 230 |
if self.start is not None: |
| 231 |
covers &= self.start<=value |
| 232 |
if self.stop is not None: |
| 233 |
covers &= self.stop>=value |
| 234 |
return covers |
| 235 |
|
| 236 |
|
| 237 |
class PQLNoRange(PQLRange): |
| 238 |
"""a stand-in for PQLRange when no ranges are to be supported |
| 239 |
|
| 240 |
It seems this is intended for string-typed values. We try to |
| 241 |
be compatible with PQLRange in the relevant API aspects. |
| 242 |
""" |
| 243 |
def __init__(self, value): |
| 244 |
self.value = value |
| 245 |
self.start = self.stop = self.step = None |
| 246 |
|
| 247 |
def __eq__(self, other): |
| 248 |
return (isinstance(other, PQLRange) |
| 249 |
and self.value==other.value |
| 250 |
and self.start==other.start |
| 251 |
and self.stop==other.stop |
| 252 |
and self.step==other.step) |
| 253 |
|
| 254 |
def __str__(self): |
| 255 |
return str(self.value) |
| 256 |
|
| 257 |
@classmethod |
| 258 |
def fromLiteral(cls, literal, destName, valParser, stepParser): |
| 259 |
"""creates a PQLRange from a PQL range literal. |
| 260 |
|
| 261 |
For the meaning of the arguments, see PQLPar.fromLiteral. |
| 262 |
""" |
| 263 |
if literal=="": |
| 264 |
return cls(value="") |
| 265 |
return cls(value=_parsePQLValue(literal, vp=valParser)) |
| 266 |
|
| 267 |
|
| 268 |
class PQLPar(object): |
| 269 |
"""a representation for PQL expressions. |
| 270 |
|
| 271 |
PQLPar objects have an attribute qualifier (None or a string), |
| 272 |
and an attribute ranges, a list of PQLRange objects. |
| 273 |
|
| 274 |
As a client, you will usually construct PQLPar objects using the |
| 275 |
fromLiteral class method; it takes a PQL literal and a name to be |
| 276 |
used for LiteralParseErrors it may raise. |
| 277 |
|
| 278 |
The plain PQLPar parses string ranges and does not allow steps. |
| 279 |
|
| 280 |
Inheriting classes must override the valParser and stepParser attributes. |
| 281 |
Both take a string and have to return a typed value or raise a |
| 282 |
ValueError if the string does not contain a proper literal. |
| 283 |
The default for valParser is str, the default for stepParser |
| 284 |
a function that always raises a ValueError. |
| 285 |
|
| 286 |
PQLPars usually support a covers(value) method that you can |
| 287 |
pass a value having the required type; it will return whether or |
| 288 |
not value would be picked up by the condition formulated in PQL. |
| 289 |
Some advanced PQLPars do not support this method and will |
| 290 |
raise a ValueError if called. |
| 291 |
|
| 292 |
Since "PQL" is totally crazy, not even the range parser is constant. |
| 293 |
It seems string ranges were never meant to be supported, and therefore |
| 294 |
we support RangeClass. PQLRange allows the "/" syntax and is supposed |
| 295 |
to work for most things but strings. PQLNoRange is just always a simple |
| 296 |
value. |
| 297 |
|
| 298 |
Note: valParser and stepParser must not be *methods* of the |
| 299 |
class but plain functions; since they are function-like class attributes, |
| 300 |
you will usually have to wrap them in staticmethods |
| 301 |
""" |
| 302 |
nullvalue = None |
| 303 |
valParser = str |
| 304 |
stepParser = staticmethod(_raiseNoSteps) |
| 305 |
rangeClass = PQLRange |
| 306 |
|
| 307 |
def __init__(self, ranges, qualifier=None, destName=None): |
| 308 |
self.qualifier = qualifier |
| 309 |
self.ranges = ranges |
| 310 |
self.destName = destName |
| 311 |
|
| 312 |
def __eq__(self, other): |
| 313 |
return (isinstance(other, PQLPar) |
| 314 |
and self.qualifier==other.qualifier |
| 315 |
and self.ranges==other.ranges) |
| 316 |
|
| 317 |
def __str__(self): |
| 318 |
res = ",".join(str(r) for r in self.ranges) |
| 319 |
if self.qualifier: |
| 320 |
res = res+";"+urllib.parse.quote(self.qualifier) |
| 321 |
return res |
| 322 |
|
| 323 |
def __repr__(self): |
| 324 |
return "%s(%s)"%(self.__class__.__name__, |
| 325 |
repr(str(self))) |
| 326 |
|
| 327 |
@staticmethod |
| 328 |
def _parsePQLString(cls, val, destName): |
| 329 |
# this is the implementation of the fromLiteral class method(s) |
| 330 |
# It's static so the fromLiterals can upcall. |
| 331 |
if val is None: |
| 332 |
return None |
| 333 |
|
| 334 |
if val==cls.nullvalue: |
| 335 |
return None |
| 336 |
|
| 337 |
mat = QUALIFIER_RE.match(val) |
| 338 |
if not mat: |
| 339 |
raise base.LiteralParseError(destName, val, hint="Not more than one" |
| 340 |
" semicolon is allowed in PQL expressions") |
| 341 |
qualifier = _parsePQLValue(mat.group(2), 1) |
| 342 |
|
| 343 |
ranges = [] |
| 344 |
listLiteral = mat.group(1) |
| 345 |
# harmless hack to avoid special-casing for one-element list |
| 346 |
rangeMat = re.match("", listLiteral) |
| 347 |
for rangeMat in LIST_RE.finditer(listLiteral): |
| 348 |
try: |
| 349 |
ranges.append( |
| 350 |
cls.rangeClass.fromLiteral(rangeMat.group(1), destName, |
| 351 |
cls.valParser, cls.stepParser)) |
| 352 |
except base.LiteralParseError as ex: |
| 353 |
ex.pos = rangeMat.start() |
| 354 |
raise |
| 355 |
ranges.append( |
| 356 |
cls.rangeClass.fromLiteral(listLiteral[rangeMat.end():], destName, |
| 357 |
cls.valParser, cls.stepParser)) |
| 358 |
return cls(ranges, qualifier, destName) |
| 359 |
|
| 360 |
@classmethod |
| 361 |
def fromLiteral(cls, val, destName): |
| 362 |
"""returns a parsed representation of a literal in PQL range-list syntax. |
| 363 |
|
| 364 |
val is a string containing the PQL expression, destName is a name to |
| 365 |
be used for the LiteralParseErrors the function raises when there are |
| 366 |
syntax errors in val. |
| 367 |
""" |
| 368 |
return cls._parsePQLString(cls, val, destName) |
| 369 |
|
| 370 |
def getValuesAsSet(self): |
| 371 |
"""returns a set of all values mentioned within the PQL expression. |
| 372 |
|
| 373 |
This raises a ValueError if this is not possible (e.g., due to |
| 374 |
non-stepped intervals). |
| 375 |
""" |
| 376 |
res = set() |
| 377 |
for r in self.ranges: |
| 378 |
res.update(r.getValuesAsSet()) |
| 379 |
return res |
| 380 |
|
| 381 |
def getSQL(self, colName, sqlPars, cmpExpr=None): |
| 382 |
"""returns an SQL condition expressing this PQL constraint for colName. |
| 383 |
|
| 384 |
The parameters necessary are added to sqlPars. |
| 385 |
|
| 386 |
cmpExpr can be used to override the cmpExpr argument to PQLRange.getSQL; |
| 387 |
this is not really intended for user code, though, but rather for |
| 388 |
subclasses of PQLPar |
| 389 |
""" |
| 390 |
if cmpExpr is None: |
| 391 |
cmpExpr = colName |
| 392 |
|
| 393 |
if len(self.ranges)==1: # Special case for SQL cosmetics |
| 394 |
return self.ranges[0].getSQL(colName, sqlPars, cmpExpr=cmpExpr) |
| 395 |
|
| 396 |
try: |
| 397 |
return "%s IN %%(%s)s"%(cmpExpr, base.getSQLKey(colName, |
| 398 |
self.getValuesAsSet(), sqlPars)) |
| 399 |
except ValueError: # at least one open or non-stepped range |
| 400 |
return "(%s)"%" OR ".join( |
| 401 |
r.getSQL(colName, sqlPars, cmpExpr=cmpExpr) for r in self.ranges) |
| 402 |
|
| 403 |
def covers(self, value): |
| 404 |
"""returns true if value is within the ranges specified by the PQL |
| 405 |
expression. |
| 406 |
|
| 407 |
value must be type-true, i.e., you are responsible for converting it |
| 408 |
into the type the range are in. |
| 409 |
""" |
| 410 |
for r in self.ranges: |
| 411 |
if r.covers(value): |
| 412 |
return True |
| 413 |
return False |
| 414 |
|
| 415 |
|
| 416 |
class PQLIntPar(PQLPar): |
| 417 |
"""a PQL parameter containing an integer. |
| 418 |
|
| 419 |
steps in ranges are allowed. |
| 420 |
""" |
| 421 |
nullvalue = "" |
| 422 |
valParser = int |
| 423 |
stepParser = int |
| 424 |
|
| 425 |
|
| 426 |
class PQLDatePar(PQLPar): |
| 427 |
"""a PQL parameter containing a date. |
| 428 |
|
| 429 |
steps in ranges are allowed. |
| 430 |
|
| 431 |
There's an additional complication here: in the database, dates can be |
| 432 |
represented in various forms. To save the day, getSQL takes an |
| 433 |
additional optional parameter and transforms the input values as |
| 434 |
appropriate before passing them to the database. |
| 435 |
""" |
| 436 |
nullvalue = "" |
| 437 |
valParser = staticmethod(literals.parseDefaultDatetime) |
| 438 |
|
| 439 |
@staticmethod |
| 440 |
def stepParser(val): |
| 441 |
return datetime.timedelta(days=float(val)) |
| 442 |
|
| 443 |
def getSQL(self, colName, sqlPars, convert=None): |
| 444 |
"""returns an SQL condition expressing the PQL constraint for colName. |
| 445 |
|
| 446 |
In addition to the usual parameters, we here accept an additional |
| 447 |
argument convert with possible values None (meaning timestamp, |
| 448 |
which is the default) mjd, jd, and jy, which represents how the |
| 449 |
datetimes are represented in the database. |
| 450 |
""" |
| 451 |
converter = { |
| 452 |
None: utils.identity, |
| 453 |
"mjd": stc.dateTimeToMJD, |
| 454 |
"jd": stc.dateTimeToJdn, |
| 455 |
"jy": stc.dateTimeToJYear,}[convert] |
| 456 |
|
| 457 |
oldKeys = set(sqlPars.keys()) |
| 458 |
res = PQLPar.getSQL(self, colName, sqlPars) |
| 459 |
|
| 460 |
# now update all keys we are responsible for |
| 461 |
if converter: |
| 462 |
for key in sqlPars: |
| 463 |
if key not in oldKeys: |
| 464 |
if sqlPars[key] is not None: |
| 465 |
sqlPars[key] = converter(sqlPars[key]) |
| 466 |
return res |
| 467 |
|
| 468 |
|
| 469 |
class PQLPositionPar(PQLPar): |
| 470 |
"""a PQL position parameter, as for SSA. |
| 471 |
|
| 472 |
Cones and intervals or real lists do not mix; we support STC-S |
| 473 |
identifiers as qualifiers. |
| 474 |
|
| 475 |
The literals here are basically two-float lists. |
| 476 |
""" |
| 477 |
valParser = float |
| 478 |
nullvalue = "" |
| 479 |
|
| 480 |
@classmethod |
| 481 |
def fromLiteral(cls, val, destName): |
| 482 |
# Hack: allow encodeded commas; this has been seen in the |
| 483 |
# wild and would be the saner way to encode this. |
| 484 |
if val is not None: |
| 485 |
val = val.upper().replace("%2C", ",") |
| 486 |
return cls._parsePQLString(cls, val, destName) |
| 487 |
|
| 488 |
def getSQL(self, colName, sqlPars): |
| 489 |
raise NotImplementedError("Ranges for PQL POS not implemented yet.") |
| 490 |
|
| 491 |
def _iterICRSPositions(self): |
| 492 |
"""yields pairs of ICRS (ra, dec) from this condition. |
| 493 |
""" |
| 494 |
if self.qualifier and self.qualifier!='ICRS': |
| 495 |
# XXX TODO: implement at least a couple of common frames |
| 496 |
raise base.ValidationError("Cannot match against coordinates" |
| 497 |
" given in %s frame"%self.qualifier, self.destName) |
| 498 |
|
| 499 |
if len(self.ranges)%2: |
| 500 |
raise base.ValidationError("PQL position values must be lists of" |
| 501 |
" length divisible by 2.", self.destName) |
| 502 |
lastCoo = None |
| 503 |
for r in self.ranges: |
| 504 |
if r.value is None: |
| 505 |
raise base.ValidationError("Ranges are not allowed as cone centers", |
| 506 |
self.destName) |
| 507 |
if lastCoo is None: |
| 508 |
lastCoo = r.value |
| 509 |
else: |
| 510 |
yield (lastCoo, r.value) |
| 511 |
lastCoo = None |
| 512 |
|
| 513 |
def getConeSQL(self, colName, sqlPars, coneSize): |
| 514 |
"""returns SQL to compute the constraint against a pgsphere point column. |
| 515 |
""" |
| 516 |
sizeName = base.getSQLKey("size", coneSize*DEG, sqlPars) |
| 517 |
parts = [] |
| 518 |
for ra, dec in self._iterICRSPositions(): |
| 519 |
parts.append("%s <@ scircle(%%(%s)s, %%(%s)s)"%(colName, |
| 520 |
base.getSQLKey("pos", pgsphere.SPoint.fromDegrees(ra, dec), |
| 521 |
sqlPars), sizeName)) |
| 522 |
return "(%s)"%" OR ".join(parts) |
| 523 |
|
| 524 |
def getQ3CSQL(self, raCol, decCol, sqlPars, coneSize): |
| 525 |
"""returns SQL to compute the constraint against a pgsphere point column. |
| 526 |
""" |
| 527 |
sizeName = base.getSQLKey("size", coneSize, sqlPars) |
| 528 |
parts = [] |
| 529 |
for ra, dec in self._iterICRSPositions(): |
| 530 |
parts.append("q3c_radial_query({}, {}, %({})s, %({})s, %({})s)".format( |
| 531 |
raCol, decCol, |
| 532 |
base.getSQLKey("ra", ra, sqlPars), |
| 533 |
base.getSQLKey("dec", dec, sqlPars), |
| 534 |
sizeName)) |
| 535 |
return "(%s)"%" OR ".join(parts) |
| 536 |
|
| 537 |
def covers(self, value): |
| 538 |
raise ValueError("%s do not support PQL covers yet. Complain." |
| 539 |
" This is fairly easy to fix."%self.__class__.__name__) |
| 540 |
|
| 541 |
|
| 542 |
class PQLFloatPar(PQLPar): |
| 543 |
"""a PQL float parameter. |
| 544 |
|
| 545 |
This has a special getSQLForInterval method for cases like SSA's |
| 546 |
BAND. |
| 547 |
""" |
| 548 |
valParser = float |
| 549 |
nullvalue = "" |
| 550 |
|
| 551 |
def getSQLForInterval(self, lowerColName, upperColName, sqlPars): |
| 552 |
"""returns an SQL phrase against an interval in a table. |
| 553 |
""" |
| 554 |
if len(self.ranges)==1: # Special case for SQL cosmetics |
| 555 |
return self.ranges[0].getSQLForInterval( |
| 556 |
lowerColName, upperColName, sqlPars) |
| 557 |
else: |
| 558 |
return "(%s)"%" OR ".join( |
| 559 |
r.getSQLForInterval(lowerColName, upperColName, sqlPars) |
| 560 |
for r in self.ranges) |
| 561 |
|
| 562 |
|
| 563 |
class PQLCaselessPar(PQLPar): |
| 564 |
"""a PQL string parameter that's compared with case folding. |
| 565 |
|
| 566 |
Don't count on case folding to work outside of ASCII. |
| 567 |
""" |
| 568 |
valParser = staticmethod(lambda val: val and val.lower()) |
| 569 |
|
| 570 |
def getSQL(self, colName, sqlPars, cmpExpr=None): |
| 571 |
"""Overridden to change cmpExpr. |
| 572 |
""" |
| 573 |
return PQLPar.getSQL(self, colName, sqlPars, "LOWER(%s)"%colName) |
| 574 |
|
| 575 |
def covers(self, value): |
| 576 |
if value is None: |
| 577 |
return False |
| 578 |
return PQLPar.covers(self, value.lower()) |
| 579 |
|
| 580 |
|
| 581 |
class PQLShellPatternPar(PQLPar): |
| 582 |
"""a PQL shell pattern parameter. |
| 583 |
|
| 584 |
These are posix shell patterns, where no PQL metacharacters are evaluated |
| 585 |
at all. |
| 586 |
""" |
| 587 |
_reOperator = "~" |
| 588 |
|
| 589 |
@classmethod |
| 590 |
def fromLiteral(cls, val, destName): |
| 591 |
if val is None: |
| 592 |
return None |
| 593 |
val = getREForShPat(val) |
| 594 |
return cls([cls.rangeClass(val)]) |
| 595 |
|
| 596 |
def getSQL(self, colName, sqlPars): |
| 597 |
"""returns an RE-based query equivalent to the input shell pattern. |
| 598 |
""" |
| 599 |
return "ssa_targname %s %%(%s)s"%(self._reOperator, |
| 600 |
base.getSQLKey(colName, self.ranges[0].value, sqlPars)) |
| 601 |
|
| 602 |
def covers(self, value): |
| 603 |
raise ValueError("%s do not support PQL covers yet. Complain." |
| 604 |
" This is easy to fix."%self.__class__.__name__) |
| 605 |
|
| 606 |
|
| 607 |
class PQLNocaseShellPatternPar(PQLShellPatternPar): |
| 608 |
"""a shell-pattern matching parameter, ignoring case. |
| 609 |
""" |
| 610 |
_reOperator = "~*" |
| 611 |
|
| 612 |
|
| 613 |
class PQLStringPar(PQLPar): |
| 614 |
"""a PQL normal string parameter. |
| 615 |
|
| 616 |
"normal" means that range expressions are not supported. |
| 617 |
""" |
| 618 |
rangeClass = PQLNoRange |
| 619 |
|
| 620 |
|
| 621 |
class PQLTextParIR(PQLPar): |
| 622 |
"""a PQL string parameter matching "google-like", "Information Retrieval". |
| 623 |
|
| 624 |
Basically, this matches the input and the database column as document |
| 625 |
vectors. Correspondingly, ranges are disallowed. |
| 626 |
""" |
| 627 |
nullvalue = "" |
| 628 |
rangeClass = PQLNoRange |
| 629 |
|
| 630 |
def getSQL(self, colName, sqlPars): |
| 631 |
docs = self.getValuesAsSet() |
| 632 |
keys = [] |
| 633 |
for doc in sorted(docs): |
| 634 |
keys.append(base.getSQLKey(colName, doc, sqlPars)) |
| 635 |
|
| 636 |
return "(%s)"%" OR ".join( |
| 637 |
"to_tsvector('english', %s) @@ plainto_tsquery('english', %%(%s)s)"%( |
| 638 |
colName, |
| 639 |
keyName) |
| 640 |
for keyName in keys) |
| 641 |
|
| 642 |
def covers(self, value): |
| 643 |
raise ValueError("%s do not support PQL covers."%self.__class__.__name__) |
| 644 |
|
| 645 |
|
| 646 |
######## posix shell patterns hacking (find some better place?) |
| 647 |
def _mungeEnumSequence(s, p, t): |
| 648 |
"""a pyparsing handler for transforming shell character enumerations to |
| 649 |
pcre character enumerations. |
| 650 |
|
| 651 |
(this is a helper for _getShPatGrammar) |
| 652 |
""" |
| 653 |
seq = "".join(t) |
| 654 |
# metacharacters in seq are troublesome: ! vs. ^, and we need to |
| 655 |
# defuse hyphens, brackets, and backslashes |
| 656 |
negate = seq.startswith("!") |
| 657 |
if negate: |
| 658 |
seq = seq[1:] |
| 659 |
seq = seq.replace("]", "\\]" |
| 660 |
).replace("\\", "\\\\" |
| 661 |
).replace("-", "\\-") |
| 662 |
|
| 663 |
if negate: |
| 664 |
return "[^%s]"%seq |
| 665 |
else: |
| 666 |
return "[%s]"%seq |
| 667 |
|
| 668 |
|
| 669 |
@functools.lru_cache(1) |
| 670 |
def _getShPatGrammar(): |
| 671 |
"""returns a grammar to translate posix shell patterns to posix regular |
| 672 |
expressions. |
| 673 |
|
| 674 |
This is different from fnmatch.translate in that it handles escaping |
| 675 |
correctly. |
| 676 |
""" |
| 677 |
from gavo.utils.parsetricks import ( |
| 678 |
Literal, Regex, CharsNotIn, ZeroOrMore, QuotedString, pyparsingWhitechars) |
| 679 |
|
| 680 |
with pyparsingWhitechars(""): |
| 681 |
enumChars = QuotedString(quoteChar="[", endQuoteChar="]", escChar="\\" |
| 682 |
).addParseAction(_mungeEnumSequence) |
| 683 |
noEnum = Literal("[").addParseAction(lambda s, p, t: "\\[") |
| 684 |
star = Literal("*").addParseAction(lambda s, p, t: ".*") |
| 685 |
questionmark = Literal("?").addParseAction(lambda s, p, t: ".") |
| 686 |
escSeq = Regex(r"\\(.)").addParseAction(lambda s, p, t: re.escape(t[0][1])) |
| 687 |
normalStuff = CharsNotIn(r"*?[\\").addParseAction(lambda s, p, t: |
| 688 |
re.escape("".join(t))) |
| 689 |
shPat = ZeroOrMore(escSeq | enumChars | noEnum |
| 690 |
| star | questionmark | normalStuff) |
| 691 |
return shPat |
| 692 |
|
| 693 |
|
| 694 |
def getREForShPat(shPat): |
| 695 |
r"""returns a POSIX RE for a POSIX shell pattern. |
| 696 |
|
| 697 |
>>> getREForShPat(r"ZU?\*[!A-Z]*") |
| 698 |
'ZU.\\*[^A\\-Z].*' |
| 699 |
>>> getREForShPat("no[*") |
| 700 |
'no\\[.*' |
| 701 |
""" |
| 702 |
return "".join(utils.pyparseString(_getShPatGrammar(), shPat, parseAll=True)) |
| 703 |
|
| 704 |
######### end posix shell patterns |
| 705 |
|
| 706 |
def _makeFactory(parType): |
| 707 |
def factory(field, val, sqlPars): |
| 708 |
try: |
| 709 |
return parType.fromLiteral(val, field.name).getSQL(field.name, sqlPars) |
| 710 |
except ValueError: |
| 711 |
raise base.ui.logOldExc(utils.ValidationError( |
| 712 |
"Invalid input for type %s" |
| 713 |
" (valid PQL literals are described in the help)"%field.type, |
| 714 |
field.name)) |
| 715 |
return factory |
| 716 |
|
| 717 |
|
| 718 |
sqlmunge.registerSQLFactory("pql-int", _makeFactory(PQLIntPar)) |
| 719 |
sqlmunge.registerSQLFactory("pql-float", _makeFactory(PQLFloatPar)) |
| 720 |
sqlmunge.registerSQLFactory("pql-string", _makeFactory(PQLPar)) |
| 721 |
sqlmunge.registerSQLFactory("pql-date", _makeFactory(PQLDatePar)) |
| 722 |
|
| 723 |
|
| 724 |
class ToPQLTypeConverter(typesystems.FromSQLConverter): |
| 725 |
typeSystem = "pqlexpr" |
| 726 |
simpleMap = { |
| 727 |
"smallint": "pql-int", |
| 728 |
"integer": "pql-int", |
| 729 |
"int": "pql-int", |
| 730 |
"bigint": "pql-int", |
| 731 |
"real": "pql-float", |
| 732 |
"float": "pql-float", |
| 733 |
"double precision": "pql-float", |
| 734 |
"double": "pql-float", |
| 735 |
"text": "pql-string", |
| 736 |
"char": "pql-string", |
| 737 |
"date": "pql-date", |
| 738 |
"timestamp": "pql-date", |
| 739 |
"pql-date": "pql-date", |
| 740 |
"pql-float": "pql-float", |
| 741 |
"pql-string": "pql-string", |
| 742 |
} |
| 743 |
|
| 744 |
def mapComplex(self, sqlType, length): |
| 745 |
if sqlType=="char": |
| 746 |
return "pql-string" |
| 747 |
if sqlType=="varchar": |
| 748 |
return "pql-string" |
| 749 |
|
| 750 |
|
| 751 |
getPQLTypeFor = ToPQLTypeConverter().convert |
| 752 |
|
| 753 |
|
| 754 |
def adaptInputKey(inputKey): |
| 755 |
"""returns inputKey changed to generate SQL for PQL-like expressions. |
| 756 |
|
| 757 |
This is used for buildFrom on CondDescs and renderers having |
| 758 |
parameterStyle pql. |
| 759 |
""" |
| 760 |
try: |
| 761 |
return inputKey.change( |
| 762 |
type=getPQLTypeFor(inputKey.type), |
| 763 |
parent_=None) |
| 764 |
except base.ConversionError: # No vexpr type, leave things |
| 765 |
pass |
| 766 |
return inputKey |
| 767 |
|
| 768 |
|
| 769 |
# Make the whole thing available to procDefs and such |
| 770 |
import sys |
| 771 |
from gavo import rscdef |
| 772 |
rscdef.addProcDefObject("pql", sys.modules[__name__]) |
| 773 |
|
| 774 |
|
| 775 |
def _test(): # pragma: no cover |
| 776 |
import doctest |
| 777 |
doctest.testmod() |