Coverage for python/lsst/daf/butler/registry/bridge/monolithic.py: 24%

103 statements  

« prev     ^ index     » next       coverage.py v7.5.0, created at 2024-04-24 23:50 -0700

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 

22 

23__all__ = ("MonolithicDatastoreRegistryBridgeManager", "MonolithicDatastoreRegistryBridge") 

24 

25import copy 

26from collections import namedtuple 

27from contextlib import contextmanager 

28from typing import TYPE_CHECKING, Dict, Iterable, Iterator, List, Optional, Set, Tuple, Type, cast 

29 

30import sqlalchemy 

31 

32from ...core import NamedValueSet, StoredDatastoreItemInfo, ddl 

33from ..interfaces import ( 

34 DatasetIdRef, 

35 DatastoreRegistryBridge, 

36 DatastoreRegistryBridgeManager, 

37 FakeDatasetRef, 

38 OpaqueTableStorage, 

39 VersionTuple, 

40) 

41from ..opaque import ByNameOpaqueTableStorage 

42from .ephemeral import EphemeralDatastoreRegistryBridge 

43 

44if TYPE_CHECKING: 44 ↛ 45line 44 didn't jump to line 45, because the condition on line 44 was never true

45 from ...core import DimensionUniverse 

46 from ..interfaces import ( 

47 Database, 

48 DatasetRecordStorageManager, 

49 OpaqueTableStorageManager, 

50 StaticTablesContext, 

51 ) 

52 

53_TablesTuple = namedtuple( 

54 "_TablesTuple", 

55 [ 

56 "dataset_location", 

57 "dataset_location_trash", 

58 ], 

59) 

60 

61# This has to be updated on every schema change 

62_VERSION = VersionTuple(0, 2, 0) 

63 

64 

65def _makeTableSpecs(datasets: Type[DatasetRecordStorageManager]) -> _TablesTuple: 

66 """Construct specifications for tables used by the monolithic datastore 

67 bridge classes. 

68 

69 Parameters 

70 ---------- 

71 universe : `DimensionUniverse` 

72 All dimensions known to the `Registry`. 

73 datasets : subclass of `DatasetRecordStorageManager` 

74 Manager class for datasets; used only to create foreign key fields. 

75 

76 Returns 

77 ------- 

78 specs : `_TablesTuple` 

79 A named tuple containing `ddl.TableSpec` instances. 

80 """ 

81 # We want the dataset_location and dataset_location_trash tables 

82 # to have the same definition, aside from the behavior of their link 

83 # to the dataset table: the trash table has no foreign key constraint. 

84 dataset_location_spec = ddl.TableSpec( 

85 doc=( 

86 "A table that provides information on whether a dataset is stored in " 

87 "one or more Datastores. The presence or absence of a record in this " 

88 "table itself indicates whether the dataset is present in that " 

89 "Datastore. " 

90 ), 

91 fields=NamedValueSet( 

92 [ 

93 ddl.FieldSpec( 

94 name="datastore_name", 

95 dtype=sqlalchemy.String, 

96 length=256, 

97 primaryKey=True, 

98 nullable=False, 

99 doc="Name of the Datastore this entry corresponds to.", 

100 ), 

101 ] 

102 ), 

103 ) 

104 dataset_location = copy.deepcopy(dataset_location_spec) 

105 datasets.addDatasetForeignKey(dataset_location, primaryKey=True) 

106 dataset_location_trash = copy.deepcopy(dataset_location_spec) 

107 datasets.addDatasetForeignKey(dataset_location_trash, primaryKey=True, constraint=False) 

108 return _TablesTuple( 

109 dataset_location=dataset_location, 

110 dataset_location_trash=dataset_location_trash, 

111 ) 

112 

113 

114class MonolithicDatastoreRegistryBridge(DatastoreRegistryBridge): 

