Coverage for python/lsst/daf/butler/registry/queries/expressions/_predicate.py: 13%

209 statements  

« prev     ^ index     » next       coverage.py v7.5.1, created at 2024-05-08 02:51 -0700

1# This file is part of daf_butler. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (http://www.lsst.org). 

6# See the COPYRIGHT file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

9# This software is dual licensed under the GNU General Public License and also 

10# under a 3-clause BSD license. Recipients may choose which of these licenses 

11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt, 

12# respectively. If you choose the GPL option then the following text applies 

13# (but note that there is still no warranty even if you opt for BSD instead): 

14# 

15# This program is free software: you can redistribute it and/or modify 

16# it under the terms of the GNU General Public License as published by 

17# the Free Software Foundation, either version 3 of the License, or 

18# (at your option) any later version. 

19# 

20# This program is distributed in the hope that it will be useful, 

21# but WITHOUT ANY WARRANTY; without even the implied warranty of 

22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

23# GNU General Public License for more details. 

24# 

25# You should have received a copy of the GNU General Public License 

26# along with this program. If not, see <http://www.gnu.org/licenses/>. 

27from __future__ import annotations 

28 

29__all__ = ("make_string_expression_predicate", "ExpressionTypeError") 

30 

31import builtins 

32import datetime 

33import types 

34import warnings 

35from collections.abc import Mapping, Set 

36from typing import Any, cast 

37 

38import astropy.time 

39import astropy.utils.exceptions 

40from lsst.daf.relation import ( 

41 ColumnContainer, 

42 ColumnExpression, 

43 ColumnExpressionSequence, 

44 ColumnLiteral, 

45 ColumnTag, 

46 Predicate, 

47 sql, 

48) 

49 

50# We import the some modules rather than types within them because match syntax 

51# uses qualified names with periods to distinguish literals from captures. 

52from .... import _timespan, timespan_database_representation 

53from ...._column_tags import DatasetColumnTag, DimensionKeyColumnTag, DimensionRecordColumnTag 

54from ...._column_type_info import ColumnTypeInfo 

55from ....dimensions import DataCoordinate, Dimension, DimensionGroup, DimensionUniverse 

56from ..._exceptions import UserExpressionError, UserExpressionSyntaxError 

57from .categorize import ExpressionConstant, categorizeConstant, categorizeElementId 

58from .check import CheckVisitor 

59from .normalForm import NormalForm, NormalFormExpression 

60from .parser import Node, TreeVisitor, parse_expression 

61 

62# As of astropy 4.2, the erfa interface is shipped independently and 

63# ErfaWarning is no longer an AstropyWarning 

64try: 

65 import erfa 

66except ImportError: 

67 erfa = None 

68 

69 

70class ExpressionTypeError(TypeError): 

71 """Exception raised when the types in a query expression are not 

72 compatible with the operators or other syntax. 

73 """ 

74 

75 

76def make_string_expression_predicate( 

77 string: str, 

78 dimensions: DimensionGroup, 

79 *, 

80 column_types: ColumnTypeInfo, 

81 bind: Mapping[str, Any] | None = None, 

82 data_id: DataCoordinate | None = None, 

83 defaults: DataCoordinate | None = None, 

84 dataset_type_name: str | None = None, 

85 allow_orphans: bool = False, 

86) -> tuple[Predicate | None, Mapping[str, Set[str]]]: 

