Coverage for python/lsst/daf/butler/registry/bridge/ephemeral.py: 81%
53 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-06 09:46 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-06 09:46 +0000
1# This file is part of daf_butler.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This software is dual licensed under the GNU General Public License and also
10# under a 3-clause BSD license. Recipients may choose which of these licenses
11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt,
12# respectively. If you choose the GPL option then the following text applies
13# (but note that there is still no warranty even if you opt for BSD instead):
14#
15# This program is free software: you can redistribute it and/or modify
16# it under the terms of the GNU General Public License as published by
17# the Free Software Foundation, either version 3 of the License, or
18# (at your option) any later version.
19#
20# This program is distributed in the hope that it will be useful,
21# but WITHOUT ANY WARRANTY; without even the implied warranty of
22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23# GNU General Public License for more details.
24#
25# You should have received a copy of the GNU General Public License
26# along with this program. If not, see <http://www.gnu.org/licenses/>.
27from __future__ import annotations
29__all__ = ("EphemeralDatastoreRegistryBridge",)
31from collections.abc import Collection, Iterable, Iterator
32from contextlib import contextmanager
33from typing import TYPE_CHECKING
35from ..._dataset_ref import DatasetId
36from .._exceptions import ConflictingDefinitionError
37from ..interfaces import DatasetIdRef, DatastoreRegistryBridge, FakeDatasetRef, OpaqueTableStorage
39if TYPE_CHECKING:
40 from ...datastore import DatastoreTransaction
41 from ...datastore.stored_file_info import StoredDatastoreItemInfo
44class EphemeralDatastoreRegistryBridge(DatastoreRegistryBridge):
45 """An implementation of `DatastoreRegistryBridge` for ephemeral datastores
46 - those whose artifacts never outlive the current process.
48 Parameters
49 ----------
50 datastoreName : `str`
51 Name of the `Datastore` as it should appear in `Registry` tables
52 referencing it.
54 Notes
55 -----
56 The current implementation just uses a Python set to remember the dataset
57 IDs associated with the datastore. This will probably need to be converted
58 to use in-database temporary tables instead in the future to support
59 "in-datastore" constraints in `Registry.queryDatasets`.
60 """
62 def __init__(self, datastoreName: str):
63 super().__init__(datastoreName)
64 self._datasetIds: set[DatasetId] = set()
65 self._trashedIds: set[DatasetId] = set()
67 def insert(self, refs: Iterable[DatasetIdRef]) -> None:
68 # Docstring inherited from DatastoreRegistryBridge
69 new_ids = {ref.id for ref in refs}
70 if known_ids := new_ids & self._datasetIds: 70 ↛ 71line 70 didn't jump to line 71 because the condition on line 70 was never true
71 raise ConflictingDefinitionError(f"Some datasets are already in registry: {known_ids}")
72 self._datasetIds.update(new_ids)
74 def ensure(self, refs: Iterable[DatasetIdRef]) -> None:
75 # Docstring inherited from DatastoreRegistryBridge
76 self._datasetIds.update(ref.id for ref in refs)
78 def forget(self, refs: Iterable[DatasetIdRef]) -> None:
79 self._datasetIds.difference_update(ref.id for ref in refs)
81 def _rollbackMoveToTrash(self, refs: Iterable[DatasetIdRef]) -> None:
82 """Rollback a moveToTrash call."""
83 for ref in refs:
84 self._trashedIds.remove(ref.id)
86 def moveToTrash(self, refs: Iterable[DatasetIdRef], transaction: DatastoreTransaction | None) -> None:
87 # Docstring inherited from DatastoreRegistryBridge
88 if transaction is None: 88 ↛ 89line 88 didn't jump to line 89 because the condition on line 88 was never true
89 raise RuntimeError("Must be called with a defined transaction.")
90 ref_list = list(refs)
91 with transaction.undoWith(f"Trash {len(ref_list)} datasets", self._rollbackMoveToTrash, ref_list):
92 self._trashedIds.update(ref.id for ref in ref_list)
94 def check(self, datasets: Iterable[DatasetId]) -> set[DatasetId]:
95 # Docstring inherited from DatastoreRegistryBridge
96 return {id for id in datasets if FakeDatasetRef(id) in self}
98 def __contains__(self, ref: DatasetIdRef) -> bool:
99 return ref.id in self._datasetIds and ref.id not in self._trashedIds
101 @contextmanager
102 def emptyTrash(
103 self,
104 records_table: OpaqueTableStorage | None = None,
105 record_class: type[StoredDatastoreItemInfo] | None = None,
106 record_column: str | None = None,
107 selected_ids: Collection[DatasetId] | None = None,
108 dry_run: bool = False,
109 ) -> Iterator[tuple[Iterable[tuple[DatasetIdRef, StoredDatastoreItemInfo | None]], set[str] | None]]:
110 # Docstring inherited from DatastoreRegistryBridge
111 matches: Iterable[tuple[FakeDatasetRef, StoredDatastoreItemInfo | None]] = ()
112 trashed_ids = self._trashedIds
114 if selected_ids is not None:
115 trashed_ids = {tid for tid in trashed_ids if tid in selected_ids}
117 if isinstance(records_table, OpaqueTableStorage): 117 ↛ 126line 117 didn't jump to line 126 because the condition on line 117 was always true
118 if record_class is None: 118 ↛ 119line 118 didn't jump to line 119 because the condition on line 118 was never true
119 raise ValueError("Record class must be provided if records table is given.")
120 matches = (
121 (FakeDatasetRef(id), record_class.from_record(record))
122 for id in trashed_ids
123 for record in records_table.fetch(dataset_id=id)
124 )
125 else:
126 matches = ((FakeDatasetRef(id), None) for id in trashed_ids)
128 # Indicate to caller that we do not know about artifacts that
129 # should be retained.
130 yield ((matches, None))
132 if dry_run:
133 return
135 if isinstance(records_table, OpaqueTableStorage): 135 ↛ 140line 135 didn't jump to line 140 because the condition on line 135 was always true
136 # Remove the records entries
137 records_table.delete(["dataset_id"], *[{"dataset_id": id} for id in trashed_ids])
139 # Empty the trash table
140 self._datasetIds.difference_update(trashed_ids)
141 self._trashedIds = self._trashedIds - trashed_ids