Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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 

25from collections import namedtuple 

26from contextlib import contextmanager 

27import copy 

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

29 

30import sqlalchemy 

31 

32from lsst.daf.butler import DatasetRef, ddl 

33from lsst.daf.butler.core.utils import NamedValueSet 

34from lsst.daf.butler.registry.interfaces import ( 

35 DatasetIdRef, 

36 DatastoreRegistryBridge, 

37 DatastoreRegistryBridgeManager, 

38 FakeDatasetRef, 

39) 

40from lsst.daf.butler.registry.bridge.ephemeral import EphemeralDatastoreRegistryBridge 

41 

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

43 from lsst.daf.butler import DimensionUniverse 

44 from lsst.daf.butler.registry.interfaces import ( 

45 Database, 

46 DatasetRecordStorageManager, 

47 OpaqueTableStorageManager, 

48 StaticTablesContext, 

49 ) 

50 

51 

52_TablesTuple = namedtuple( 

53 "_TablesTuple", 

54 [ 

55 "dataset_location", 

56 "dataset_location_trash", 

57 ] 

58) 

59 

60 

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

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

63 bridge classes. 

64 

65 Parameters 

66 ---------- 

67 universe : `DimensionUniverse` 

68 All dimensions known to the `Registry`. 

69 datasets : subclass of `DatasetRecordStorageManager` 

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

71 

72 Returns 

73 ------- 

74 specs : `_TablesTuple` 

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

76 """ 

77 # We want the dataset_location and dataset_location_trash tables 

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

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

80 dataset_location_spec = ddl.TableSpec( 

81 doc=( 

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

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

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

85 "Datastore. " 

86 ), 

87 fields=NamedValueSet([ 

88 ddl.FieldSpec( 

89 name="datastore_name", 

90 dtype=sqlalchemy.String, 

91 length=256, 

92 primaryKey=True, 

93 nullable=False, 

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

95 ), 

96 ]), 

97 ) 

98 dataset_location = copy.deepcopy(dataset_location_spec) 

99 datasets.addDatasetForeignKey(dataset_location, primaryKey=True) 

100 dataset_location_trash = copy.deepcopy(dataset_location_spec) 

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

102 return _TablesTuple( 

103 dataset_location=dataset_location, 

104 dataset_location_trash=dataset_location_trash, 

105 ) 

106 

107 

108class MonolithicDatastoreRegistryBridge(DatastoreRegistryBridge): 

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

110 tables for all non-ephemeral datastores. 

111 

112 Parameters 

113 ---------- 

114 datastoreName : `str` 

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

116 referencing it. 

117 db : `Database` 

118 Object providing a database connection and generic distractions. 

119 tables : `_TablesTuple` 

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

121 """ 

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

123 super().__init__(datastoreName) 

124 self._db = db 

125 self._tables = tables 

126 

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

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

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

130 class. 

131 

132 Parameters 

133 ---------- 

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

135 Datasets to transform. 

136 

137 Returns 

138 ------- 

139 rows : `list` [ `dict` ] 

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

141 """ 

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

143 

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

145 # Docstring inherited from DatastoreRegistryBridge 

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

147 

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

149 # Docstring inherited from DatastoreRegistryBridge 

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

151 # INSERT INTO dataset_location_trash 

152 # SELECT datastore_name, dataset_id FROM dataset_location 

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

154 # DELETE FROM dataset_location 

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

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

157 # right now. 

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

159 with self._db.transaction(): 

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

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

162 

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

164 # Docstring inherited from DatastoreRegistryBridge 

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

166 sql = sqlalchemy.sql.select( 

167 [self._tables.dataset_location.columns.dataset_id] 

168 ).select_from( 

169 self._tables.dataset_location 

170 ).where( 

171 sqlalchemy.sql.and_( 

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

173 self._tables.dataset_location.columns.dataset_id.in_(byId.keys()) 

174 ) 

175 ) 

176 for row in self._db.query(sql).fetchall(): 

177 yield byId[row["dataset_id"]] 

178 

179 @contextmanager 

180 def emptyTrash(self) -> Iterator[Iterable[DatasetIdRef]]: 

181 # Docstring inherited from DatastoreRegistryBridge 

182 sql = sqlalchemy.sql.select( 

183 [self._tables.dataset_location_trash.columns.dataset_id] 

184 ).select_from( 

185 self._tables.dataset_location_trash 

186 ).where( 

187 self._tables.dataset_location_trash.columns.datastore_name == self.datastoreName 

188 ) 

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

190 # use to delete. 

191 rows = [{"dataset_id": row["dataset_id"], "datastore_name": self.datastoreName} 

192 for row in self._db.query(sql).fetchall()] 

193 # Start contextmanager, returning generator expression to iterate over. 

194 yield (FakeDatasetRef(row["dataset_id"]) for row in rows) 

195 # No exception raised in context manager block. Delete those rows 

196 # from the trash table. 

197 self._db.delete(self._tables.dataset_location_trash, ["dataset_id", "datastore_name"], *rows) 

198 

199 

200class MonolithicDatastoreRegistryBridgeManager(DatastoreRegistryBridgeManager): 

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

202 two tables for all non-ephemeral datastores. 

203 

204 Parameters 

205 ---------- 

206 db : `Database` 

207 Object providing a database connection and generic distractions. 

208 tables : `_TablesTuple` 

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

210 opaque : `OpaqueTableStorageManager` 

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

212 universe : `DimensionUniverse` 

213 All dimensions know to the `Registry`. 

214 """ 

215 def __init__(self, *, db: Database, tables: _TablesTuple, 

216 opaque: OpaqueTableStorageManager, universe: DimensionUniverse): 

217 super().__init__(opaque=opaque, universe=universe) 

218 self._db = db 

219 self._tables = tables 

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

221 

222 @classmethod 

223 def initialize(cls, db: Database, context: StaticTablesContext, *, 

224 opaque: OpaqueTableStorageManager, 

225 datasets: Type[DatasetRecordStorageManager], 

226 universe: DimensionUniverse, 

227 ) -> DatastoreRegistryBridgeManager: 

228 # Docstring inherited from DatastoreRegistryBridge 

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

230 return cls(db=db, tables=cast(_TablesTuple, tables), opaque=opaque, universe=universe) 

231 

232 def refresh(self) -> None: 

233 # Docstring inherited from DatastoreRegistryBridge 

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

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

236 pass 

237 

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

239 # Docstring inherited from DatastoreRegistryBridge 

240 if ephemeral: 

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

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

243 

244 def findDatastores(self, ref: DatasetRef) -> Iterable[str]: 

245 # Docstring inherited from DatastoreRegistryBridge 

246 sql = sqlalchemy.sql.select( 

247 [self._tables.dataset_location.columns.datastore_name] 

248 ).select_from( 

249 self._tables.dataset_location 

250 ).where( 

251 self._tables.dataset_location.columns.dataset_id == ref.getCheckedId() 

252 ) 

253 for row in self._db.query(sql).fetchall(): 

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

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

256 if ref in bridge: 

257 yield name