87 """Create a predicate by parsing and analyzing a string expression. 

88 

89 Parameters 

90 ---------- 

91 string : `str` 

92 String to parse. 

93 dimensions : `DimensionGroup` 

94 The dimensions the query would include in the absence of this WHERE 

95 expression. 

96 column_types : `ColumnTypeInfo` 

97 Information about column types. 

98 bind : `~collections.abc.Mapping` [ `str`, `Any` ], optional 

99 Literal values referenced in the expression. 

100 data_id : `DataCoordinate`, optional 

101 A fully-expanded data ID identifying dimensions known in advance. 

102 If not provided, will be set to an empty data ID. 

103 ``dataId.hasRecords()`` must return `True`. 

104 defaults : `DataCoordinate`, optional 

105 A data ID containing default for governor dimensions. Ignored 

106 unless ``check=True``. 

107 dataset_type_name : `str` or `None`, optional 

108 The name of the dataset type to assume for unqualified dataset 

109 columns, or `None` if there are no such identifiers. 

110 allow_orphans : `bool`, optional 

111 If `True`, permit expressions to refer to dimensions without 

112 providing a value for their governor dimensions (e.g. referring to 

113 a visit without an instrument). Should be left to default to 

114 `False` in essentially all new code. 

115 

116 Returns 

117 ------- 

118 predicate : `lsst.daf.relation.colum_expressions.Predicate` or `None` 

119 New predicate derived from the string expression, or `None` if the 

120 string is empty. 

121 governor_constraints : `~collections.abc.Mapping` [ `str` , \ 

122 `~collections.abc.Set` ] 

123 Constraints on dimension values derived from the expression and data 

124 ID. 

125 """ 

126 governor_constraints: dict[str, Set[str]] = {} 

127 if data_id is None: 

128 data_id = DataCoordinate.make_empty(dimensions.universe) 

129 if not string: 

130 for dimension in data_id.dimensions.governors: 

131 governor_constraints[dimension] = {cast(str, data_id[dimension])} 

132 return None, governor_constraints 

133 try: 

134 tree = parse_expression(string) 

135 except Exception as exc: 

136 raise UserExpressionSyntaxError(f"Failed to parse user expression {string!r}.") from exc 

137 if bind is None: 

138 bind = {} 

139 if bind: 

140 for identifier in bind: 

141 if identifier in dimensions.universe.elements.names: 

142 raise RuntimeError(f"Bind parameter key {identifier!r} conflicts with a dimension element.") 

143 table, _, column = identifier.partition(".") 

144 if column and table in dimensions.universe.elements.names: 

145 raise RuntimeError(f"Bind parameter key {identifier!r} looks like a dimension column.") 

146 if defaults is None: 

147 defaults = DataCoordinate.make_empty(dimensions.universe) 

148 # Convert the expression to disjunctive normal form (ORs of ANDs). 

149 # That's potentially super expensive in the general case (where there's 

150 # a ton of nesting of ANDs and ORs). That won't be the case for the 

151 # expressions we expect, and we actually use disjunctive normal instead 

152 # of conjunctive (i.e. ANDs of ORs) because I think the worst-case is 

153 # a long list of OR'd-together data IDs, which is already in or very 

154 # close to disjunctive normal form. 

155 expr = NormalFormExpression.fromTree(tree, NormalForm.DISJUNCTIVE) 

156 # Check the expression for consistency and completeness. 

157 visitor = CheckVisitor(data_id, dimensions, bind, defaults, allow_orphans=allow_orphans) 

158 try: 

159 summary = expr.visit(visitor) 

160 except UserExpressionError as err: 

161 exprOriginal = str(tree) 

162 exprNormal = str(expr.toTree()) 

163 if exprNormal == exprOriginal: 

164 msg = f'Error in query expression "{exprOriginal}": {err}' 

165 else: 

166 msg = f'Error in query expression "{exprOriginal}" (normalized to "{exprNormal}"): {err}' 

167 raise UserExpressionError(msg) from None 

168 for dimension_name, values in summary.dimension_constraints.items(): 

169 if dimension_name in dimensions.universe.governor_dimensions.names: 

170 governor_constraints[dimension_name] = cast(Set[str], values) 

171 converter = PredicateConversionVisitor(bind, dataset_type_name, dimensions.universe, column_types) 

172 predicate = tree.visit(converter) 

173 return predicate, governor_constraints 

174 

175 

176VisitorResult = Predicate | ColumnExpression | ColumnContainer 

