Coverage for python/lsst/daf/butler/registry/queries/_builder.py : 11%

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__ = ("QueryBuilder",)
25from typing import AbstractSet, Any, Iterable, List, Optional
27import sqlalchemy.sql
29from ...core import (
30 DimensionElement,
31 SkyPixDimension,
32 Dimension,
33 DatasetType,
34 SimpleQuery,
35)
37from ...core.named import NamedKeyDict, NamedValueAbstractSet, NamedValueSet
39from .._collectionType import CollectionType
40from ._structs import QuerySummary, QueryColumns, DatasetQueryColumns, RegistryManagers
41from .expressions import ClauseVisitor
42from ._query import DirectQuery, DirectQueryUniqueness, EmptyQuery, Query
43from ..wildcards import CollectionSearch, CollectionQuery
46class QueryBuilder:
47 """A builder for potentially complex queries that join tables based
48 on dimension relationships.
50 Parameters
51 ----------
52 summary : `QuerySummary`
53 Struct organizing the dimensions involved in the query.
54 managers : `RegistryManagers`
55 A struct containing the registry manager instances used by the query
56 system.
57 """
58 def __init__(self, summary: QuerySummary, managers: RegistryManagers):
59 self.summary = summary
60 self._simpleQuery = SimpleQuery()
61 self._elements: NamedKeyDict[DimensionElement, sqlalchemy.sql.FromClause] = NamedKeyDict()
62 self._columns = QueryColumns()
63 self._managers = managers
65 def hasDimensionKey(self, dimension: Dimension) -> bool:
66 """Return `True` if the given dimension's primary key column has
67 been included in the query (possibly via a foreign key column on some
68 other table).
69 """
70 return dimension in self._columns.keys
72 def joinDimensionElement(self, element: DimensionElement) -> None:
73 """Add the table for a `DimensionElement` to the query.
75 This automatically joins the element table to all other tables in the
76 query with which it is related, via both dimension keys and spatial
77 and temporal relationships.
79 External calls to this method should rarely be necessary; `finish` will
80 automatically call it if the `DimensionElement` has been identified as
81 one that must be included.
83 Parameters
84 ----------
85 element : `DimensionElement`
86 Element for which a table should be added. The element must be
87 associated with a database table (see `DimensionElement.hasTable`).
88 """
89 assert element not in self._elements, "Element already included in query."
90 storage = self._managers.dimensions[element]
91 fromClause = storage.join(
92 self,
93 regions=self._columns.regions if element in self.summary.spatial else None,
94 timespans=self._columns.timespans if element in self.summary.temporal else None,
95 )
96 self._elements[element] = fromClause
98 def joinDataset(self, datasetType: DatasetType, collections: Any, *,
99 isResult: bool = True, findFirst: bool = False) -> bool:
100 """Add a dataset search or constraint to the query.
102 Unlike other `QueryBuilder` join methods, this *must* be called
103 directly to search for datasets of a particular type or constrain the
104 query results based on the exists of datasets. However, all dimensions
105 used to identify the dataset type must have already been included in
106 `QuerySummary.requested` when initializing the `QueryBuilder`.
108 Parameters
109 ----------
110 datasetType : `DatasetType`
111 The type of datasets to search for.
112 collections : `Any`
113 An expression that fully or partially identifies the collections
114 to search for datasets, such as a `str`, `re.Pattern`, or iterable
115 thereof. `...` can be used to return all collections. See
116 :ref:`daf_butler_collection_expressions` for more information.
117 isResult : `bool`, optional
118 If `True` (default), include the dataset ID column in the
119 result columns of the query, allowing complete `DatasetRef`
120 instances to be produced from the query results for this dataset
121 type. If `False`, the existence of datasets of this type is used
122 only to constrain the data IDs returned by the query.
123 `joinDataset` may be called with ``isResult=True`` at most one time
124 on a particular `QueryBuilder` instance.
125 findFirst : `bool`, optional
126 If `True` (`False` is default), only include the first match for
127 each data ID, searching the given collections in order. Requires
128 that all entries in ``collections`` be regular strings, so there is
129 a clear search order. Ignored if ``isResult`` is `False`.
131 Returns
132 -------
133 anyRecords : `bool`
134 If `True`, joining the dataset table was successful and the query
135 should proceed. If `False`, we were able to determine (from the
136 combination of ``datasetType`` and ``collections``) that there
137 would be no results joined in from this dataset, and hence (due to
138 the inner join that would normally be present), the full query will
139 return no results.
140 """
141 assert datasetType.dimensions.issubset(self.summary.requested)
142 if isResult and findFirst:
143 collections = CollectionSearch.fromExpression(collections)
144 else:
145 collections = CollectionQuery.fromExpression(collections)
146 # If we are searching all collections with no constraints, loop over
147 # RUN collections only, because that will include all datasets.
148 collectionTypes: AbstractSet[CollectionType]
149 if collections == CollectionQuery():
150 collectionTypes = {CollectionType.RUN}
151 else:
152 collectionTypes = CollectionType.all()
153 datasetRecordStorage = self._managers.datasets.find(datasetType.name)
154 if datasetRecordStorage is None:
155 # Unrecognized dataset type means no results. It might be better
156 # to raise here, but this is consistent with previous behavior,
157 # which is expected by QuantumGraph generation code in pipe_base.
158 return False
159 subsubqueries = []
160 runKeyName = self._managers.collections.getRunForeignKeyName()
161 baseColumnNames = {"id", runKeyName} if isResult else set()
162 baseColumnNames.update(datasetType.dimensions.required.names)
163 for rank, collectionRecord in enumerate(collections.iter(self._managers.collections,
164 collectionTypes=collectionTypes)):
165 if collectionRecord.type is CollectionType.CALIBRATION:
166 if datasetType.isCalibration():
167 raise NotImplementedError(
168 f"Query for dataset type '{datasetType.name}' in CALIBRATION-type collection "
169 f"'{collectionRecord.name}' is not yet supported."
170 )
171 else:
172 # We can never find a non-calibration dataset in a
173 # CALIBRATION collection.
174 continue
175 ssq = datasetRecordStorage.select(collection=collectionRecord,
176 dataId=SimpleQuery.Select,
177 id=SimpleQuery.Select if isResult else None,
178 run=SimpleQuery.Select if isResult else None)
179 if ssq is None:
180 continue
181 assert {c.name for c in ssq.columns} == baseColumnNames
182 if findFirst:
183 ssq.columns.append(sqlalchemy.sql.literal(rank).label("rank"))
184 subsubqueries.append(ssq.combine())
185 if not subsubqueries:
186 return False
187 subquery = sqlalchemy.sql.union_all(*subsubqueries)
188 columns: Optional[DatasetQueryColumns] = None
189 if isResult:
190 if findFirst:
191 # Rewrite the subquery (currently a UNION ALL over
192 # per-collection subsubqueries) to select the rows with the
193 # lowest rank per data ID. The block below will set subquery
194 # to something like this:
195 #
196 # WITH {dst}_search AS (
197 # SELECT {data-id-cols}, id, run_id, 1 AS rank
198 # FROM <collection1>
199 # UNION ALL
200 # SELECT {data-id-cols}, id, run_id, 2 AS rank
201 # FROM <collection2>
202 # UNION ALL
203 # ...
204 # )
205 # SELECT
206 # {dst}_window.{data-id-cols},
207 # {dst}_window.id,
208 # {dst}_window.run_id
209 # FROM (
210 # SELECT
211 # {dst}_search.{data-id-cols},
212 # {dst}_search.id,
213 # {dst}_search.run_id,
214 # ROW_NUMBER() OVER (
215 # PARTITION BY {dst_search}.{data-id-cols}
216 # ORDER BY rank
217 # ) AS rownum
218 # ) {dst}_window
219 # WHERE
220 # {dst}_window.rownum = 1;
221 #
222 search = subquery.cte(f"{datasetType.name}_search")
223 windowDataIdCols = [
224 search.columns[name].label(name) for name in datasetType.dimensions.required.names
225 ]
226 windowSelectCols = [
227 search.columns["id"].label("id"),
228 search.columns[runKeyName].label(runKeyName)
229 ]
230 windowSelectCols += windowDataIdCols
231 assert {c.name for c in windowSelectCols} == baseColumnNames
232 windowSelectCols.append(
233 sqlalchemy.sql.func.row_number().over(
234 partition_by=windowDataIdCols,
235 order_by=search.columns["rank"]
236 ).label("rownum")
237 )
238 window = sqlalchemy.sql.select(
239 windowSelectCols
240 ).select_from(search).alias(
241 f"{datasetType.name}_window"
242 )
243 subquery = sqlalchemy.sql.select(
244 [window.columns[name].label(name) for name in baseColumnNames]
245 ).select_from(
246 window
247 ).where(
248 window.columns["rownum"] == 1
249 ).alias(datasetType.name)
250 else:
251 subquery = subquery.alias(datasetType.name)
252 columns = DatasetQueryColumns(
253 datasetType=datasetType,
254 id=subquery.columns["id"],
255 runKey=subquery.columns[runKeyName],
256 )
257 else:
258 subquery = subquery.alias(datasetType.name)
259 self.joinTable(subquery, datasetType.dimensions.required, datasets=columns)
260 return True
262 def joinTable(self, table: sqlalchemy.sql.FromClause, dimensions: NamedValueAbstractSet[Dimension], *,
263 datasets: Optional[DatasetQueryColumns] = None) -> None:
264 """Join an arbitrary table to the query via dimension relationships.
266 External calls to this method should only be necessary for tables whose
267 records represent neither datasets nor dimension elements.
269 Parameters
270 ----------
271 table : `sqlalchemy.sql.FromClause`
272 SQLAlchemy object representing the logical table (which may be a
273 join or subquery expression) to be joined.
274 dimensions : iterable of `Dimension`
275 The dimensions that relate this table to others that may be in the
276 query. The table must have columns with the names of the
277 dimensions.
278 datasets : `DatasetQueryColumns`, optional
279 Columns that identify a dataset that is part of the query results.
280 """
281 unexpectedDimensions = NamedValueSet(dimensions - self.summary.requested.dimensions)
282 unexpectedDimensions.discard(self.summary.universe.commonSkyPix)
283 if unexpectedDimensions:
284 raise NotImplementedError(
285 f"QueryBuilder does not yet support joining in dimensions {unexpectedDimensions} that "
286 f"were not provided originally to the QuerySummary object passed at construction."
287 )
288 joinOn = self.startJoin(table, dimensions, dimensions.names)
289 self.finishJoin(table, joinOn)
290 if datasets is not None:
291 assert self._columns.datasets is None, \
292 "At most one result dataset type can be returned by a query."
293 self._columns.datasets = datasets
295 def startJoin(self, table: sqlalchemy.sql.FromClause, dimensions: Iterable[Dimension],
296 columnNames: Iterable[str]
297 ) -> List[sqlalchemy.sql.ColumnElement]:
298 """Begin a join on dimensions.
300 Must be followed by call to `finishJoin`.
302 Parameters
303 ----------
304 table : `sqlalchemy.sql.FromClause`
305 SQLAlchemy object representing the logical table (which may be a
306 join or subquery expression) to be joined.
307 dimensions : iterable of `Dimension`
308 The dimensions that relate this table to others that may be in the
309 query. The table must have columns with the names of the
310 dimensions.
311 columnNames : iterable of `str`
312 Names of the columns that correspond to dimension key values; must
313 be `zip` iterable with ``dimensions``.
315 Returns
316 -------
317 joinOn : `list` of `sqlalchemy.sql.ColumnElement`
318 Sequence of boolean expressions that should be combined with AND
319 to form (part of) the ON expression for this JOIN.
320 """
321 joinOn = []
322 for dimension, columnName in zip(dimensions, columnNames):
323 columnInTable = table.columns[columnName]
324 columnsInQuery = self._columns.keys.setdefault(dimension, [])
325 for columnInQuery in columnsInQuery:
326 joinOn.append(columnInQuery == columnInTable)
327 columnsInQuery.append(columnInTable)
328 return joinOn
330 def finishJoin(self, table: sqlalchemy.sql.FromClause, joinOn: List[sqlalchemy.sql.ColumnElement]
331 ) -> None:
332 """Complete a join on dimensions.
334 Must be preceded by call to `startJoin`.
336 Parameters
337 ----------
338 table : `sqlalchemy.sql.FromClause`
339 SQLAlchemy object representing the logical table (which may be a
340 join or subquery expression) to be joined. Must be the same object
341 passed to `startJoin`.
342 joinOn : `list` of `sqlalchemy.sql.ColumnElement`
343 Sequence of boolean expressions that should be combined with AND
344 to form (part of) the ON expression for this JOIN. Should include
345 at least the elements of the list returned by `startJoin`.
346 """
347 onclause: Optional[sqlalchemy.sql.ColumnElement]
348 if len(joinOn) == 0:
349 onclause = None
350 elif len(joinOn) == 1:
351 onclause = joinOn[0]
352 else:
353 onclause = sqlalchemy.sql.and_(*joinOn)
354 self._simpleQuery.join(table, onclause=onclause)
356 def _joinMissingDimensionElements(self) -> None:
357 """Join all dimension element tables that were identified as necessary
358 by `QuerySummary` and have not yet been joined.
360 For internal use by `QueryBuilder` only; will be called (and should
361 only by called) by `finish`.
362 """
363 # Join all DimensionElement tables that we need for spatial/temporal
364 # joins/filters or a nontrivial WHERE expression.
365 # We iterate over these in *reverse* topological order to minimize the
366 # number of tables joined. For example, the "visit" table provides
367 # the primary key value for the "instrument" table it depends on, so we
368 # don't need to join "instrument" as well unless we had a nontrivial
369 # expression on it (and hence included it already above).
370 for element in self.summary.universe.sorted(self.summary.mustHaveTableJoined, reverse=True):
371 self.joinDimensionElement(element)
372 # Join in any requested Dimension tables that don't already have their
373 # primary keys identified by the query.
374 for dimension in self.summary.universe.sorted(self.summary.mustHaveKeysJoined, reverse=True):
375 if dimension not in self._columns.keys:
376 self.joinDimensionElement(dimension)
378 def _addWhereClause(self) -> None:
379 """Add a WHERE clause to the query under construction, connecting all
380 joined dimensions to the expression and data ID dimensions from
381 `QuerySummary`.
383 For internal use by `QueryBuilder` only; will be called (and should
384 only by called) by `finish`.
385 """
386 if self.summary.expression.tree is not None:
387 visitor = ClauseVisitor(self.summary.universe, self._columns, self._elements)
388 self._simpleQuery.where.append(self.summary.expression.tree.visit(visitor))
389 for dimension, columnsInQuery in self._columns.keys.items():
390 if dimension in self.summary.dataId.graph:
391 givenKey = self.summary.dataId[dimension]
392 # Add a WHERE term for each column that corresponds to each
393 # key. This is redundant with the JOIN ON clauses that make
394 # them equal to each other, but more constraints have a chance
395 # of making things easier on the DB's query optimizer.
396 for columnInQuery in columnsInQuery:
397 self._simpleQuery.where.append(columnInQuery == givenKey)
398 else:
399 # Dimension is not fully identified, but it might be a skypix
400 # dimension that's constrained by a given region.
401 if self.summary.whereRegion is not None and isinstance(dimension, SkyPixDimension):
402 # We know the region now.
403 givenSkyPixIds: List[int] = []
404 for begin, end in dimension.pixelization.envelope(self.summary.whereRegion):
405 givenSkyPixIds.extend(range(begin, end))
406 for columnInQuery in columnsInQuery:
407 self._simpleQuery.where.append(columnInQuery.in_(givenSkyPixIds))
408 # If we are given an dataId with a timespan, and there are one or more
409 # timespans in the query that aren't given, add a WHERE expression for
410 # each of them.
411 if self.summary.dataId.graph.temporal and self.summary.temporal:
412 # Timespan is known now.
413 givenInterval = self.summary.dataId.timespan
414 assert givenInterval is not None
415 for element, intervalInQuery in self._columns.timespans.items():
416 assert element not in self.summary.dataId.graph.elements
417 self._simpleQuery.where.append(intervalInQuery.overlaps(givenInterval))
419 def finish(self, joinMissing: bool = True) -> Query:
420 """Finish query constructing, returning a new `Query` instance.
422 Parameters
423 ----------
424 joinMissing : `bool`, optional
425 If `True` (default), automatically join any missing dimension
426 element tables (according to the categorization of the
427 `QuerySummary` the builder was constructed with). `False` should
428 only be passed if the caller can independently guarantee that all
429 dimension relationships are already captured in non-dimension
430 tables that have been manually included in the query.
432 Returns
433 -------
434 query : `Query`
435 A `Query` object that can be executed and used to interpret result
436 rows.
437 """
438 if joinMissing:
439 self._joinMissingDimensionElements()
440 self._addWhereClause()
441 if self._columns.isEmpty():
442 return EmptyQuery(self.summary.requested.universe, managers=self._managers)
443 return DirectQuery(graph=self.summary.requested,
444 uniqueness=DirectQueryUniqueness.NOT_UNIQUE,
445 whereRegion=self.summary.dataId.region,
446 simpleQuery=self._simpleQuery,
447 columns=self._columns,
448 managers=self._managers)