115 """An implementation of `DatastoreRegistryBridge` that uses the same two 

116 tables for all non-ephemeral datastores. 

117 

118 Parameters 

119 ---------- 

120 datastoreName : `str` 

121 Name of the `Datastore` as it should appear in `Registry` tables 

122 referencing it. 

123 db : `Database` 

124 Object providing a database connection and generic distractions. 

125 tables : `_TablesTuple` 

126 Named tuple containing `sqlalchemy.schema.Table` instances. 

127 """ 

128 

129 def __init__(self, datastoreName: str, *, db: Database, tables: _TablesTuple): 

130 super().__init__(datastoreName) 

131 self._db = db 

132 self._tables = tables 

133 

134 def _refsToRows(self, refs: Iterable[DatasetIdRef]) -> List[dict]: 

135 """Transform an iterable of `DatasetRef` or `FakeDatasetRef` objects to 

136 a list of dictionaries that match the schema of the tables used by this 

137 class. 

138 

139 Parameters 

140 ---------- 

141 refs : `Iterable` [ `DatasetRef` or `FakeDatasetRef` ] 

142 Datasets to transform. 

143 

144 Returns 

145 ------- 

146 rows : `list` [ `dict` ] 

147 List of dictionaries, with "datastoreName" and "dataset_id" keys. 

148 """ 

149 return [{"datastore_name": self.datastoreName, "dataset_id": ref.getCheckedId()} for ref in refs] 

150 

151 def insert(self, refs: Iterable[DatasetIdRef]) -> None: 

152 # Docstring inherited from DatastoreRegistryBridge 

153 self._db.insert(self._tables.dataset_location, *self._refsToRows(refs)) 

154 

155 def forget(self, refs: Iterable[DatasetIdRef]) -> None: 

156 # Docstring inherited from DatastoreRegistryBridge 

157 rows = self._refsToRows(self.check(refs)) 

158 self._db.delete(self._tables.dataset_location, ["datastore_name", "dataset_id"], *rows) 

159 

160 def moveToTrash(self, refs: Iterable[DatasetIdRef]) -> None: 

161 # Docstring inherited from DatastoreRegistryBridge 

162 # TODO: avoid self.check() call via queries like 

163 # INSERT INTO dataset_location_trash 

164 # SELECT datastore_name, dataset_id FROM dataset_location 

165 # WHERE datastore_name=? AND dataset_id IN (?); 

166 # DELETE FROM dataset_location 

167 # WHERE datastore_name=? AND dataset_id IN (?); 

168 # ...but the Database interface doesn't support those kinds of queries 

169 # right now. 

170 rows = self._refsToRows(self.check(refs)) 

171 with self._db.transaction(): 

172 self._db.delete(self._tables.dataset_location, ["datastore_name", "dataset_id"], *rows) 

173 self._db.insert(self._tables.dataset_location_trash, *rows) 

174 

175 def check(self, refs: Iterable[DatasetIdRef]) -> Iterable[DatasetIdRef]: 

176 # Docstring inherited from DatastoreRegistryBridge 

177 byId = {ref.getCheckedId(): ref for ref in refs} 

178 sql = ( 

179 sqlalchemy.sql.select(self._tables.dataset_location.columns.dataset_id) 

180 .select_from(self._tables.dataset_location) 

181 .where( 

182 sqlalchemy.sql.and_( 

183 self._tables.dataset_location.columns.datastore_name == self.datastoreName, 

184 self._tables.dataset_location.columns.dataset_id.in_(byId.keys()), 

185 ) 

186 ) 

187 ) 

188 with self._db.query(sql) as sql_result: 

189 sql_rows = sql_result.fetchall() 

190 for row in sql_rows: 

191 yield byId[row.dataset_id] 

192 

193 @contextmanager 

194 def emptyTrash( 

195 self, 

196 records_table: Optional[OpaqueTableStorage] = None, 

197 record_class: Optional[Type[StoredDatastoreItemInfo]] = None, 

198 record_column: Optional[str] = None, 

199 ) -> Iterator[ 

200 Tuple[Iterable[Tuple[DatasetIdRef, Optional[StoredDatastoreItemInfo]]], Optional[Set[str]]] 

201 ]: 