177 

178 

179class PredicateConversionVisitor(TreeVisitor[VisitorResult]): 

180 def __init__( 

181 self, 

182 bind: Mapping[str, Any], 

183 dataset_type_name: str | None, 

184 universe: DimensionUniverse, 

185 column_types: ColumnTypeInfo, 

186 ): 

187 self.bind = bind 

188 self.dataset_type_name = dataset_type_name 

189 self.universe = universe 

190 self.column_types = column_types 

191 

192 OPERATOR_MAP = { 

193 "=": "__eq__", 

194 "!=": "__ne__", 

195 "<": "__lt__", 

196 ">": "__gt__", 

197 "<=": "__le__", 

198 ">=": "__ge__", 

199 "+": "__add__", 

200 "-": "__sub__", 

201 "*": "__mul__", 

202 } 

203 

204 def to_datetime(self, time: astropy.time.Time) -> datetime.datetime: 

205 with warnings.catch_warnings(): 

206 warnings.simplefilter("ignore", category=astropy.utils.exceptions.AstropyWarning) 

207 if erfa is not None: 

208 warnings.simplefilter("ignore", category=erfa.ErfaWarning) 

209 return time.to_datetime() 

210 

211 def visitBinaryOp( 

212 self, operator: str, lhs: VisitorResult, rhs: VisitorResult, node: Node 

213 ) -> VisitorResult: 

214 # Docstring inherited. 

215 b = builtins 

216 match (operator, lhs, rhs): 

217 case ["OR", Predicate() as lhs, Predicate() as rhs]: 

218 return lhs.logical_or(rhs) 

219 case ["AND", Predicate() as lhs, Predicate() as rhs]: 

220 return lhs.logical_and(rhs) 

221 # Allow all comparisons between expressions of the same type for 

222 # sortable types. 

223 case [ 

224 "=" | "!=" | "<" | ">" | "<=" | ">=", 

225 ColumnExpression( 

226 dtype=b.int | b.float | b.str | astropy.time.Time | datetime.datetime 

227 ) as lhs, 

228 ColumnExpression() as rhs, 

229 ] if lhs.dtype is rhs.dtype: 

230 return lhs.predicate_method(self.OPERATOR_MAP[operator], rhs) 

231 # Allow comparisons between datetime expressions and 

232 # astropy.time.Time literals/binds (only), by coercing the 

233 # astropy.time.Time version to datetime. 

234 case [ 

235 "=" | "!=" | "<" | ">" | "<=" | ">=", 

236 ColumnLiteral(dtype=astropy.time.Time) as lhs, 

237 ColumnExpression(dtype=datetime.datetime) as rhs, 

238 ]: 

239 lhs = ColumnLiteral(self.to_datetime(lhs.value), datetime.datetime) 

240 return lhs.predicate_method(self.OPERATOR_MAP[operator], rhs) 

241 case [ 

242 "=" | "!=" | "<" | ">" | "<=" | ">=", 

243 ColumnExpression(dtype=datetime.datetime) as lhs, 

244 ColumnLiteral(dtype=astropy.time.Time) as rhs, 

245 ]: 

246 rhs = ColumnLiteral(self.to_datetime(rhs.value), datetime.datetime) 

247 return lhs.predicate_method(self.OPERATOR_MAP[operator], rhs) 

248 # Allow comparisons between astropy.time.Time expressions and 

249 # datetime literals/binds, by coercing the 

250 # datetime literals to astropy.time.Time (in UTC scale). 

251 case [ 

252 "=" | "!=" | "<" | ">" | "<=" | ">=", 

253 ColumnLiteral(dtype=datetime.datetime) as lhs, 

254 ColumnExpression(dtype=astropy.time.Time) as rhs, 

255 ]: 

256 lhs = ColumnLiteral(astropy.time.Time(lhs.value, scale="utc"), astropy.time.Time) 

257 return lhs.predicate_method(self.OPERATOR_MAP[operator], rhs) 

