Coverage for python/lsst/daf/butler/registry/bridge/monolithic.py: 28%
103 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-06 10:53 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-06 10:53 +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
29from ... import ddl
31__all__ = ("MonolithicDatastoreRegistryBridgeManager", "MonolithicDatastoreRegistryBridge")
33import copy
34from collections import namedtuple
35from collections.abc import Iterable, Iterator
36from contextlib import contextmanager
37from typing import TYPE_CHECKING, cast
39import sqlalchemy
41from ..._named import NamedValueSet
42from ...datastore.stored_file_info import StoredDatastoreItemInfo
43from ..interfaces import (
44 DatasetIdRef,
45 DatastoreRegistryBridge,
46 DatastoreRegistryBridgeManager,
47 FakeDatasetRef,
48 OpaqueTableStorage,
49 VersionTuple,
50)
51from ..opaque import ByNameOpaqueTableStorage
52from .ephemeral import EphemeralDatastoreRegistryBridge
54if TYPE_CHECKING:
55 from ...datastore import DatastoreTransaction
56 from ...dimensions import DimensionUniverse
57 from ..interfaces import (
58 Database,
59 DatasetRecordStorageManager,
60 OpaqueTableStorageManager,
61 StaticTablesContext,
62 )
64_TablesTuple = namedtuple(
65 "_TablesTuple",
66 [
67 "dataset_location",
68 "dataset_location_trash",
69 ],
70)
72# This has to be updated on every schema change
73_VERSION = VersionTuple(0, 2, 0)
76def _makeTableSpecs(datasets: type[DatasetRecordStorageManager]) -> _TablesTuple:
77 """Construct specifications for tables used by the monolithic datastore
78 bridge classes.
80 Parameters
81 ----------
82 universe : `DimensionUniverse`
83 All dimensions known to the `Registry`.
84 datasets : subclass of `DatasetRecordStorageManager`
85 Manager class for datasets; used only to create foreign key fields.
87 Returns
88 -------
89 specs : `_TablesTuple`
90 A named tuple containing `ddl.TableSpec` instances.
91 """
92 # We want the dataset_location and dataset_location_trash tables
93 # to have the same definition, aside from the behavior of their link
94 # to the dataset table: the trash table has no foreign key constraint.
95 dataset_location_spec = ddl.TableSpec(
96 doc=(
97 "A table that provides information on whether a dataset is stored in "
98 "one or more Datastores. The presence or absence of a record in this "
99 "table itself indicates whether the dataset is present in that "
100 "Datastore. "
101 ),
102 fields=NamedValueSet(
103 [
104 ddl.FieldSpec(
105 name="datastore_name",
106 dtype=sqlalchemy.String,
107 length=256,
108 primaryKey=True,
109 nullable=False,
110 doc="Name of the Datastore this entry corresponds to.",
111 ),
112 ]
113 ),
114 )
115 dataset_location = copy.deepcopy(dataset_location_spec)
116 datasets.addDatasetForeignKey(dataset_location, primaryKey=True)
117 dataset_location_trash = copy.deepcopy(dataset_location_spec)
118 datasets.addDatasetForeignKey(dataset_location_trash, primaryKey=True, constraint=False)
119 return _TablesTuple(
120 dataset_location=dataset_location,
121 dataset_location_trash=dataset_location_trash,
122 )
125class MonolithicDatastoreRegistryBridge(DatastoreRegistryBridge):
126 """An implementation of `DatastoreRegistryBridge` that uses the same two
127 tables for all non-ephemeral datastores.
129 Parameters
130 ----------
131 datastoreName : `str`
132 Name of the `Datastore` as it should appear in `Registry` tables
133 referencing it.
134 db : `Database`
135 Object providing a database connection and generic distractions.
136 tables : `_TablesTuple`
137 Named tuple containing `sqlalchemy.schema.Table` instances.
138 """
140 def __init__(self, datastoreName: str, *, db: Database, tables: _TablesTuple):
141 super().__init__(datastoreName)
142 self._db = db
143 self._tables = tables
145 def _refsToRows(self, refs: Iterable[DatasetIdRef]) -> list[dict]:
146 """Transform an iterable of `DatasetRef` or `FakeDatasetRef` objects to
147 a list of dictionaries that match the schema of the tables used by this
148 class.
150 Parameters
151 ----------
152 refs : `~collections.abc.Iterable` [ `DatasetRef` or `FakeDatasetRef` ]
153 Datasets to transform.
155 Returns
156 -------
157 rows : `list` [ `dict` ]
158 List of dictionaries, with "datastoreName" and "dataset_id" keys.
159 """
160 return [{"datastore_name": self.datastoreName, "dataset_id": ref.id} for ref in refs]
162 def ensure(self, refs: Iterable[DatasetIdRef]) -> None:
163 # Docstring inherited from DatastoreRegistryBridge
164 self._db.ensure(self._tables.dataset_location, *self._refsToRows(refs))
166 def insert(self, refs: Iterable[DatasetIdRef]) -> None:
167 # Docstring inherited from DatastoreRegistryBridge
168 self._db.insert(self._tables.dataset_location, *self._refsToRows(refs))
170 def forget(self, refs: Iterable[DatasetIdRef]) -> None:
171 # Docstring inherited from DatastoreRegistryBridge
172 rows = self._refsToRows(self.check(refs))
173 self._db.delete(self._tables.dataset_location, ["datastore_name", "dataset_id"], *rows)
175 def moveToTrash(self, refs: Iterable[DatasetIdRef], transaction: DatastoreTransaction | None) -> None:
176 # Docstring inherited from DatastoreRegistryBridge
177 # TODO: avoid self.check() call via queries like
178 # INSERT INTO dataset_location_trash
179 # SELECT datastore_name, dataset_id FROM dataset_location
180 # WHERE datastore_name=? AND dataset_id IN (?);
181 # DELETE FROM dataset_location
182 # WHERE datastore_name=? AND dataset_id IN (?);
183 # ...but the Database interface doesn't support those kinds of queries
184 # right now.
185 rows = self._refsToRows(self.check(refs))
186 with self._db.transaction():
187 self._db.delete(self._tables.dataset_location, ["datastore_name", "dataset_id"], *rows)
188 self._db.insert(self._tables.dataset_location_trash, *rows)
190 def check(self, refs: Iterable[DatasetIdRef]) -> Iterable[DatasetIdRef]:
191 # Docstring inherited from DatastoreRegistryBridge
192 byId = {ref.id: ref for ref in refs}
193 sql = (
194 sqlalchemy.sql.select(self._tables.dataset_location.columns.dataset_id)
195 .select_from(self._tables.dataset_location)
196 .where(
197 sqlalchemy.sql.and_(
198 self._tables.dataset_location.columns.datastore_name == self.datastoreName,
199 self._tables.dataset_location.columns.dataset_id.in_(byId.keys()),
200 )
201 )
202 )
203 with self._db.query(sql) as sql_result:
204 sql_rows = sql_result.fetchall()
205 for row in sql_rows:
206 yield byId[row.dataset_id]
208 @contextmanager
209 def emptyTrash(
210 self,
211 records_table: OpaqueTableStorage | None = None,
212 record_class: type[StoredDatastoreItemInfo] | None = None,
213 record_column: str | None = None,
214 ) -> Iterator[tuple[Iterable[tuple[DatasetIdRef, StoredDatastoreItemInfo | None]], set[str] | None]]:
215 # Docstring inherited from DatastoreRegistryBridge
217 if records_table is None:
218 raise ValueError("This implementation requires a records table.")
220 assert isinstance(
221 records_table, ByNameOpaqueTableStorage
222 ), f"Records table must support hidden attributes. Got {type(records_table)}."
224 if record_class is None:
225 raise ValueError("Record class must be provided if records table is given.")
227 # Helper closure to generate the common join+where clause.
228 def join_records(
229 select: sqlalchemy.sql.Select, location_table: sqlalchemy.schema.Table
230 ) -> sqlalchemy.sql.Select:
231 # mypy needs to be sure
232 assert isinstance(records_table, ByNameOpaqueTableStorage)
233 return select.select_from(
234 records_table._table.join(
235 location_table,
236 onclause=records_table._table.columns.dataset_id == location_table.columns.dataset_id,
237 )
238 ).where(location_table.columns.datastore_name == self.datastoreName)
240 # SELECT records.dataset_id, records.path FROM records
241 # JOIN records on dataset_location.dataset_id == records.dataset_id
242 # WHERE dataset_location.datastore_name = datastoreName
244 # It's possible that we may end up with a ref listed in the trash
245 # table that is not listed in the records table. Such an
246 # inconsistency would be missed by this query.
247 info_in_trash = join_records(records_table._table.select(), self._tables.dataset_location_trash)
249 # Run query, transform results into a list of dicts that we can later
250 # use to delete.
251 with self._db.query(info_in_trash) as sql_result:
252 rows = [dict(row, datastore_name=self.datastoreName) for row in sql_result.mappings()]
254 # It is possible for trashed refs to be linked to artifacts that
255 # are still associated with refs that are not to be trashed. We
256 # need to be careful to consider those and indicate to the caller
257 # that those artifacts should be retained. Can only do this check
258 # if the caller provides a column name that can map to multiple
259 # refs.
260 preserved: set[str] | None = None
261 if record_column is not None:
262 # Some helper subqueries
263 items_not_in_trash = join_records(
264 sqlalchemy.sql.select(records_table._table.columns[record_column]),
265 self._tables.dataset_location,
266 ).alias("items_not_in_trash")
267 items_in_trash = join_records(
268 sqlalchemy.sql.select(records_table._table.columns[record_column]),
269 self._tables.dataset_location_trash,
270 ).alias("items_in_trash")
272 # A query for paths that are referenced by datasets in the trash
273 # and datasets not in the trash.
274 items_to_preserve = sqlalchemy.sql.select(items_in_trash.columns[record_column]).select_from(
275 items_not_in_trash.join(
276 items_in_trash,
277 onclause=items_in_trash.columns[record_column]
278 == items_not_in_trash.columns[record_column],
279 )
280 )
281 with self._db.query(items_to_preserve) as sql_result:
282 preserved = {row[record_column] for row in sql_result.mappings()}
284 # Convert results to a tuple of id+info and a record of the artifacts
285 # that should not be deleted from datastore. The id+info tuple is
286 # solely to allow logging to report the relevant ID.
287 id_info = ((FakeDatasetRef(row["dataset_id"]), record_class.from_record(row)) for row in rows)
289 # Start contextmanager, return results
290 yield ((id_info, preserved))
292 # No exception raised in context manager block.
293 if not rows:
294 return
296 # Delete the rows from the records table
297 records_table.delete(["dataset_id"], *[{"dataset_id": row["dataset_id"]} for row in rows])
299 # Delete those rows from the trash table.
300 self._db.delete(
301 self._tables.dataset_location_trash,
302 ["dataset_id", "datastore_name"],
303 *[{"dataset_id": row["dataset_id"], "datastore_name": row["datastore_name"]} for row in rows],
304 )
307class MonolithicDatastoreRegistryBridgeManager(DatastoreRegistryBridgeManager):
308 """An implementation of `DatastoreRegistryBridgeManager` that uses the same
309 two tables for all non-ephemeral datastores.
311 Parameters
312 ----------
313 db : `Database`
314 Object providing a database connection and generic distractions.
315 tables : `_TablesTuple`
316 Named tuple containing `sqlalchemy.schema.Table` instances.
317 opaque : `OpaqueTableStorageManager`
318 Manager object for opaque table storage in the `Registry`.
319 universe : `DimensionUniverse`
320 All dimensions know to the `Registry`.
321 datasetIdColumnType : `type`
322 Type for dataset ID column.
323 """
325 def __init__(
326 self,
327 *,
328 db: Database,
329 tables: _TablesTuple,
330 opaque: OpaqueTableStorageManager,
331 universe: DimensionUniverse,
332 datasetIdColumnType: type,
333 registry_schema_version: VersionTuple | None = None,
334 ):
335 super().__init__(
336 opaque=opaque,
337 universe=universe,
338 datasetIdColumnType=datasetIdColumnType,
339 registry_schema_version=registry_schema_version,
340 )
341 self._db = db
342 self._tables = tables
343 self._ephemeral: dict[str, EphemeralDatastoreRegistryBridge] = {}
345 @classmethod
346 def initialize(
347 cls,
348 db: Database,
349 context: StaticTablesContext,
350 *,
351 opaque: OpaqueTableStorageManager,
352 datasets: type[DatasetRecordStorageManager],
353 universe: DimensionUniverse,
354 registry_schema_version: VersionTuple | None = None,
355 ) -> DatastoreRegistryBridgeManager:
356 # Docstring inherited from DatastoreRegistryBridge
357 tables = context.addTableTuple(_makeTableSpecs(datasets))
358 return cls(
359 db=db,
360 tables=cast(_TablesTuple, tables),
361 opaque=opaque,
362 universe=universe,
363 datasetIdColumnType=datasets.getIdColumnType(),
364 registry_schema_version=registry_schema_version,
365 )
367 def refresh(self) -> None:
368 # Docstring inherited from DatastoreRegistryBridge
369 # This implementation has no in-Python state that depends on which
370 # datastores exist, so there's nothing to do.
371 pass
373 def register(self, name: str, *, ephemeral: bool = False) -> DatastoreRegistryBridge:
374 # Docstring inherited from DatastoreRegistryBridge
375 if ephemeral:
376 return self._ephemeral.setdefault(name, EphemeralDatastoreRegistryBridge(name))
377 return MonolithicDatastoreRegistryBridge(name, db=self._db, tables=self._tables)
379 def findDatastores(self, ref: DatasetIdRef) -> Iterable[str]:
380 # Docstring inherited from DatastoreRegistryBridge
381 sql = (
382 sqlalchemy.sql.select(self._tables.dataset_location.columns.datastore_name)
383 .select_from(self._tables.dataset_location)
384 .where(self._tables.dataset_location.columns.dataset_id == ref.id)
385 )
386 with self._db.query(sql) as sql_result:
387 sql_rows = sql_result.mappings().fetchall()
388 for row in sql_rows:
389 yield row[self._tables.dataset_location.columns.datastore_name]
390 for name, bridge in self._ephemeral.items():
391 if ref in bridge:
392 yield name
394 @classmethod
395 def currentVersions(cls) -> list[VersionTuple]:
396 # Docstring inherited from VersionedExtension.
397 return [_VERSION]