202 # Docstring inherited from DatastoreRegistryBridge 

203 

204 if records_table is None: 

205 raise ValueError("This implementation requires a records table.") 

206 

207 assert isinstance( 

208 records_table, ByNameOpaqueTableStorage 

209 ), f"Records table must support hidden attributes. Got {type(records_table)}." 

210 

211 if record_class is None: 

212 raise ValueError("Record class must be provided if records table is given.") 

213 

214 # Helper closure to generate the common join+where clause. 

215 def join_records( 

216 select: sqlalchemy.sql.Select, location_table: sqlalchemy.schema.Table 

217 ) -> sqlalchemy.sql.FromClause: 

218 # mypy needs to be sure 

219 assert isinstance(records_table, ByNameOpaqueTableStorage) 

220 return select.select_from( 

221 records_table._table.join( 

222 location_table, 

223 onclause=records_table._table.columns.dataset_id == location_table.columns.dataset_id, 

224 ) 

225 ).where(location_table.columns.datastore_name == self.datastoreName) 

226 

227 # SELECT records.dataset_id, records.path FROM records 

228 # JOIN records on dataset_location.dataset_id == records.dataset_id 

229 # WHERE dataset_location.datastore_name = datastoreName 

230 

231 # It's possible that we may end up with a ref listed in the trash 

232 # table that is not listed in the records table. Such an 

233 # inconsistency would be missed by this query. 

234 info_in_trash = join_records(records_table._table.select(), self._tables.dataset_location_trash) 

235 

236 # Run query, transform results into a list of dicts that we can later 

237 # use to delete. 

238 with self._db.query(info_in_trash) as sql_result: 

239 rows = [dict(**row, datastore_name=self.datastoreName) for row in sql_result.mappings()] 

240 

241 # It is possible for trashed refs to be linked to artifacts that 

242 # are still associated with refs that are not to be trashed. We 

243 # need to be careful to consider those and indicate to the caller 

244 # that those artifacts should be retained. Can only do this check 

245 # if the caller provides a column name that can map to multiple 

246 # refs. 

247 preserved: Optional[Set[str]] = None 

248 if record_column is not None: 

249 # Some helper subqueries 

250 items_not_in_trash = join_records( 

251 sqlalchemy.sql.select(records_table._table.columns[record_column]), 

252 self._tables.dataset_location, 

253 ).alias("items_not_in_trash") 

254 items_in_trash = join_records( 

255 sqlalchemy.sql.select(records_table._table.columns[record_column]), 

256 self._tables.dataset_location_trash, 

257 ).alias("items_in_trash") 

258 

259 # A query for paths that are referenced by datasets in the trash 

260 # and datasets not in the trash. 

261 items_to_preserve = sqlalchemy.sql.select(items_in_trash.columns[record_column]).select_from( 

262 items_not_in_trash.join( 

263 items_in_trash, 

264 onclause=items_in_trash.columns[record_column] 

265 == items_not_in_trash.columns[record_column], 

266 ) 

267 ) 

268 with self._db.query(items_to_preserve) as sql_result: 

269 preserved = {row[record_column] for row in sql_result.mappings()} 

270 

271 # Convert results to a tuple of id+info and a record of the artifacts 

272 # that should not be deleted from datastore. The id+info tuple is 

273 # solely to allow logging to report the relevant ID. 

274 id_info = ((FakeDatasetRef(row["dataset_id"]), record_class.from_record(row)) for row in rows) 

275 

276 # Start contextmanager, return results 

277 yield ((id_info, preserved)) 

278 

279 # No exception raised in context manager block. 

280 if not rows: 

281 return 

282 

283 # Delete the rows from the records table 

284 records_table.delete(["dataset_id"], *[{"dataset_id": row["dataset_id"]} for row in rows]) 

285 

286 # Delete those rows from the trash table. 

