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

99 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-28 10:10 +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 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 collections.abc import Iterable, Iterator 

28from contextlib import contextmanager 

29from typing import TYPE_CHECKING, cast 

30 

31import sqlalchemy 

32 

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

34from ..interfaces import ( 

35 DatasetIdRef, 

36 DatastoreRegistryBridge, 

37 DatastoreRegistryBridgeManager, 

38 FakeDatasetRef, 

39 OpaqueTableStorage, 

40 VersionTuple, 

41) 

42from ..opaque import ByNameOpaqueTableStorage 

43from .ephemeral import EphemeralDatastoreRegistryBridge 

44 

45if TYPE_CHECKING: 

46 from ...core import DimensionUniverse 

47 from ...core.datastore import DatastoreTransaction 

48 from ..interfaces import ( 

49 Database, 

50 DatasetRecordStorageManager, 

51 OpaqueTableStorageManager, 

52 StaticTablesContext, 

53 ) 

54 

55_TablesTuple = namedtuple( 

56 "_TablesTuple", 

57 [ 

58 "dataset_location", 

59 "dataset_location_trash", 

60 ], 

61) 

62 

63# This has to be updated on every schema change 

64_VERSION = VersionTuple(0, 2, 0) 

65 

66 

67def _makeTableSpecs(datasets: type[DatasetRecordStorageManager]) -> _TablesTuple: 

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

69 bridge classes. 

70 

71 Parameters 

72 ---------- 

73 universe : `DimensionUniverse` 

74 All dimensions known to the `Registry`. 

75 datasets : subclass of `DatasetRecordStorageManager` 

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

77 

78 Returns 

79 ------- 

80 specs : `_TablesTuple` 

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

82 """ 

83 # We want the dataset_location and dataset_location_trash tables 

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

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

86 dataset_location_spec = ddl.TableSpec( 

87 doc=( 

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

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

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

91 "Datastore. " 

92 ), 

93 fields=NamedValueSet( 

94 [ 

95 ddl.FieldSpec( 

96 name="datastore_name", 

97 dtype=sqlalchemy.String, 

98 length=256, 

99 primaryKey=True, 

100 nullable=False, 

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

102 ), 

103 ] 

104 ), 

105 ) 

106 dataset_location = copy.deepcopy(dataset_location_spec) 

107 datasets.addDatasetForeignKey(dataset_location, primaryKey=True) 

108 dataset_location_trash = copy.deepcopy(dataset_location_spec) 

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

110 return _TablesTuple( 

111 dataset_location=dataset_location, 

112 dataset_location_trash=dataset_location_trash, 

113 ) 

114 

115 

116class MonolithicDatastoreRegistryBridge(DatastoreRegistryBridge): 

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

118 tables for all non-ephemeral datastores. 

119 

120 Parameters 

121 ---------- 

122 datastoreName : `str` 

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

124 referencing it. 

125 db : `Database` 

126 Object providing a database connection and generic distractions. 

127 tables : `_TablesTuple` 

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

129 """ 

130 

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

132 super().__init__(datastoreName) 

133 self._db = db 

134 self._tables = tables 

135 

136 def _refsToRows(self, refs: Iterable[DatasetIdRef]) -> list[dict]: 

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

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

139 class. 

140 

141 Parameters 

142 ---------- 

143 refs : `~collections.abc.Iterable` [ `DatasetRef` or `FakeDatasetRef` ] 

144 Datasets to transform. 

145 

146 Returns 

147 ------- 

148 rows : `list` [ `dict` ] 

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

150 """ 

151 return [{"datastore_name": self.datastoreName, "dataset_id": ref.id} for ref in refs] 

152 

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

154 # Docstring inherited from DatastoreRegistryBridge 

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

156 

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

158 # Docstring inherited from DatastoreRegistryBridge 

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

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

161 

162 def moveToTrash(self, refs: Iterable[DatasetIdRef], transaction: DatastoreTransaction | None) -> None: 

163 # Docstring inherited from DatastoreRegistryBridge 

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

165 # INSERT INTO dataset_location_trash 

166 # SELECT datastore_name, dataset_id FROM dataset_location 

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

168 # DELETE FROM dataset_location 

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

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

171 # right now. 

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

173 with self._db.transaction(): 

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

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

176 

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

178 # Docstring inherited from DatastoreRegistryBridge 

179 byId = {ref.id: ref for ref in refs} 

180 sql = ( 

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

182 .select_from(self._tables.dataset_location) 

183 .where( 

184 sqlalchemy.sql.and_( 

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

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

187 ) 

188 ) 

189 ) 

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

191 sql_rows = sql_result.fetchall() 

192 for row in sql_rows: 

193 yield byId[row.dataset_id] 

194 

195 @contextmanager 

196 def emptyTrash( 

197 self, 

198 records_table: OpaqueTableStorage | None = None, 

199 record_class: type[StoredDatastoreItemInfo] | None = None, 

200 record_column: str | None = None, 

201 ) -> Iterator[tuple[Iterable[tuple[DatasetIdRef, StoredDatastoreItemInfo | None]], set[str] | None]]: 

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.Select: 

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: set[str] | None = 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 registry_schema_version: VersionTuple | None = None, 

321 ): 

322 super().__init__( 

323 opaque=opaque, 

324 universe=universe, 

325 datasetIdColumnType=datasetIdColumnType, 

326 registry_schema_version=registry_schema_version, 

327 ) 

328 self._db = db 

329 self._tables = tables 

330 self._ephemeral: dict[str, EphemeralDatastoreRegistryBridge] = {} 

331 

332 @classmethod 

333 def initialize( 

334 cls, 

335 db: Database, 

336 context: StaticTablesContext, 

337 *, 

338 opaque: OpaqueTableStorageManager, 

339 datasets: type[DatasetRecordStorageManager], 

340 universe: DimensionUniverse, 

341 registry_schema_version: VersionTuple | None = None, 

342 ) -> DatastoreRegistryBridgeManager: 

343 # Docstring inherited from DatastoreRegistryBridge 

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

345 return cls( 

346 db=db, 

347 tables=cast(_TablesTuple, tables), 

348 opaque=opaque, 

349 universe=universe, 

350 datasetIdColumnType=datasets.getIdColumnType(), 

351 registry_schema_version=registry_schema_version, 

352 ) 

353 

354 def refresh(self) -> None: 

355 # Docstring inherited from DatastoreRegistryBridge 

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

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

358 pass 

359 

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

361 # Docstring inherited from DatastoreRegistryBridge 

362 if ephemeral: 

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

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

365 

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

367 # Docstring inherited from DatastoreRegistryBridge 

368 sql = ( 

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

370 .select_from(self._tables.dataset_location) 

371 .where(self._tables.dataset_location.columns.dataset_id == ref.id) 

372 ) 

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

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

375 for row in sql_rows: 

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

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

378 if ref in bridge: 

379 yield name 

380 

381 @classmethod 

382 def currentVersions(cls) -> list[VersionTuple]: 

383 # Docstring inherited from VersionedExtension. 

384 return [_VERSION]