Coverage for python/lsst/daf/butler/registry/queries/_structs.py : 42%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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 program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <http://www.gnu.org/licenses/>.
21from __future__ import annotations
23__all__ = ["QuerySummary", "RegistryManagers"] # other classes here are local to subpackage
25from dataclasses import dataclass
26from typing import Iterator, List, Optional, Union
28from sqlalchemy.sql import ColumnElement
30from lsst.sphgeom import Region
31from ...core import (
32 DataCoordinate,
33 DatasetType,
34 Dimension,
35 DimensionElement,
36 DimensionGraph,
37 DimensionUniverse,
38 NamedKeyDict,
39 NamedValueSet,
40 SkyPixDimension,
41 Timespan,
42)
43from ..interfaces import (
44 CollectionManager,
45 DatasetRecordStorageManager,
46 DimensionRecordStorageManager,
47)
48# We're not trying to add typing to the lex/yacc parser code, so MyPy
49# doesn't know about some of these imports.
50from .exprParser import Node, ParserYacc # type: ignore
53@dataclass
54class QueryWhereExpression:
55 """A struct representing a parsed user-provided WHERE expression.
57 Parameters
58 ----------
59 universe : `DimensionUniverse`
60 All known dimensions.
61 expression : `str`, optional
62 The string expression to parse.
63 """
64 def __init__(self, universe: DimensionUniverse, expression: Optional[str] = None):
65 if expression:
66 from .expressions import InspectionVisitor
67 try:
68 parser = ParserYacc()
69 self.tree = parser.parse(expression)
70 except Exception as exc:
71 raise RuntimeError(f"Failed to parse user expression `{expression}'.") from exc
72 visitor = InspectionVisitor(universe)
73 assert self.tree is not None
74 self.tree.visit(visitor)
75 self.keys = visitor.keys
76 self.metadata = visitor.metadata
77 else:
78 self.tree = None
79 self.keys = NamedValueSet()
80 self.metadata = NamedKeyDict()
82 tree: Optional[Node]
83 """The parsed user expression tree, if present (`Node` or `None`).
84 """
86 keys: NamedValueSet[Dimension]
87 """All dimensions whose keys are referenced by the expression
88 (`NamedValueSet` of `Dimension`).
89 """
91 metadata: NamedKeyDict[DimensionElement, List[str]]
92 """All dimension elements metadata fields referenced by the expression
93 (`NamedKeyDict` mapping `DimensionElement` to a `set` of field names).
94 """
97@dataclass
98class QuerySummary:
99 """A struct that holds and categorizes the dimensions involved in a query.
101 A `QuerySummary` instance is necessary to construct a `QueryBuilder`, and
102 it needs to include all of the dimensions that will be included in the
103 query (including any needed for querying datasets).
105 Parameters
106 ----------
107 requested : `DimensionGraph`
108 The dimensions whose primary keys should be included in the result rows
109 of the query.
110 dataId : `DataCoordinate`, optional
111 A fully-expanded data ID identifying dimensions known in advance. If
112 not provided, will be set to an empty data ID. ``dataId.hasRecords()``
113 must return `True`.
114 expression : `str` or `QueryWhereExpression`, optional
115 A user-provided string WHERE expression.
116 whereRegion : `lsst.sphgeom.Region`, optional
117 A spatial region that all rows must overlap. If `None` and ``dataId``
118 is not `None`, ``dataId.region`` will be used.
119 """
120 def __init__(self, requested: DimensionGraph, *,
121 dataId: Optional[DataCoordinate] = None,
122 expression: Optional[Union[str, QueryWhereExpression]] = None,
123 whereRegion: Optional[Region] = None):
124 self.requested = requested
125 self.dataId = dataId if dataId is not None else DataCoordinate.makeEmpty(requested.universe)
126 self.expression = (expression if isinstance(expression, QueryWhereExpression)
127 else QueryWhereExpression(requested.universe, expression))
128 if whereRegion is None and self.dataId is not None:
129 whereRegion = self.dataId.region
130 self.whereRegion = whereRegion
132 requested: DimensionGraph
133 """Dimensions whose primary keys should be included in the result rows of
134 the query (`DimensionGraph`).
135 """
137 dataId: DataCoordinate
138 """A data ID identifying dimensions known before query construction
139 (`DataCoordinate`).
141 ``dataId.hasRecords()`` is guaranteed to return `True`.
142 """
144 whereRegion: Optional[Region]
145 """A spatial region that all result rows must overlap
146 (`lsst.sphgeom.Region` or `None`).
147 """
149 expression: QueryWhereExpression
150 """Information about any parsed user WHERE expression
151 (`QueryWhereExpression`).
152 """
154 @property
155 def universe(self) -> DimensionUniverse:
156 """All known dimensions (`DimensionUniverse`).
157 """
158 return self.requested.universe
160 @property
161 def spatial(self) -> NamedValueSet[DimensionElement]:
162 """Dimension elements whose regions and skypix IDs should be included
163 in the query (`NamedValueSet` of `DimensionElement`).
164 """
165 # An element may participate spatially in the query if:
166 # - it's the most precise spatial element for its system in the
167 # requested dimensions (i.e. in `self.requested.spatial`);
168 # - it isn't also given at query construction time.
169 result = NamedValueSet(self.mustHaveKeysJoined.spatial - self.dataId.graph.elements)
170 if len(result) == 1:
171 # There's no spatial join, but there might be a WHERE filter based
172 # on a given region.
173 if self.dataId.graph.spatial:
174 # We can only perform those filters against SkyPix dimensions,
175 # so if what we have isn't one, add the common SkyPix dimension
176 # to the query; the element we have will be joined to that.
177 element, = result
178 if not isinstance(element, SkyPixDimension):
179 result.add(self.universe.commonSkyPix)
180 else:
181 # There is no spatial join or filter in this query. Even
182 # if this element might be associated with spatial
183 # information, we don't need it for this query.
184 return NamedValueSet()
185 elif len(result) > 1:
186 # There's a spatial join. Those require the common SkyPix
187 # system to be included in the query in order to connect them.
188 result.add(self.universe.commonSkyPix)
189 return result
191 @property
192 def temporal(self) -> NamedValueSet[DimensionElement]:
193 """Dimension elements whose timespans should be included in the
194 query (`NamedValueSet` of `DimensionElement`).
195 """
196 # An element may participate temporally in the query if:
197 # - it's the most precise temporal element for its system in the
198 # requested dimensions (i.e. in `self.requested.temporal`);
199 # - it isn't also given at query construction time.
200 result = NamedValueSet(self.mustHaveKeysJoined.temporal - self.dataId.graph.elements)
201 if len(result) == 1 and not self.dataId.graph.temporal:
202 # No temporal join or filter. Even if this element might be
203 # associated with temporal information, we don't need it for this
204 # query.
205 return NamedValueSet()
206 return result
208 @property
209 def mustHaveKeysJoined(self) -> DimensionGraph:
210 """Dimensions whose primary keys must be used in the JOIN ON clauses
211 of the query, even if their tables do not appear (`DimensionGraph`).
213 A `Dimension` primary key can appear in a join clause without its table
214 via a foreign key column in table of a dependent dimension element or
215 dataset.
216 """
217 names = set(self.requested.names | self.expression.keys.names)
218 return DimensionGraph(self.universe, names=names)
220 @property
221 def mustHaveTableJoined(self) -> NamedValueSet[DimensionElement]:
222 """Dimension elements whose associated tables must appear in the
223 query's FROM clause (`NamedValueSet` of `DimensionElement`).
224 """
225 result = NamedValueSet(self.spatial | self.temporal | self.expression.metadata.keys())
226 for dimension in self.mustHaveKeysJoined:
227 if dimension.implied:
228 result.add(dimension)
229 for element in self.mustHaveKeysJoined.union(self.dataId.graph).elements:
230 if element.alwaysJoin:
231 result.add(element)
232 return result
235@dataclass
236class DatasetQueryColumns:
237 """A struct containing the columns used to reconstruct `DatasetRef`
238 instances from query results.
239 """
241 datasetType: DatasetType
242 """The dataset type being queried (`DatasetType`).
243 """
245 id: ColumnElement
246 """Column containing the unique integer ID for this dataset.
247 """
249 runKey: ColumnElement
250 """Foreign key column to the `~CollectionType.RUN` collection that holds
251 this dataset.
252 """
254 def __iter__(self) -> Iterator[ColumnElement]:
255 yield self.id
256 yield self.runKey
259@dataclass
260class QueryColumns:
261 """A struct organizing the columns in an under-construction or currently-
262 executing query.
264 Takes no parameters at construction, as expected usage is to add elements
265 to its container attributes incrementally.
266 """
267 def __init__(self) -> None:
268 self.keys = NamedKeyDict()
269 self.timespans = NamedKeyDict()
270 self.regions = NamedKeyDict()
271 self.datasets = None
273 keys: NamedKeyDict[Dimension, List[ColumnElement]]
274 """Columns that correspond to the primary key values of dimensions
275 (`NamedKeyDict` mapping `Dimension` to a `list` of `ColumnElement`).
277 Each value list contains columns from multiple tables corresponding to the
278 same dimension, and the query should constrain the values of those columns
279 to be the same.
281 In a `Query`, the keys of this dictionary must include at least the
282 dimensions in `QuerySummary.requested` and `QuerySummary.dataId.graph`.
283 """
285 timespans: NamedKeyDict[DimensionElement, Timespan[ColumnElement]]
286 """Columns that correspond to timespans for elements that participate in a
287 temporal join or filter in the query (`NamedKeyDict` mapping
288 `DimensionElement` to `Timespan` of `ColumnElement`).
290 In a `Query`, the keys of this dictionary must be exactly the elements
291 in `QuerySummary.temporal`.
292 """
294 regions: NamedKeyDict[DimensionElement, ColumnElement]
295 """Columns that correspond to regions for elements that participate in a
296 spatial join or filter in the query (`NamedKeyDict` mapping
297 `DimensionElement` to `ColumnElement`).
299 In a `Query`, the keys of this dictionary must be exactly the elements
300 in `QuerySummary.spatial`.
301 """
303 datasets: Optional[DatasetQueryColumns]
304 """Columns that can be used to construct `DatasetRef` instances from query
305 results.
306 (`DatasetQueryColumns` or `None`).
307 """
309 def isEmpty(self) -> bool:
310 """Return `True` if this query has no columns at all.
311 """
312 return not (self.keys or self.timespans or self.regions or self.datasets is not None)
314 def getKeyColumn(self, dimension: Union[Dimension, str]) -> ColumnElement:
315 """ Return one of the columns in self.keys for the given dimension.
317 The column selected is an implentation detail but is guaranteed to
318 be deterministic and consistent across multiple calls.
320 Parameters
321 ----------
322 dimension : `Dimension` or `str`
323 Dimension for which to obtain a key column.
325 Returns
326 -------
327 column : `sqlalchemy.sql.ColumnElement`
328 SQLAlchemy column object.
329 """
330 # Choosing the last element here is entirely for human readers of the
331 # query (e.g. developers debugging things); it makes it more likely a
332 # dimension key will be provided by the dimension's own table, or
333 # failing that, some closely related dimension, which might be less
334 # surprising to see than e.g. some dataset subquery. From the
335 # database's perspective this is entirely arbitrary, because the query
336 # guarantees they all have equal values.
337 return self.keys[dimension][-1]
340@dataclass
341class RegistryManagers:
342 """Struct used to pass around the manager objects that back a `Registry`
343 and are used internally by the query system.
344 """
346 collections: CollectionManager
347 """Manager for collections (`CollectionManager`).
348 """
350 datasets: DatasetRecordStorageManager
351 """Manager for datasets and dataset types (`DatasetRecordStorageManager`).
352 """
354 dimensions: DimensionRecordStorageManager
355 """Manager for dimensions (`DimensionRecordStorageManager`).
356 """