258 case [ 

259 "=" | "!=" | "<" | ">" | "<=" | ">=", 

260 ColumnExpression(dtype=astropy.time.Time) as lhs, 

261 ColumnLiteral(dtype=datetime.datetime) as rhs, 

262 ]: 

263 rhs = ColumnLiteral(astropy.time.Time(rhs.value, scale="utc"), astropy.time.Time) 

264 return lhs.predicate_method(self.OPERATOR_MAP[operator], rhs) 

265 # Allow equality comparisons with None/NULL. We don't have an 'IS' 

266 # operator. 

267 case ["=" | "!=", ColumnExpression(dtype=types.NoneType) as lhs, ColumnExpression() as rhs]: 

268 return lhs.predicate_method(self.OPERATOR_MAP[operator], rhs) 

269 case ["=" | "!=", ColumnExpression() as lhs, ColumnExpression(dtype=types.NoneType) as rhs]: 

270 return lhs.predicate_method(self.OPERATOR_MAP[operator], rhs) 

271 # Comparisions between Time and Timespan need have the Timespan on 

272 # the lhs, since that (actually TimespanDatabaseRepresentation) is 

273 # what actually has the methods. 

274 case [ 

275 "<", 

276 ColumnExpression(dtype=astropy.time.Time) as lhs, 

277 ColumnExpression(dtype=_timespan.Timespan) as rhs, 

278 ]: 

279 return rhs.predicate_method(self.OPERATOR_MAP[">"], lhs) 

280 case [ 

281 ">", 

282 ColumnExpression(dtype=astropy.time.Time) as lhs, 

283 ColumnExpression(dtype=_timespan.Timespan) as rhs, 

284 ]: 

285 return rhs.predicate_method(self.OPERATOR_MAP["<"], lhs) 

286 # Enable other comparisons between times and Timespans (many of the 

287 # combinations matched by this branch will have already been 

288 # covered by a preceding branch). 

289 case [ 

290 "<" | ">", 

291 ColumnExpression(dtype=_timespan.Timespan | astropy.time.Time) as lhs, 

292 ColumnExpression(dtype=_timespan.Timespan | astropy.time.Time) as rhs, 

293 ]: 

294 return lhs.predicate_method(self.OPERATOR_MAP[operator], rhs) 

295 # Enable "overlaps" operations between timespans, and between times 

296 # and timespans. The latter resolve to the `Timespan.contains` or 

297 # `TimespanDatabaseRepresentation.contains` methods, but we use 

298 # OVERLAPS in the string expression language to keep that simple. 

299 case [ 

300 "OVERLAPS", 

301 ColumnExpression(dtype=_timespan.Timespan) as lhs, 

302 ColumnExpression(dtype=_timespan.Timespan) as rhs, 

303 ]: 

304 return lhs.predicate_method("overlaps", rhs) 

305 case [ 

306 "OVERLAPS", 

307 ColumnExpression(dtype=_timespan.Timespan) as lhs, 

308 ColumnExpression(dtype=astropy.time.Time) as rhs, 

309 ]: 

310 return lhs.predicate_method("overlaps", rhs) 

311 case [ 

312 "OVERLAPS", 

313 ColumnExpression(dtype=astropy.time.Time) as lhs, 

314 ColumnExpression(dtype=_timespan.Timespan) as rhs, 

315 ]: 

316 return rhs.predicate_method("overlaps", lhs) 

317 # Enable arithmetic operators on numeric types, without any type 

318 # coercion or broadening. 

319 case [ 

320 "+" | "-" | "*", 

321 ColumnExpression(dtype=b.int | b.float) as lhs, 

322 ColumnExpression() as rhs, 

323 ] if lhs.dtype is rhs.dtype: 

324 return lhs.method(self.OPERATOR_MAP[operator], rhs, dtype=lhs.dtype) 

