Coverage for python/lsst/daf/butler/registry/interfaces/_datasets.py: 77%
78 statements
« prev ^ index » next coverage.py v7.11.0, created at 2025-11-13 01:31 -0800
« prev ^ index » next coverage.py v7.11.0, created at 2025-11-13 01:31 -0800
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/>.
28from __future__ import annotations
30from ... import ddl
32__all__ = ("DatasetRecordStorageManager",)
34from abc import abstractmethod
35from collections.abc import Iterable, Mapping, Sequence, Set
36from typing import TYPE_CHECKING, Any
38from ..._dataset_ref import DatasetId, DatasetIdGenEnum, DatasetRef
39from ..._dataset_type import DatasetType
40from ..._exceptions import DatasetTypeError, DatasetTypeNotSupportedError
41from ..._timespan import Timespan
42from ...dimensions import DataCoordinate
43from ...queries import QueryFactoryFunction
44from ...queries.tree import AnyDatasetFieldName
45from ._versioning import VersionedExtension, VersionTuple
47if TYPE_CHECKING:
48 from ...direct_query_driver import SqlJoinsBuilder # new query system, server+direct only
49 from .._caching_context import CachingContext
50 from .._collection_summary import CollectionSummary
51 from ._collections import CollectionManager, CollectionRecord, RunRecord
52 from ._database import Database, StaticTablesContext
53 from ._dimensions import DimensionRecordStorageManager
56class DatasetRecordStorageManager(VersionedExtension):
57 """An interface that manages the tables that describe datasets.
59 `DatasetRecordStorageManager` primarily serves as a container and factory
60 for `DatasetRecordStorage` instances, which each provide access to the
61 records for a different `DatasetType`.
63 Parameters
64 ----------
65 registry_schema_version : `VersionTuple` or `None`, optional
66 Version of registry schema.
67 """
69 def __init__(self, *, registry_schema_version: VersionTuple | None = None) -> None:
70 super().__init__(registry_schema_version=registry_schema_version)
72 @abstractmethod
73 def clone(
74 self,
75 *,
76 db: Database,
77 collections: CollectionManager,
78 dimensions: DimensionRecordStorageManager,
79 caching_context: CachingContext,
80 ) -> DatasetRecordStorageManager:
81 """Make an independent copy of this manager instance bound to new
82 instances of `Database` and other managers.
84 Parameters
85 ----------
86 db : `Database`
87 New `Database` object to use when instantiating the manager.
88 collections : `CollectionManager`
89 New `CollectionManager` object to use when instantiating the
90 manager.
91 dimensions : `DimensionRecordStorageManager`
92 New `DimensionRecordStorageManager` object to use when
93 instantiating the manager.
94 caching_context : `CachingContext`
95 New `CachingContext` object to use when instantiating the manager.
97 Returns
98 -------
99 instance : `DatasetRecordStorageManager`
100 New manager instance with the same configuration as this instance,
101 but bound to a new Database object.
102 """
103 raise NotImplementedError()
105 @abstractmethod
106 def preload_cache(self) -> None:
107 """Fetch data from the database and use it to pre-populate caches to
108 speed up later operations.
109 """
110 raise NotImplementedError()
112 @classmethod
113 @abstractmethod
114 def initialize(
115 cls,
116 db: Database,
117 context: StaticTablesContext,
118 *,
119 collections: CollectionManager,
120 dimensions: DimensionRecordStorageManager,
121 caching_context: CachingContext,
122 registry_schema_version: VersionTuple | None = None,
123 ) -> DatasetRecordStorageManager:
124 """Construct an instance of the manager.
126 Parameters
127 ----------
128 db : `Database`
129 Interface to the underlying database engine and namespace.
130 context : `StaticTablesContext`
131 Context object obtained from `Database.declareStaticTables`; used
132 to declare any tables that should always be present.
133 collections : `CollectionManager`
134 Manager object for the collections in this `Registry`.
135 dimensions : `DimensionRecordStorageManager`
136 Manager object for the dimensions in this `Registry`.
137 caching_context : `CachingContext`
138 Object controlling caching of information returned by managers.
139 registry_schema_version : `VersionTuple` or `None`
140 Schema version of this extension as defined in registry.
142 Returns
143 -------
144 manager : `DatasetRecordStorageManager`
145 An instance of a concrete `DatasetRecordStorageManager` subclass.
146 """
147 raise NotImplementedError()
149 @classmethod
150 @abstractmethod
151 def addDatasetForeignKey(
152 cls,
153 tableSpec: ddl.TableSpec,
154 *,
155 name: str = "dataset",
156 constraint: bool = True,
157 onDelete: str | None = None,
158 **kwargs: Any,
159 ) -> ddl.FieldSpec:
160 """Add a foreign key (field and constraint) referencing the dataset
161 table.
163 Parameters
164 ----------
165 tableSpec : `ddl.TableSpec`
166 Specification for the table that should reference the dataset
167 table. Will be modified in place.
168 name : `str`, optional
169 A name to use for the prefix of the new field; the full name is
170 ``{name}_id``.
171 constraint : `bool`, optional
172 If `False` (`True` is default), add a field that can be joined to
173 the dataset primary key, but do not add a foreign key constraint.
174 onDelete : `str`, optional
175 One of "CASCADE" or "SET NULL", indicating what should happen to
176 the referencing row if the collection row is deleted. `None`
177 indicates that this should be an integrity error.
178 **kwargs
179 Additional keyword arguments are forwarded to the `ddl.FieldSpec`
180 constructor (only the ``name`` and ``dtype`` arguments are
181 otherwise provided).
183 Returns
184 -------
185 idSpec : `ddl.FieldSpec`
186 Specification for the ID field.
187 """
188 raise NotImplementedError()
190 @abstractmethod
191 def refresh(self) -> None:
192 """Ensure all other operations on this manager are aware of any
193 dataset types that may have been registered by other clients since
194 it was initialized or last refreshed.
195 """
196 raise NotImplementedError()
198 @abstractmethod
199 def get_dataset_type(self, name: str) -> DatasetType:
200 """Look up a dataset type by name.
202 Parameters
203 ----------
204 name : `str`
205 Name of a parent dataset type.
207 Returns
208 -------
209 dataset_type : `DatasetType`
210 The object representing the records for the given dataset type.
212 Raises
213 ------
214 MissingDatasetTypeError
215 Raised if there is no dataset type with the given name.
216 """
217 raise NotImplementedError()
219 def conform_exact_dataset_type(self, dataset_type: DatasetType | str) -> DatasetType:
220 """Conform a value that may be a dataset type or dataset type name to
221 just the dataset type name, while checking that the dataset type is not
222 a component and (if a `DatasetType` instance is given) has the exact
223 same definition in the registry.
225 Parameters
226 ----------
227 dataset_type : `str` or `DatasetType`
228 Dataset type object or name.
230 Returns
231 -------
232 dataset_type : `DatasetType`
233 The corresponding registered dataset type.
235 Raises
236 ------
237 DatasetTypeError
238 Raised if ``dataset_type`` is a component, or if its definition
239 does not exactly match the registered dataset type.
240 MissingDatasetTypeError
241 Raised if this dataset type is not registered at all.
242 """
243 if isinstance(dataset_type, DatasetType):
244 dataset_type_name = dataset_type.name
245 given_dataset_type = dataset_type
246 else:
247 dataset_type_name = dataset_type
248 given_dataset_type = None
249 parent_name, component = DatasetType.splitDatasetTypeName(dataset_type_name)
250 if component is not None:
251 raise DatasetTypeNotSupportedError(
252 f"Component dataset {dataset_type_name!r} is not supported in this context."
253 )
254 registered_dataset_type = self.get_dataset_type(dataset_type_name)
255 if given_dataset_type is not None and registered_dataset_type != given_dataset_type:
256 raise DatasetTypeError(
257 f"Given dataset type {given_dataset_type} is not identical to the "
258 f"registered one {registered_dataset_type}."
259 )
260 return registered_dataset_type
262 @abstractmethod
263 def register_dataset_type(self, dataset_type: DatasetType) -> bool:
264 """Ensure that this `Registry` can hold records for the given
265 `DatasetType`, creating new tables as necessary.
267 Parameters
268 ----------
269 dataset_type : `DatasetType`
270 Dataset type for which a table should created (as necessary) and
271 an associated `DatasetRecordStorage` returned.
273 Returns
274 -------
275 inserted : `bool`
276 `True` if the dataset type did not exist in the registry before.
278 Notes
279 -----
280 This operation may not be invoked within a `Database.transaction`
281 context.
282 """
283 raise NotImplementedError()
285 @abstractmethod
286 def remove_dataset_type(self, name: str) -> None:
287 """Remove the dataset type.
289 Parameters
290 ----------
291 name : `str`
292 Name of the dataset type.
293 """
294 raise NotImplementedError()
296 @abstractmethod
297 def resolve_wildcard(
298 self,
299 expression: Any,
300 missing: list[str] | None = None,
301 explicit_only: bool = False,
302 ) -> list[DatasetType]:
303 """Resolve a dataset type wildcard expression.
305 Parameters
306 ----------
307 expression : `~typing.Any`
308 Expression to resolve. Will be passed to
309 `DatasetTypeWildcard.from_expression`.
310 missing : `list` of `str`, optional
311 String dataset type names that were explicitly given (i.e. not
312 regular expression patterns) but not found will be appended to this
313 list, if it is provided.
314 explicit_only : `bool`, optional
315 If `True`, require explicit `DatasetType` instances or `str` names,
316 with `re.Pattern` instances deprecated and ``...`` prohibited.
318 Returns
319 -------
320 dataset_types : `list` [ `DatasetType` ]
321 A list of resolved dataset types.
322 """
323 raise NotImplementedError()
325 @abstractmethod
326 def getDatasetRef(self, id: DatasetId) -> DatasetRef | None:
327 """Return a `DatasetRef` for the given dataset primary key
328 value.
330 Parameters
331 ----------
332 id : `DatasetId`
333 Primary key value for the dataset.
335 Returns
336 -------
337 ref : `DatasetRef` or `None`
338 Object representing the dataset, or `None` if no dataset with the
339 given primary key values exists in this layer.
340 """
341 raise NotImplementedError()
343 @abstractmethod
344 def getCollectionSummary(self, collection: CollectionRecord) -> CollectionSummary:
345 """Return a summary for the given collection.
347 Parameters
348 ----------
349 collection : `CollectionRecord`
350 Record describing the collection for which a summary is to be
351 retrieved.
353 Returns
354 -------
355 summary : `CollectionSummary`
356 Summary of the dataset types and governor dimension values in
357 this collection.
358 """
359 raise NotImplementedError()
361 @abstractmethod
362 def fetch_summaries(
363 self,
364 collections: Iterable[CollectionRecord],
365 dataset_types: Iterable[DatasetType] | Iterable[str] | None = None,
366 ) -> Mapping[Any, CollectionSummary]:
367 """Fetch collection summaries given their names and dataset types.
369 Parameters
370 ----------
371 collections : `~collections.abc.Iterable` [`CollectionRecord`]
372 Collection records to query.
373 dataset_types : `~collections.abc.Iterable` [`DatasetType`] or `None`
374 Dataset types to include into returned summaries. If `None` then
375 all dataset types will be included.
377 Returns
378 -------
379 summaries : `~collections.abc.Mapping` [`Any`, `CollectionSummary`]
380 Collection summaries indexed by collection record key. This mapping
381 will also contain all nested non-chained collections of the chained
382 collections.
383 """
384 raise NotImplementedError()
386 @abstractmethod
387 def fetch_run_dataset_ids(self, run: RunRecord) -> list[DatasetId]:
388 """Return the IDs of all datasets in the given ``RUN``
389 collection.
391 Parameters
392 ----------
393 run : `RunRecord`
394 Record describing the collection.
396 Returns
397 -------
398 dataset_ids : `list` [`uuid.UUID`]
399 List of dataset IDs.
400 """
401 raise NotImplementedError()
403 @abstractmethod
404 def ingest_date_dtype(self) -> type:
405 """Return type of the ``ingest_date`` column."""
406 raise NotImplementedError()
408 @abstractmethod
409 def insert(
410 self,
411 dataset_type_name: str,
412 run: RunRecord,
413 data_ids: Iterable[DataCoordinate],
414 id_generation_mode: DatasetIdGenEnum = DatasetIdGenEnum.UNIQUE,
415 ) -> list[DatasetRef]:
416 """Insert one or more dataset entries into the database.
418 Parameters
419 ----------
420 dataset_type_name : `str`
421 Name of the dataset type.
422 run : `RunRecord`
423 The record object describing the `~CollectionType.RUN` collection
424 these datasets will be associated with.
425 data_ids : `~collections.abc.Iterable` [ `DataCoordinate` ]
426 Expanded data IDs (`DataCoordinate` instances) for the
427 datasets to be added. The dimensions of all data IDs must be the
428 same as ``dataset_type.dimensions``.
429 id_generation_mode : `DatasetIdGenEnum`
430 With `UNIQUE` each new dataset is inserted with its new unique ID.
431 With non-`UNIQUE` mode ID is computed from some combination of
432 dataset type, dataId, and run collection name; if the same ID is
433 already in the database then new record is not inserted.
435 Returns
436 -------
437 datasets : `list` [ `DatasetRef` ]
438 References to the inserted datasets.
439 """
440 raise NotImplementedError()
442 @abstractmethod
443 def import_(self, run: RunRecord, refs: list[DatasetRef], assume_new: bool = False) -> None:
444 """Insert one or more dataset entries into the database.
446 Parameters
447 ----------
448 run : `RunRecord`
449 The record object describing the `~CollectionType.RUN` collection
450 these datasets will be associated with.
451 refs : `list` [ `DatasetRef` ]
452 List of datasets to be be inserted. All of the ``DatasetRef``
453 ``run`` attributes must match the ``run`` parameter.
454 assume_new : `bool`, optional
455 If `True`, assume all datasets are new and skip conflict resolution
456 logic.
457 """
458 raise NotImplementedError()
460 @abstractmethod
461 def delete(self, datasets: Iterable[DatasetId | DatasetRef]) -> None:
462 """Fully delete the given datasets from the registry.
464 Parameters
465 ----------
466 datasets : `~collections.abc.Iterable` [ `DatasetId` or `DatasetRef` ]
467 Datasets to be deleted. If `DatasetRef` instances are passed,
468 only the `DatasetRef.id` attribute is used.
469 """
470 raise NotImplementedError()
472 @abstractmethod
473 def associate(
474 self, dataset_type: DatasetType, collection: CollectionRecord, datasets: Iterable[DatasetRef]
475 ) -> None:
476 """Associate one or more datasets with a collection.
478 Parameters
479 ----------
480 dataset_type : `DatasetType`
481 Type of all datasets.
482 collection : `CollectionRecord`
483 The record object describing the collection. ``collection.type``
484 must be `~CollectionType.TAGGED`.
485 datasets : `~collections.abc.Iterable` [ `DatasetRef` ]
486 Datasets to be associated. All datasets must have the same
487 `DatasetType` as ``dataset_type``, but this is not checked.
489 Notes
490 -----
491 Associating a dataset into collection that already contains a
492 different dataset with the same `DatasetType` and data ID will remove
493 the existing dataset from that collection.
495 Associating the same dataset into a collection multiple times is a
496 no-op, but is still not permitted on read-only databases.
497 """
498 raise NotImplementedError()
500 @abstractmethod
501 def disassociate(
502 self, dataset_type: DatasetType, collection: CollectionRecord, datasets: Iterable[DatasetRef]
503 ) -> None:
504 """Remove one or more datasets from a collection.
506 Parameters
507 ----------
508 dataset_type : `DatasetType`
509 Type of all datasets.
510 collection : `CollectionRecord`
511 The record object describing the collection. ``collection.type``
512 must be `~CollectionType.TAGGED`.
513 datasets : `~collections.abc.Iterable` [ `DatasetRef` ]
514 Datasets to be disassociated. All datasets must have the same
515 `DatasetType` as ``dataset_type``, but this is not checked.
516 """
517 raise NotImplementedError()
519 @abstractmethod
520 def certify(
521 self,
522 dataset_type: DatasetType,
523 collection: CollectionRecord,
524 datasets: Iterable[DatasetRef],
525 timespan: Timespan,
526 query_func: QueryFactoryFunction,
527 ) -> None:
528 """Associate one or more datasets with a calibration collection and a
529 validity range within it.
531 Parameters
532 ----------
533 dataset_type : `DatasetType`
534 Type of all datasets.
535 collection : `CollectionRecord`
536 The record object describing the collection. ``collection.type``
537 must be `~CollectionType.CALIBRATION`.
538 datasets : `~collections.abc.Iterable` [ `DatasetRef` ]
539 Datasets to be associated. All datasets must have the same
540 `DatasetType` as ``dataset_type``, but this is not checked.
541 timespan : `Timespan`
542 The validity range for these datasets within the collection.
543 query_func : `QueryFactoryFunction`
544 Function returning a context manager that sets up a `Query` object
545 for querying the registry. (That is, a function equivalent to
546 ``Butler.query()``).
548 Raises
549 ------
550 ConflictingDefinitionError
551 Raised if the collection already contains a different dataset with
552 the same `DatasetType` and data ID and an overlapping validity
553 range.
554 DatasetTypeError
555 Raised if ``dataset_type.isCalibration() is False``.
556 CollectionTypeError
557 Raised if
558 ``collection.type is not CollectionType.CALIBRATION``.
559 """
560 raise NotImplementedError()
562 @abstractmethod
563 def decertify(
564 self,
565 dataset_type: DatasetType,
566 collection: CollectionRecord,
567 timespan: Timespan,
568 *,
569 data_ids: Iterable[DataCoordinate] | None = None,
570 query_func: QueryFactoryFunction,
571 ) -> None:
572 """Remove or adjust datasets to clear a validity range within a
573 calibration collection.
575 Parameters
576 ----------
577 dataset_type : `DatasetType`
578 Type of all datasets.
579 collection : `CollectionRecord`
580 The record object describing the collection. ``collection.type``
581 must be `~CollectionType.CALIBRATION`.
582 timespan : `Timespan`
583 The validity range to remove datasets from within the collection.
584 Datasets that overlap this range but are not contained by it will
585 have their validity ranges adjusted to not overlap it, which may
586 split a single dataset validity range into two.
587 data_ids : `~collections.abc.Iterable` [ `DataCoordinate` ], optional
588 Data IDs that should be decertified within the given validity range
589 If `None`, all data IDs for ``dataset_type`` in ``collection`` will
590 be decertified.
591 query_func : `QueryFactoryFunction`
592 Function returning a context manager that sets up a `Query` object
593 for querying the registry. (That is, a function equivalent to
594 ``Butler.query()``).
596 Raises
597 ------
598 DatasetTypeError
599 Raised if ``dataset_type.isCalibration() is False``.
600 CollectionTypeError
601 Raised if
602 ``collection.type is not CollectionType.CALIBRATION``.
603 """
604 raise NotImplementedError()
606 @abstractmethod
607 def make_joins_builder(
608 self,
609 dataset_type: DatasetType,
610 collections: Sequence[CollectionRecord],
611 fields: Set[AnyDatasetFieldName],
612 is_union: bool = False,
613 ) -> SqlJoinsBuilder:
614 """Make a `..direct_query_driver.SqlJoinsBuilder` that represents a
615 search for datasets of this type.
617 Parameters
618 ----------
619 dataset_type : `DatasetType`
620 Type of dataset to query for.
621 collections : `~collections.abc.Sequence` [ `CollectionRecord` ]
622 Collections to search, in order, after filtering out collections
623 with no datasets of this type via collection summaries.
624 fields : `~collections.abc.Set` [ `str` ]
625 Names of fields to make available in the builder. Options include:
627 - ``dataset_id`` (UUID)
628 - ``run`` (collection name, `str`)
629 - ``collection`` (collection name, `str`)
630 - ``collection_key`` (collection primary key, manager-dependent)
631 - ``timespan`` (validity range, or unbounded for non-calibrations)
632 - ``ingest_date`` (time dataset was ingested into repository)
634 Dimension keys for the dataset type's required dimensions are
635 always included.
636 is_union : `bool`, optional
637 If `True`, this search is being joined in as part of one term in
638 a union over all dataset types. This causes fields to be added to
639 the builder via the special ``...`` instad of the dataset type
640 name.
642 Returns
643 -------
644 builder : `..direct_query_driver.SqlJoinsBuilder`
645 A query-construction object representing a table or subquery.
646 """
647 raise NotImplementedError()
649 @abstractmethod
650 def refresh_collection_summaries(self, dataset_type: DatasetType) -> None:
651 """Make sure that collection summaries for this dataset type are
652 consistent with the contents of the dataset tables.
654 Parameters
655 ----------
656 dataset_type : `DatasetType`
657 Dataset type whose summary entries should be refreshed.
658 """
659 raise NotImplementedError()