287 self._db.delete( 

288 self._tables.dataset_location_trash, 

289 ["dataset_id", "datastore_name"], 

290 *[{"dataset_id": row["dataset_id"], "datastore_name": row["datastore_name"]} for row in rows], 

291 ) 

292 

293 

294class MonolithicDatastoreRegistryBridgeManager(DatastoreRegistryBridgeManager): 

295 """An implementation of `DatastoreRegistryBridgeManager` that uses the same 

296 two tables for all non-ephemeral datastores. 

297 

298 Parameters 

299 ---------- 

300 db : `Database` 

301 Object providing a database connection and generic distractions. 

302 tables : `_TablesTuple` 

303 Named tuple containing `sqlalchemy.schema.Table` instances. 

304 opaque : `OpaqueTableStorageManager` 

305 Manager object for opaque table storage in the `Registry`. 

306 universe : `DimensionUniverse` 

307 All dimensions know to the `Registry`. 

308 datasetIdColumnType : `type` 

309 Type for dataset ID column. 

310 """ 

311 

312 def __init__( 

313 self, 

314 *, 

315 db: Database, 

316 tables: _TablesTuple, 

317 opaque: OpaqueTableStorageManager, 

318 universe: DimensionUniverse, 

319 datasetIdColumnType: type, 

320 ): 

321 super().__init__(opaque=opaque, universe=universe, datasetIdColumnType=datasetIdColumnType) 

322 self._db = db 

323 self._tables = tables 

324 self._ephemeral: Dict[str, EphemeralDatastoreRegistryBridge] = {} 

325 

326 @classmethod 

327 def initialize( 

328 cls, 

329 db: Database, 

330 context: StaticTablesContext, 

331 *, 

332 opaque: OpaqueTableStorageManager, 

333 datasets: Type[DatasetRecordStorageManager], 

334 universe: DimensionUniverse, 

335 ) -> DatastoreRegistryBridgeManager: 

336 # Docstring inherited from DatastoreRegistryBridge 

337 tables = context.addTableTuple(_makeTableSpecs(datasets)) 

338 return cls( 

339 db=db, 

340 tables=cast(_TablesTuple, tables), 

341 opaque=opaque, 

342 universe=universe, 

343 datasetIdColumnType=datasets.getIdColumnType(), 

344 ) 

345 

346 def refresh(self) -> None: 

347 # Docstring inherited from DatastoreRegistryBridge 

348 # This implementation has no in-Python state that depends on which 

349 # datastores exist, so there's nothing to do. 

350 pass 

351 

352 def register(self, name: str, *, ephemeral: bool = False) -> DatastoreRegistryBridge: 

353 # Docstring inherited from DatastoreRegistryBridge 

354 if ephemeral: 

355 return self._ephemeral.setdefault(name, EphemeralDatastoreRegistryBridge(name)) 

356 return MonolithicDatastoreRegistryBridge(name, db=self._db, tables=self._tables) 

357 

358 def findDatastores(self, ref: DatasetIdRef) -> Iterable[str]: 

359 # Docstring inherited from DatastoreRegistryBridge 

360 sql = ( 

361 sqlalchemy.sql.select(self._tables.dataset_location.columns.datastore_name) 

362 .select_from(self._tables.dataset_location) 

363 .where(self._tables.dataset_location.columns.dataset_id == ref.getCheckedId()) 

364 ) 

365 with self._db.query(sql) as sql_result: 

366 sql_rows = sql_result.mappings().fetchall() 

367 for row in sql_rows: 

368 yield row[self._tables.dataset_location.columns.datastore_name] 

369 for name, bridge in self._ephemeral.items(): 

370 if ref in bridge: 

371 yield name 

372 

373 @classmethod 

374 def currentVersion(cls) -> Optional[VersionTuple]: 

375 # Docstring inherited from VersionedExtension. 

376 return _VERSION 

377 

378 def schemaDigest(self) -> Optional[str]: 

379 # Docstring inherited from VersionedExtension. 

380 return self._defaultSchemaDigest(self._tables, self._db.dialect)