325 case ["/", ColumnExpression(dtype=b.float) as lhs, ColumnExpression(dtype=b.float) as rhs]: 

326 return lhs.method("__truediv__", rhs, dtype=b.float) 

327 case ["/", ColumnExpression(dtype=b.int) as lhs, ColumnExpression(dtype=b.int) as rhs]: 

328 # SQLAlchemy maps Python's '/' (__truediv__) operator directly 

329 # to SQL's '/', despite those being defined differently for 

330 # integers. Our expression language uses the SQL definition, 

331 # and we only care about these expressions being evaluated in 

332 # SQL right now, but we still want to guard against it being 

333 # evaluated in Python and producing a surprising answer, so we 

334 # mark it as being supported only by a SQL engine. 

335 return lhs.method( 

336 "__truediv__", 

337 rhs, 

338 dtype=b.int, 

339 supporting_engine_types={sql.Engine}, 

340 ) 

341 case ["%", ColumnExpression(dtype=b.int) as lhs, ColumnExpression(dtype=b.int) as rhs]: 

342 return lhs.method("__mod__", rhs, dtype=b.int) 

343 assert ( 

344 lhs.dtype is not None and rhs.dtype is not None 

345 ), "Expression converter should not yield untyped nodes." 

346 raise ExpressionTypeError( 

347 f"Invalid types {lhs.dtype.__name__}, {rhs.dtype.__name__} for binary operator {operator!r} " 

348 f"in expression {node!s}." 

349 ) 

350 

351 def visitIdentifier(self, name: str, node: Node) -> VisitorResult: 

352 # Docstring inherited. 

353 if name in self.bind: 

354 value = self.bind[name] 

355 if isinstance(value, list | tuple | Set): 

356 elements = [] 

357 all_dtypes = set() 

358 for item in value: 

359 dtype = type(item) 

360 all_dtypes.add(dtype) 

361 elements.append(ColumnExpression.literal(item, dtype=dtype)) 

362 if len(all_dtypes) > 1: 

363 raise ExpressionTypeError( 

364 f"Mismatched types in bind iterable: {value} has a mix of {all_dtypes}." 

365 ) 

366 elif not elements: 

367 # Empty container 

368 return ColumnContainer.sequence([]) 

369 else: 

370 (dtype,) = all_dtypes 

371 return ColumnContainer.sequence(elements, dtype=dtype) 

372 return ColumnExpression.literal(value, dtype=type(value)) 

373 tag: ColumnTag 

374 match categorizeConstant(name): 

375 case ExpressionConstant.INGEST_DATE: 

376 assert self.dataset_type_name is not None 

377 tag = DatasetColumnTag(self.dataset_type_name, "ingest_date") 

378 return ColumnExpression.reference(tag, self.column_types.ingest_date_pytype) 

379 case ExpressionConstant.NULL: 

380 return ColumnExpression.literal(None, type(None)) 

381 case None: 

382 pass 

383 case _: 

384 raise AssertionError("Check for enum values should be exhaustive.") 

385 element, column = categorizeElementId(self.universe, name) 

386 if column is not None: 

387 tag = DimensionRecordColumnTag(element.name, column) 

388 dtype = ( 

389 _timespan.Timespan 

390 if column == timespan_database_representation.TimespanDatabaseRepresentation.NAME 

391 else element.RecordClass.fields.standard[column].getPythonType() 

392 ) 

393 return ColumnExpression.reference(tag, dtype) 

394 else: 

395 tag = DimensionKeyColumnTag(element.name) 

396 assert isinstance(element, Dimension) 

397 return ColumnExpression.reference(tag, element.primaryKey.getPythonType()) 

398 

399 def visitIsIn( 

400 self, lhs: VisitorResult, values: list[VisitorResult], not_in: bool, node: Node 

401 ) -> VisitorResult: 

402 # Docstring inherited. 

403 clauses: list[Predicate] = [] 

404 items: list[ColumnExpression] = [] 

