Coverage for python/lsst/daf/butler/registries/sql.py : 13%

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/>.
22from __future__ import annotations
24__all__ = (
25 "SqlRegistry",
26)
28from collections import defaultdict
29import contextlib
30import logging
31from typing import (
32 Any,
33 Dict,
34 Iterable,
35 Iterator,
36 List,
37 Mapping,
38 Optional,
39 Set,
40 TYPE_CHECKING,
41 Union,
42)
44import sqlalchemy
46from ..core import (
47 ButlerURI,
48 Config,
49 DataCoordinate,
50 DataCoordinateIterable,
51 DataId,
52 DatasetAssociation,
53 DatasetId,
54 DatasetRef,
55 DatasetType,
56 ddl,
57 Dimension,
58 DimensionConfig,
59 DimensionElement,
60 DimensionGraph,
61 DimensionRecord,
62 DimensionUniverse,
63 NamedKeyMapping,
64 NameLookupMapping,
65 Progress,
66 StorageClassFactory,
67 Timespan,
68)
69from ..core.utils import iterable, transactional
71from ..registry import (
72 Registry,
73 RegistryConfig,
74 CollectionType,
75 RegistryDefaults,
76 ConflictingDefinitionError,
77 InconsistentDataIdError,
78 OrphanedRecordError,
79 CollectionSearch,
80)
81from ..registry import queries
82from ..registry.wildcards import CategorizedWildcard, CollectionQuery, Ellipsis
83from ..registry.summaries import CollectionSummary
84from ..registry.managers import RegistryManagerTypes, RegistryManagerInstances
85from ..registry.interfaces import ChainedCollectionRecord, DatasetIdGenEnum, RunRecord
87if TYPE_CHECKING: 87 ↛ 88line 87 didn't jump to line 88, because the condition on line 87 was never true
88 from .._butlerConfig import ButlerConfig
89 from ..registry.interfaces import (
90 CollectionRecord,
91 Database,
92 DatastoreRegistryBridgeManager,
93 )
96_LOG = logging.getLogger(__name__)
99class SqlRegistry(Registry):
100 """Registry implementation based on SQLAlchemy.
102 Parameters
103 ----------
104 database : `Database`
105 Database instance to store Registry.
106 defaults : `RegistryDefaults`
107 Default collection search path and/or output `~CollectionType.RUN`
108 collection.
109 managers : `RegistryManagerInstances`
110 All the managers required for this registry.
111 """
113 defaultConfigFile: Optional[str] = None
114 """Path to configuration defaults. Accessed within the ``configs`` resource
115 or relative to a search path. Can be None if no defaults specified.
116 """
118 @classmethod
119 def createFromConfig(cls, config: Optional[Union[RegistryConfig, str]] = None,
120 dimensionConfig: Optional[Union[DimensionConfig, str]] = None,
121 butlerRoot: Optional[str] = None) -> Registry:
122 """Create registry database and return `SqlRegistry` instance.
124 This method initializes database contents, database must be empty
125 prior to calling this method.
127 Parameters
128 ----------
129 config : `RegistryConfig` or `str`, optional
130 Registry configuration, if missing then default configuration will
131 be loaded from registry.yaml.
132 dimensionConfig : `DimensionConfig` or `str`, optional
133 Dimensions configuration, if missing then default configuration
134 will be loaded from dimensions.yaml.
135 butlerRoot : `str`, optional
136 Path to the repository root this `SqlRegistry` will manage.
138 Returns
139 -------
140 registry : `SqlRegistry`
141 A new `SqlRegistry` instance.
142 """
143 config = cls.forceRegistryConfig(config)
144 config.replaceRoot(butlerRoot)
146 if isinstance(dimensionConfig, str):
147 dimensionConfig = DimensionConfig(config)
148 elif dimensionConfig is None:
149 dimensionConfig = DimensionConfig()
150 elif not isinstance(dimensionConfig, DimensionConfig):
151 raise TypeError(f"Incompatible Dimension configuration type: {type(dimensionConfig)}")
153 DatabaseClass = config.getDatabaseClass()
154 database = DatabaseClass.fromUri(str(config.connectionString), origin=config.get("origin", 0),
155 namespace=config.get("namespace"))
156 managerTypes = RegistryManagerTypes.fromConfig(config)
157 managers = managerTypes.makeRepo(database, dimensionConfig)
158 return cls(database, RegistryDefaults(), managers)
160 @classmethod
161 def fromConfig(cls, config: Union[ButlerConfig, RegistryConfig, Config, str],
162 butlerRoot: Optional[Union[str, ButlerURI]] = None, writeable: bool = True,
163 defaults: Optional[RegistryDefaults] = None) -> Registry:
164 """Create `Registry` subclass instance from `config`.
166 Registry database must be inbitialized prior to calling this method.
168 Parameters
169 ----------
170 config : `ButlerConfig`, `RegistryConfig`, `Config` or `str`
171 Registry configuration
172 butlerRoot : `str` or `ButlerURI`, optional
173 Path to the repository root this `Registry` will manage.
174 writeable : `bool`, optional
175 If `True` (default) create a read-write connection to the database.
176 defaults : `RegistryDefaults`, optional
177 Default collection search path and/or output `~CollectionType.RUN`
178 collection.
180 Returns
181 -------
182 registry : `SqlRegistry` (subclass)
183 A new `SqlRegistry` subclass instance.
184 """
185 config = cls.forceRegistryConfig(config)
186 config.replaceRoot(butlerRoot)
187 DatabaseClass = config.getDatabaseClass()
188 database = DatabaseClass.fromUri(str(config.connectionString), origin=config.get("origin", 0),
189 namespace=config.get("namespace"), writeable=writeable)
190 managerTypes = RegistryManagerTypes.fromConfig(config)
191 managers = managerTypes.loadRepo(database)
192 if defaults is None:
193 defaults = RegistryDefaults()
194 return cls(database, defaults, managers)
196 def __init__(self, database: Database, defaults: RegistryDefaults, managers: RegistryManagerInstances):
197 self._db = database
198 self._managers = managers
199 self.storageClasses = StorageClassFactory()
200 # Intentionally invoke property setter to initialize defaults. This
201 # can only be done after most of the rest of Registry has already been
202 # initialized, and must be done before the property getter is used.
203 self.defaults = defaults
205 def __str__(self) -> str:
206 return str(self._db)
208 def __repr__(self) -> str:
209 return f"SqlRegistry({self._db!r}, {self.dimensions!r})"
211 def isWriteable(self) -> bool:
212 # Docstring inherited from lsst.daf.butler.registry.Registry
213 return self._db.isWriteable()
215 def copy(self, defaults: Optional[RegistryDefaults] = None) -> Registry:
216 # Docstring inherited from lsst.daf.butler.registry.Registry
217 if defaults is None:
218 # No need to copy, because `RegistryDefaults` is immutable; we
219 # effectively copy on write.
220 defaults = self.defaults
221 return type(self)(self._db, defaults, self._managers)
223 @property
224 def dimensions(self) -> DimensionUniverse:
225 # Docstring inherited from lsst.daf.butler.registry.Registry
226 return self._managers.dimensions.universe
228 def refresh(self) -> None:
229 # Docstring inherited from lsst.daf.butler.registry.Registry
230 self._managers.refresh()
232 @contextlib.contextmanager
233 def transaction(self, *, savepoint: bool = False) -> Iterator[None]:
234 # Docstring inherited from lsst.daf.butler.registry.Registry
235 try:
236 with self._db.transaction(savepoint=savepoint):
237 yield
238 except BaseException:
239 # TODO: this clears the caches sometimes when we wouldn't actually
240 # need to. Can we avoid that?
241 self._managers.dimensions.clearCaches()
242 raise
244 def resetConnectionPool(self) -> None:
245 """Reset SQLAlchemy connection pool for `SqlRegistry` database.
247 This operation is useful when using registry with fork-based
248 multiprocessing. To use registry across fork boundary one has to make
249 sure that there are no currently active connections (no session or
250 transaction is in progress) and connection pool is reset using this
251 method. This method should be called by the child process immediately
252 after the fork.
253 """
254 self._db._engine.dispose()
256 def registerOpaqueTable(self, tableName: str, spec: ddl.TableSpec) -> None:
257 """Add an opaque (to the `Registry`) table for use by a `Datastore` or
258 other data repository client.
260 Opaque table records can be added via `insertOpaqueData`, retrieved via
261 `fetchOpaqueData`, and removed via `deleteOpaqueData`.
263 Parameters
264 ----------
265 tableName : `str`
266 Logical name of the opaque table. This may differ from the
267 actual name used in the database by a prefix and/or suffix.
268 spec : `ddl.TableSpec`
269 Specification for the table to be added.
270 """
271 self._managers.opaque.register(tableName, spec)
273 @transactional
274 def insertOpaqueData(self, tableName: str, *data: dict) -> None:
275 """Insert records into an opaque table.
277 Parameters
278 ----------
279 tableName : `str`
280 Logical name of the opaque table. Must match the name used in a
281 previous call to `registerOpaqueTable`.
282 data
283 Each additional positional argument is a dictionary that represents
284 a single row to be added.
285 """
286 self._managers.opaque[tableName].insert(*data)
288 def fetchOpaqueData(self, tableName: str, **where: Any) -> Iterator[dict]:
289 """Retrieve records from an opaque table.
291 Parameters
292 ----------
293 tableName : `str`
294 Logical name of the opaque table. Must match the name used in a
295 previous call to `registerOpaqueTable`.
296 where
297 Additional keyword arguments are interpreted as equality
298 constraints that restrict the returned rows (combined with AND);
299 keyword arguments are column names and values are the values they
300 must have.
302 Yields
303 ------
304 row : `dict`
305 A dictionary representing a single result row.
306 """
307 yield from self._managers.opaque[tableName].fetch(**where)
309 @transactional
310 def deleteOpaqueData(self, tableName: str, **where: Any) -> None:
311 """Remove records from an opaque table.
313 Parameters
314 ----------
315 tableName : `str`
316 Logical name of the opaque table. Must match the name used in a
317 previous call to `registerOpaqueTable`.
318 where
319 Additional keyword arguments are interpreted as equality
320 constraints that restrict the deleted rows (combined with AND);
321 keyword arguments are column names and values are the values they
322 must have.
323 """
324 self._managers.opaque[tableName].delete(where.keys(), where)
326 def registerCollection(self, name: str, type: CollectionType = CollectionType.TAGGED,
327 doc: Optional[str] = None) -> None:
328 # Docstring inherited from lsst.daf.butler.registry.Registry
329 self._managers.collections.register(name, type, doc=doc)
331 def getCollectionType(self, name: str) -> CollectionType:
332 # Docstring inherited from lsst.daf.butler.registry.Registry
333 return self._managers.collections.find(name).type
335 def _get_collection_record(self, name: str) -> CollectionRecord:
336 # Docstring inherited from lsst.daf.butler.registry.Registry
337 return self._managers.collections.find(name)
339 def registerRun(self, name: str, doc: Optional[str] = None) -> None:
340 # Docstring inherited from lsst.daf.butler.registry.Registry
341 self._managers.collections.register(name, CollectionType.RUN, doc=doc)
343 @transactional
344 def removeCollection(self, name: str) -> None:
345 # Docstring inherited from lsst.daf.butler.registry.Registry
346 self._managers.collections.remove(name)
348 def getCollectionChain(self, parent: str) -> CollectionSearch:
349 # Docstring inherited from lsst.daf.butler.registry.Registry
350 record = self._managers.collections.find(parent)
351 if record.type is not CollectionType.CHAINED:
352 raise TypeError(f"Collection '{parent}' has type {record.type.name}, not CHAINED.")
353 assert isinstance(record, ChainedCollectionRecord)
354 return record.children
356 @transactional
357 def setCollectionChain(self, parent: str, children: Any, *, flatten: bool = False) -> None:
358 # Docstring inherited from lsst.daf.butler.registry.Registry
359 record = self._managers.collections.find(parent)
360 if record.type is not CollectionType.CHAINED:
361 raise TypeError(f"Collection '{parent}' has type {record.type.name}, not CHAINED.")
362 assert isinstance(record, ChainedCollectionRecord)
363 children = CollectionSearch.fromExpression(children)
364 if children != record.children or flatten:
365 record.update(self._managers.collections, children, flatten=flatten)
367 def getCollectionDocumentation(self, collection: str) -> Optional[str]:
368 # Docstring inherited from lsst.daf.butler.registry.Registry
369 return self._managers.collections.getDocumentation(self._managers.collections.find(collection).key)
371 def setCollectionDocumentation(self, collection: str, doc: Optional[str]) -> None:
372 # Docstring inherited from lsst.daf.butler.registry.Registry
373 self._managers.collections.setDocumentation(self._managers.collections.find(collection).key, doc)
375 def getCollectionSummary(self, collection: str) -> CollectionSummary:
376 # Docstring inherited from lsst.daf.butler.registry.Registry
377 record = self._managers.collections.find(collection)
378 return self._managers.datasets.getCollectionSummary(record)
380 def registerDatasetType(self, datasetType: DatasetType) -> bool:
381 # Docstring inherited from lsst.daf.butler.registry.Registry
382 _, inserted = self._managers.datasets.register(datasetType)
383 return inserted
385 def removeDatasetType(self, name: str) -> None:
386 # Docstring inherited from lsst.daf.butler.registry.Registry
387 self._managers.datasets.remove(name)
389 def getDatasetType(self, name: str) -> DatasetType:
390 # Docstring inherited from lsst.daf.butler.registry.Registry
391 return self._managers.datasets[name].datasetType
393 def findDataset(self, datasetType: Union[DatasetType, str], dataId: Optional[DataId] = None, *,
394 collections: Any = None, timespan: Optional[Timespan] = None,
395 **kwargs: Any) -> Optional[DatasetRef]:
396 # Docstring inherited from lsst.daf.butler.registry.Registry
397 if isinstance(datasetType, DatasetType):
398 storage = self._managers.datasets[datasetType.name]
399 else:
400 storage = self._managers.datasets[datasetType]
401 dataId = DataCoordinate.standardize(dataId, graph=storage.datasetType.dimensions,
402 universe=self.dimensions, defaults=self.defaults.dataId,
403 **kwargs)
404 if collections is None:
405 if not self.defaults.collections:
406 raise TypeError("No collections provided to findDataset, "
407 "and no defaults from registry construction.")
408 collections = self.defaults.collections
409 else:
410 collections = CollectionSearch.fromExpression(collections)
411 for collectionRecord in collections.iter(self._managers.collections):
412 if (collectionRecord.type is CollectionType.CALIBRATION
413 and (not storage.datasetType.isCalibration() or timespan is None)):
414 continue
415 result = storage.find(collectionRecord, dataId, timespan=timespan)
416 if result is not None:
417 return result
419 return None
421 @transactional
422 def insertDatasets(self, datasetType: Union[DatasetType, str], dataIds: Iterable[DataId],
423 run: Optional[str] = None, expand: bool = True,
424 idGenerationMode: DatasetIdGenEnum = DatasetIdGenEnum.UNIQUE) -> List[DatasetRef]:
425 # Docstring inherited from lsst.daf.butler.registry.Registry
426 if isinstance(datasetType, DatasetType):
427 storage = self._managers.datasets.find(datasetType.name)
428 if storage is None:
429 raise LookupError(f"DatasetType '{datasetType}' has not been registered.")
430 else:
431 storage = self._managers.datasets.find(datasetType)
432 if storage is None:
433 raise LookupError(f"DatasetType with name '{datasetType}' has not been registered.")
434 if run is None:
435 if self.defaults.run is None:
436 raise TypeError("No run provided to insertDatasets, "
437 "and no default from registry construction.")
438 run = self.defaults.run
439 runRecord = self._managers.collections.find(run)
440 if runRecord.type is not CollectionType.RUN:
441 raise TypeError(f"Given collection is of type {runRecord.type.name}; RUN collection required.")
442 assert isinstance(runRecord, RunRecord)
443 progress = Progress("daf.butler.Registry.insertDatasets", level=logging.DEBUG)
444 if expand:
445 expandedDataIds = [self.expandDataId(dataId, graph=storage.datasetType.dimensions)
446 for dataId in progress.wrap(dataIds,
447 f"Expanding {storage.datasetType.name} data IDs")]
448 else:
449 expandedDataIds = [DataCoordinate.standardize(dataId, graph=storage.datasetType.dimensions)
450 for dataId in dataIds]
451 try:
452 refs = list(storage.insert(runRecord, expandedDataIds, idGenerationMode))
453 except sqlalchemy.exc.IntegrityError as err:
454 raise ConflictingDefinitionError(f"A database constraint failure was triggered by inserting "
455 f"one or more datasets of type {storage.datasetType} into "
456 f"collection '{run}'. "
457 f"This probably means a dataset with the same data ID "
458 f"and dataset type already exists, but it may also mean a "
459 f"dimension row is missing.") from err
460 return refs
462 @transactional
463 def _importDatasets(self, datasets: Iterable[DatasetRef], expand: bool = True,
464 idGenerationMode: DatasetIdGenEnum = DatasetIdGenEnum.UNIQUE,
465 reuseIds: bool = False) -> List[DatasetRef]:
466 # Docstring inherited from lsst.daf.butler.registry.Registry
467 datasets = list(datasets)
468 if not datasets:
469 # nothing to do
470 return []
472 # find dataset type
473 datasetTypes = set(dataset.datasetType for dataset in datasets)
474 if len(datasetTypes) != 1:
475 raise ValueError(f"Multiple dataset types in input datasets: {datasetTypes}")
476 datasetType = datasetTypes.pop()
478 # get storage handler for this dataset type
479 storage = self._managers.datasets.find(datasetType.name)
480 if storage is None:
481 raise LookupError(f"DatasetType '{datasetType}' has not been registered.")
483 # find run name
484 runs = set(dataset.run for dataset in datasets)
485 if len(runs) != 1:
486 raise ValueError(f"Multiple run names in input datasets: {runs}")
487 run = runs.pop()
488 if run is None:
489 if self.defaults.run is None:
490 raise TypeError("No run provided to ingestDatasets, "
491 "and no default from registry construction.")
492 run = self.defaults.run
494 runRecord = self._managers.collections.find(run)
495 if runRecord.type is not CollectionType.RUN:
496 raise TypeError(f"Given collection is of type {runRecord.type.name}; RUN collection required.")
497 assert isinstance(runRecord, RunRecord)
499 progress = Progress("daf.butler.Registry.insertDatasets", level=logging.DEBUG)
500 if expand:
501 expandedDatasets = [
502 dataset.expanded(self.expandDataId(dataset.dataId, graph=storage.datasetType.dimensions))
503 for dataset in progress.wrap(datasets, f"Expanding {storage.datasetType.name} data IDs")]
504 else:
505 expandedDatasets = [
506 DatasetRef(datasetType, dataset.dataId, id=dataset.id, run=dataset.run, conform=True)
507 for dataset in datasets
508 ]
510 try:
511 refs = list(storage.import_(runRecord, expandedDatasets, idGenerationMode, reuseIds))
512 except sqlalchemy.exc.IntegrityError as err:
513 raise ConflictingDefinitionError(f"A database constraint failure was triggered by inserting "
514 f"one or more datasets of type {storage.datasetType} into "
515 f"collection '{run}'. "
516 f"This probably means a dataset with the same data ID "
517 f"and dataset type already exists, but it may also mean a "
518 f"dimension row is missing.") from err
519 return refs
521 def getDataset(self, id: DatasetId) -> Optional[DatasetRef]:
522 # Docstring inherited from lsst.daf.butler.registry.Registry
523 return self._managers.datasets.getDatasetRef(id)
525 @transactional
526 def removeDatasets(self, refs: Iterable[DatasetRef]) -> None:
527 # Docstring inherited from lsst.daf.butler.registry.Registry
528 progress = Progress("lsst.daf.butler.Registry.removeDatasets", level=logging.DEBUG)
529 for datasetType, refsForType in progress.iter_item_chunks(DatasetRef.groupByType(refs).items(),
530 desc="Removing datasets by type"):
531 storage = self._managers.datasets[datasetType.name]
532 try:
533 storage.delete(refsForType)
534 except sqlalchemy.exc.IntegrityError as err:
535 raise OrphanedRecordError("One or more datasets is still "
536 "present in one or more Datastores.") from err
538 @transactional
539 def associate(self, collection: str, refs: Iterable[DatasetRef]) -> None:
540 # Docstring inherited from lsst.daf.butler.registry.Registry
541 progress = Progress("lsst.daf.butler.Registry.associate", level=logging.DEBUG)
542 collectionRecord = self._managers.collections.find(collection)
543 if collectionRecord.type is not CollectionType.TAGGED:
544 raise TypeError(f"Collection '{collection}' has type {collectionRecord.type.name}, not TAGGED.")
545 for datasetType, refsForType in progress.iter_item_chunks(DatasetRef.groupByType(refs).items(),
546 desc="Associating datasets by type"):
547 storage = self._managers.datasets[datasetType.name]
548 try:
549 storage.associate(collectionRecord, refsForType)
550 except sqlalchemy.exc.IntegrityError as err:
551 raise ConflictingDefinitionError(
552 f"Constraint violation while associating dataset of type {datasetType.name} with "
553 f"collection {collection}. This probably means that one or more datasets with the same "
554 f"dataset type and data ID already exist in the collection, but it may also indicate "
555 f"that the datasets do not exist."
556 ) from err
558 @transactional
559 def disassociate(self, collection: str, refs: Iterable[DatasetRef]) -> None:
560 # Docstring inherited from lsst.daf.butler.registry.Registry
561 progress = Progress("lsst.daf.butler.Registry.disassociate", level=logging.DEBUG)
562 collectionRecord = self._managers.collections.find(collection)
563 if collectionRecord.type is not CollectionType.TAGGED:
564 raise TypeError(f"Collection '{collection}' has type {collectionRecord.type.name}; "
565 "expected TAGGED.")
566 for datasetType, refsForType in progress.iter_item_chunks(DatasetRef.groupByType(refs).items(),
567 desc="Disassociating datasets by type"):
568 storage = self._managers.datasets[datasetType.name]
569 storage.disassociate(collectionRecord, refsForType)
571 @transactional
572 def certify(self, collection: str, refs: Iterable[DatasetRef], timespan: Timespan) -> None:
573 # Docstring inherited from lsst.daf.butler.registry.Registry
574 progress = Progress("lsst.daf.butler.Registry.certify", level=logging.DEBUG)
575 collectionRecord = self._managers.collections.find(collection)
576 for datasetType, refsForType in progress.iter_item_chunks(DatasetRef.groupByType(refs).items(),
577 desc="Certifying datasets by type"):
578 storage = self._managers.datasets[datasetType.name]
579 storage.certify(collectionRecord, refsForType, timespan)
581 @transactional
582 def decertify(self, collection: str, datasetType: Union[str, DatasetType], timespan: Timespan, *,
583 dataIds: Optional[Iterable[DataId]] = None) -> None:
584 # Docstring inherited from lsst.daf.butler.registry.Registry
585 collectionRecord = self._managers.collections.find(collection)
586 if isinstance(datasetType, str):
587 storage = self._managers.datasets[datasetType]
588 else:
589 storage = self._managers.datasets[datasetType.name]
590 standardizedDataIds = None
591 if dataIds is not None:
592 standardizedDataIds = [DataCoordinate.standardize(d, graph=storage.datasetType.dimensions)
593 for d in dataIds]
594 storage.decertify(collectionRecord, timespan, dataIds=standardizedDataIds)
596 def getDatastoreBridgeManager(self) -> DatastoreRegistryBridgeManager:
597 """Return an object that allows a new `Datastore` instance to
598 communicate with this `Registry`.
600 Returns
601 -------
602 manager : `DatastoreRegistryBridgeManager`
603 Object that mediates communication between this `Registry` and its
604 associated datastores.
605 """
606 return self._managers.datastores
608 def getDatasetLocations(self, ref: DatasetRef) -> Iterable[str]:
609 # Docstring inherited from lsst.daf.butler.registry.Registry
610 return self._managers.datastores.findDatastores(ref)
612 def expandDataId(self, dataId: Optional[DataId] = None, *, graph: Optional[DimensionGraph] = None,
613 records: Optional[NameLookupMapping[DimensionElement, Optional[DimensionRecord]]] = None,
614 withDefaults: bool = True,
615 **kwargs: Any) -> DataCoordinate:
616 # Docstring inherited from lsst.daf.butler.registry.Registry
617 if not withDefaults:
618 defaults = None
619 else:
620 defaults = self.defaults.dataId
621 standardized = DataCoordinate.standardize(dataId, graph=graph, universe=self.dimensions,
622 defaults=defaults, **kwargs)
623 if standardized.hasRecords():
624 return standardized
625 if records is None:
626 records = {}
627 elif isinstance(records, NamedKeyMapping):
628 records = records.byName()
629 else:
630 records = dict(records)
631 if isinstance(dataId, DataCoordinate) and dataId.hasRecords():
632 records.update(dataId.records.byName())
633 keys = standardized.byName()
634 for element in standardized.graph.primaryKeyTraversalOrder:
635 record = records.get(element.name, ...) # Use ... to mean not found; None might mean NULL
636 if record is ...:
637 if isinstance(element, Dimension) and keys.get(element.name) is None:
638 if element in standardized.graph.required:
639 raise LookupError(
640 f"No value or null value for required dimension {element.name}."
641 )
642 keys[element.name] = None
643 record = None
644 else:
645 storage = self._managers.dimensions[element]
646 dataIdSet = DataCoordinateIterable.fromScalar(
647 DataCoordinate.standardize(keys, graph=element.graph)
648 )
649 fetched = tuple(storage.fetch(dataIdSet))
650 try:
651 (record,) = fetched
652 except ValueError:
653 record = None
654 records[element.name] = record
655 if record is not None:
656 for d in element.implied:
657 value = getattr(record, d.name)
658 if keys.setdefault(d.name, value) != value:
659 raise InconsistentDataIdError(
660 f"Data ID {standardized} has {d.name}={keys[d.name]!r}, "
661 f"but {element.name} implies {d.name}={value!r}."
662 )
663 else:
664 if element in standardized.graph.required:
665 raise LookupError(
666 f"Could not fetch record for required dimension {element.name} via keys {keys}."
667 )
668 if element.alwaysJoin:
669 raise InconsistentDataIdError(
670 f"Could not fetch record for element {element.name} via keys {keys}, ",
671 "but it is marked alwaysJoin=True; this means one or more dimensions are not "
672 "related."
673 )
674 for d in element.implied:
675 keys.setdefault(d.name, None)
676 records.setdefault(d.name, None)
677 return DataCoordinate.standardize(keys, graph=standardized.graph).expanded(records=records)
679 def insertDimensionData(self, element: Union[DimensionElement, str],
680 *data: Union[Mapping[str, Any], DimensionRecord],
681 conform: bool = True) -> None:
682 # Docstring inherited from lsst.daf.butler.registry.Registry
683 if conform:
684 if isinstance(element, str):
685 element = self.dimensions[element]
686 records = [row if isinstance(row, DimensionRecord) else element.RecordClass(**row)
687 for row in data]
688 else:
689 # Ignore typing since caller said to trust them with conform=False.
690 records = data # type: ignore
691 storage = self._managers.dimensions[element] # type: ignore
692 storage.insert(*records)
694 def syncDimensionData(self, element: Union[DimensionElement, str],
695 row: Union[Mapping[str, Any], DimensionRecord],
696 conform: bool = True) -> bool:
697 # Docstring inherited from lsst.daf.butler.registry.Registry
698 if conform:
699 if isinstance(element, str):
700 element = self.dimensions[element]
701 record = row if isinstance(row, DimensionRecord) else element.RecordClass(**row)
702 else:
703 # Ignore typing since caller said to trust them with conform=False.
704 record = row # type: ignore
705 storage = self._managers.dimensions[element] # type: ignore
706 return storage.sync(record)
708 def queryDatasetTypes(self, expression: Any = ..., *, components: Optional[bool] = None
709 ) -> Iterator[DatasetType]:
710 # Docstring inherited from lsst.daf.butler.registry.Registry
711 wildcard = CategorizedWildcard.fromExpression(expression, coerceUnrecognized=lambda d: d.name)
712 if wildcard is Ellipsis:
713 for datasetType in self._managers.datasets:
714 # The dataset type can no longer be a component
715 yield datasetType
716 if components:
717 # Automatically create the component dataset types
718 try:
719 componentsForDatasetType = datasetType.makeAllComponentDatasetTypes()
720 except KeyError as err:
721 _LOG.warning(f"Could not load storage class {err} for {datasetType.name}; "
722 "if it has components they will not be included in query results.")
723 else:
724 yield from componentsForDatasetType
725 return
726 done: Set[str] = set()
727 for name in wildcard.strings:
728 storage = self._managers.datasets.find(name)
729 if storage is not None:
730 done.add(storage.datasetType.name)
731 yield storage.datasetType
732 if wildcard.patterns:
733 # If components (the argument) is None, we'll save component
734 # dataset that we might want to match, but only if their parents
735 # didn't get included.
736 componentsForLater = []
737 for registeredDatasetType in self._managers.datasets:
738 # Components are not stored in registry so expand them here
739 allDatasetTypes = [registeredDatasetType]
740 try:
741 allDatasetTypes.extend(registeredDatasetType.makeAllComponentDatasetTypes())
742 except KeyError as err:
743 _LOG.warning(f"Could not load storage class {err} for {registeredDatasetType.name}; "
744 "if it has components they will not be included in query results.")
745 for datasetType in allDatasetTypes:
746 if datasetType.name in done:
747 continue
748 parentName, componentName = datasetType.nameAndComponent()
749 if componentName is not None and not components:
750 if components is None and parentName not in done:
751 componentsForLater.append(datasetType)
752 continue
753 if any(p.fullmatch(datasetType.name) for p in wildcard.patterns):
754 done.add(datasetType.name)
755 yield datasetType
756 # Go back and try to match saved components.
757 for datasetType in componentsForLater:
758 parentName, _ = datasetType.nameAndComponent()
759 if parentName not in done and any(p.fullmatch(datasetType.name) for p in wildcard.patterns):
760 yield datasetType
762 def queryCollections(self, expression: Any = ...,
763 datasetType: Optional[DatasetType] = None,
764 collectionTypes: Iterable[CollectionType] = CollectionType.all(),
765 flattenChains: bool = False,
766 includeChains: Optional[bool] = None) -> Iterator[str]:
767 # Docstring inherited from lsst.daf.butler.registry.Registry
769 # Right now the datasetTypes argument is completely ignored, but that
770 # is consistent with its [lack of] guarantees. DM-24939 or a follow-up
771 # ticket will take care of that.
772 query = CollectionQuery.fromExpression(expression)
773 for record in query.iter(self._managers.collections, collectionTypes=frozenset(collectionTypes),
774 flattenChains=flattenChains, includeChains=includeChains):
775 yield record.name
777 def _makeQueryBuilder(self, summary: queries.QuerySummary) -> queries.QueryBuilder:
778 """Return a `QueryBuilder` instance capable of constructing and
779 managing more complex queries than those obtainable via `Registry`
780 interfaces.
782 This is an advanced interface; downstream code should prefer
783 `Registry.queryDataIds` and `Registry.queryDatasets` whenever those
784 are sufficient.
786 Parameters
787 ----------
788 summary : `queries.QuerySummary`
789 Object describing and categorizing the full set of dimensions that
790 will be included in the query.
792 Returns
793 -------
794 builder : `queries.QueryBuilder`
795 Object that can be used to construct and perform advanced queries.
796 """
797 return queries.QueryBuilder(
798 summary,
799 queries.RegistryManagers(
800 collections=self._managers.collections,
801 dimensions=self._managers.dimensions,
802 datasets=self._managers.datasets,
803 TimespanReprClass=self._db.getTimespanRepresentation(),
804 ),
805 )
807 def queryDatasets(self, datasetType: Any, *,
808 collections: Any = None,
809 dimensions: Optional[Iterable[Union[Dimension, str]]] = None,
810 dataId: Optional[DataId] = None,
811 where: Optional[str] = None,
812 findFirst: bool = False,
813 components: Optional[bool] = None,
814 bind: Optional[Mapping[str, Any]] = None,
815 check: bool = True,
816 **kwargs: Any) -> queries.DatasetQueryResults:
817 # Docstring inherited from lsst.daf.butler.registry.Registry
819 # Standardize the collections expression.
820 if collections is None:
821 if not self.defaults.collections:
822 raise TypeError("No collections provided to findDataset, "
823 "and no defaults from registry construction.")
824 collections = self.defaults.collections
825 elif findFirst:
826 collections = CollectionSearch.fromExpression(collections)
827 else:
828 collections = CollectionQuery.fromExpression(collections)
829 # Standardize and expand the data ID provided as a constraint.
830 standardizedDataId = self.expandDataId(dataId, **kwargs)
832 # We can only query directly if given a non-component DatasetType
833 # instance. If we were given an expression or str or a component
834 # DatasetType instance, we'll populate this dict, recurse, and return.
835 # If we already have a non-component DatasetType, it will remain None
836 # and we'll run the query directly.
837 composition: Optional[
838 Dict[
839 DatasetType, # parent dataset type
840 List[Optional[str]] # component name, or None for parent
841 ]
842 ] = None
843 if not isinstance(datasetType, DatasetType):
844 # We were given a dataset type expression (which may be as simple
845 # as a str). Loop over all matching datasets, delegating handling
846 # of the `components` argument to queryDatasetTypes, as we populate
847 # the composition dict.
848 composition = defaultdict(list)
849 for trueDatasetType in self.queryDatasetTypes(datasetType, components=components):
850 parentName, componentName = trueDatasetType.nameAndComponent()
851 if componentName is not None:
852 parentDatasetType = self.getDatasetType(parentName)
853 composition.setdefault(parentDatasetType, []).append(componentName)
854 else:
855 composition.setdefault(trueDatasetType, []).append(None)
856 elif datasetType.isComponent():
857 # We were given a true DatasetType instance, but it's a component.
858 # the composition dict will have exactly one item.
859 parentName, componentName = datasetType.nameAndComponent()
860 parentDatasetType = self.getDatasetType(parentName)
861 composition = {parentDatasetType: [componentName]}
862 if composition is not None:
863 # We need to recurse. Do that once for each parent dataset type.
864 chain = []
865 for parentDatasetType, componentNames in composition.items():
866 parentResults = self.queryDatasets(
867 parentDatasetType,
868 collections=collections,
869 dimensions=dimensions,
870 dataId=standardizedDataId,
871 where=where,
872 findFirst=findFirst,
873 check=check,
874 )
875 if isinstance(parentResults, queries.ParentDatasetQueryResults):
876 chain.append(
877 parentResults.withComponents(componentNames)
878 )
879 else:
880 # Should only happen if we know there would be no results.
881 assert isinstance(parentResults, queries.ChainedDatasetQueryResults) \
882 and not parentResults._chain
883 return queries.ChainedDatasetQueryResults(chain)
884 # If we get here, there's no need to recurse (or we are already
885 # recursing; there can only ever be one level of recursion).
887 # The full set of dimensions in the query is the combination of those
888 # needed for the DatasetType and those explicitly requested, if any.
889 requestedDimensionNames = set(datasetType.dimensions.names)
890 if dimensions is not None:
891 requestedDimensionNames.update(self.dimensions.extract(dimensions).names)
892 # Construct the summary structure needed to construct a QueryBuilder.
893 summary = queries.QuerySummary(
894 requested=DimensionGraph(self.dimensions, names=requestedDimensionNames),
895 dataId=standardizedDataId,
896 expression=where,
897 bind=bind,
898 defaults=self.defaults.dataId,
899 check=check,
900 )
901 builder = self._makeQueryBuilder(summary)
902 # Add the dataset subquery to the query, telling the QueryBuilder to
903 # include the rank of the selected collection in the results only if we
904 # need to findFirst. Note that if any of the collections are
905 # actually wildcard expressions, and we've asked for deduplication,
906 # this will raise TypeError for us.
907 if not builder.joinDataset(datasetType, collections, isResult=True, findFirst=findFirst):
908 return queries.ChainedDatasetQueryResults(())
909 query = builder.finish()
910 return queries.ParentDatasetQueryResults(self._db, query, components=[None])
912 def queryDataIds(self, dimensions: Union[Iterable[Union[Dimension, str]], Dimension, str], *,
913 dataId: Optional[DataId] = None,
914 datasets: Any = None,
915 collections: Any = None,
916 where: Optional[str] = None,
917 components: Optional[bool] = None,
918 bind: Optional[Mapping[str, Any]] = None,
919 check: bool = True,
920 **kwargs: Any) -> queries.DataCoordinateQueryResults:
921 # Docstring inherited from lsst.daf.butler.registry.Registry
922 dimensions = iterable(dimensions)
923 standardizedDataId = self.expandDataId(dataId, **kwargs)
924 standardizedDatasetTypes = set()
925 requestedDimensions = self.dimensions.extract(dimensions)
926 queryDimensionNames = set(requestedDimensions.names)
927 if datasets is not None:
928 if collections is None:
929 if not self.defaults.collections:
930 raise TypeError("Cannot pass 'datasets' without 'collections'.")
931 collections = self.defaults.collections
932 else:
933 # Preprocess collections expression in case the original
934 # included single-pass iterators (we'll want to use it multiple
935 # times below).
936 collections = CollectionQuery.fromExpression(collections)
937 for datasetType in self.queryDatasetTypes(datasets, components=components):
938 queryDimensionNames.update(datasetType.dimensions.names)
939 # If any matched dataset type is a component, just operate on
940 # its parent instead, because Registry doesn't know anything
941 # about what components exist, and here (unlike queryDatasets)
942 # we don't care about returning them.
943 parentDatasetTypeName, componentName = datasetType.nameAndComponent()
944 if componentName is not None:
945 datasetType = self.getDatasetType(parentDatasetTypeName)
946 standardizedDatasetTypes.add(datasetType)
948 summary = queries.QuerySummary(
949 requested=DimensionGraph(self.dimensions, names=queryDimensionNames),
950 dataId=standardizedDataId,
951 expression=where,
952 bind=bind,
953 defaults=self.defaults.dataId,
954 check=check,
955 )
956 builder = self._makeQueryBuilder(summary)
957 for datasetType in standardizedDatasetTypes:
958 builder.joinDataset(datasetType, collections, isResult=False)
959 query = builder.finish()
960 return queries.DataCoordinateQueryResults(self._db, query)
962 def queryDimensionRecords(self, element: Union[DimensionElement, str], *,
963 dataId: Optional[DataId] = None,
964 datasets: Any = None,
965 collections: Any = None,
966 where: Optional[str] = None,
967 components: Optional[bool] = None,
968 bind: Optional[Mapping[str, Any]] = None,
969 check: bool = True,
970 **kwargs: Any) -> Iterator[DimensionRecord]:
971 # Docstring inherited from lsst.daf.butler.registry.Registry
972 if not isinstance(element, DimensionElement):
973 try:
974 element = self.dimensions[element]
975 except KeyError as e:
976 raise KeyError(f"No such dimension '{element}', available dimensions: "
977 + str(self.dimensions.getStaticElements())) from e
978 dataIds = self.queryDataIds(element.graph, dataId=dataId, datasets=datasets, collections=collections,
979 where=where, components=components, bind=bind, check=check, **kwargs)
980 return iter(self._managers.dimensions[element].fetch(dataIds))
982 def queryDatasetAssociations(
983 self,
984 datasetType: Union[str, DatasetType],
985 collections: Any = ...,
986 *,
987 collectionTypes: Iterable[CollectionType] = CollectionType.all(),
988 flattenChains: bool = False,
989 ) -> Iterator[DatasetAssociation]:
990 # Docstring inherited from lsst.daf.butler.registry.Registry
991 if collections is None:
992 if not self.defaults.collections:
993 raise TypeError("No collections provided to findDataset, "
994 "and no defaults from registry construction.")
995 collections = self.defaults.collections
996 else:
997 collections = CollectionQuery.fromExpression(collections)
998 TimespanReprClass = self._db.getTimespanRepresentation()
999 if isinstance(datasetType, str):
1000 storage = self._managers.datasets[datasetType]
1001 else:
1002 storage = self._managers.datasets[datasetType.name]
1003 for collectionRecord in collections.iter(self._managers.collections,
1004 collectionTypes=frozenset(collectionTypes),
1005 flattenChains=flattenChains):
1006 query = storage.select(collectionRecord)
1007 if query is None:
1008 continue
1009 for row in self._db.query(query.combine()):
1010 dataId = DataCoordinate.fromRequiredValues(
1011 storage.datasetType.dimensions,
1012 tuple(row[name] for name in storage.datasetType.dimensions.required.names)
1013 )
1014 runRecord = self._managers.collections[row[self._managers.collections.getRunForeignKeyName()]]
1015 ref = DatasetRef(storage.datasetType, dataId, id=row["id"], run=runRecord.name,
1016 conform=False)
1017 if collectionRecord.type is CollectionType.CALIBRATION:
1018 timespan = TimespanReprClass.extract(row)
1019 else:
1020 timespan = None
1021 yield DatasetAssociation(ref=ref, collection=collectionRecord.name, timespan=timespan)
1023 storageClasses: StorageClassFactory
1024 """All storage classes known to the registry (`StorageClassFactory`).
1025 """