405 assert isinstance(lhs, ColumnExpression), "LHS of IN guaranteed to be scalar by parser." 

406 for rhs_item in values: 

407 match rhs_item: 

408 case ColumnExpressionSequence( 

409 items=rhs_items, dtype=rhs_dtype 

410 ) if rhs_dtype is None or rhs_dtype == lhs.dtype: 

411 items.extend(rhs_items) 

412 case ColumnContainer(dtype=lhs.dtype): 

413 clauses.append(rhs_item.contains(lhs)) 

414 case ColumnExpression(dtype=lhs.dtype): 

415 items.append(rhs_item) 

416 case _: 

417 raise ExpressionTypeError( 

418 f"Invalid type {rhs_item.dtype} for element in {lhs.dtype} IN expression '{node}'." 

419 ) 

420 if items: 

421 clauses.append(ColumnContainer.sequence(items, dtype=lhs.dtype).contains(lhs)) 

422 result = Predicate.logical_or(*clauses) 

423 if not_in: 

424 result = result.logical_not() 

425 return result 

426 

427 def visitNumericLiteral(self, value: str, node: Node) -> VisitorResult: 

428 # Docstring inherited. 

429 try: 

430 return ColumnExpression.literal(int(value), dtype=int) 

431 except ValueError: 

432 return ColumnExpression.literal(float(value), dtype=float) 

433 

434 def visitParens(self, expression: VisitorResult, node: Node) -> VisitorResult: 

435 # Docstring inherited. 

436 return expression 

437 

438 def visitPointNode(self, ra: VisitorResult, dec: VisitorResult, node: Node) -> VisitorResult: 

439 # Docstring inherited. 

440 

441 # this is a placeholder for future extension, we enabled syntax but 

442 # do not support actual use just yet. 

443 raise NotImplementedError("POINT() function is not supported yet") 

444 

445 def visitRangeLiteral(self, start: int, stop: int, stride: int | None, node: Node) -> VisitorResult: 

446 # Docstring inherited. 

447 return ColumnContainer.range_literal(range(start, stop + 1, stride or 1)) 

448 

449 def visitStringLiteral(self, value: str, node: Node) -> VisitorResult: 

450 # Docstring inherited. 

451 return ColumnExpression.literal(value, dtype=str) 

452 

453 def visitTimeLiteral(self, value: astropy.time.Time, node: Node) -> VisitorResult: 

454 # Docstring inherited. 

455 return ColumnExpression.literal(value, dtype=astropy.time.Time) 

456 

457 def visitTupleNode(self, items: tuple[VisitorResult, ...], node: Node) -> VisitorResult: 

458 # Docstring inherited. 

459 match items: 

460 case [ 

461 ColumnLiteral(value=begin, dtype=astropy.time.Time | types.NoneType), 

462 ColumnLiteral(value=end, dtype=astropy.time.Time | types.NoneType), 

463 ]: 

464 return ColumnExpression.literal(_timespan.Timespan(begin, end), dtype=_timespan.Timespan) 

465 raise ExpressionTypeError( 

466 f'Invalid type(s) ({items[0].dtype}, {items[1].dtype}) in timespan tuple "{node}" ' 

467 '(Note that date/time strings must be preceded by "T" to be recognized).' 

468 ) 

469 

470 def visitUnaryOp(self, operator: str, operand: VisitorResult, node: Node) -> VisitorResult: 

471 # Docstring inherited. 

472 match (operator, operand): 

473 case ["NOT", Predicate() as operand]: 

474 return operand.logical_not() 

475 case ["+", ColumnExpression(dtype=builtins.int | builtins.float) as operand]: 

476 return operand.method("__pos__") 

477 case ["-", ColumnExpression(dtype=builtins.int | builtins.float) as operand]: 

478 return operand.method("__neg__") 

479 raise ExpressionTypeError( 

480 f"Unary operator {operator!r} is not valid for operand of type {operand.dtype!s} in {node!s}." 

481 )