Coverage for python/lsst/daf/butler/registry/collections/_base.py: 90%

180 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2022-11-15 01:58 -0800

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__ = () 

24 

25import itertools 

26from abc import abstractmethod 

27from collections import namedtuple 

28from collections.abc import Iterable, Iterator, Set 

29from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast 

30 

31import sqlalchemy 

32from lsst.utils.ellipsis import Ellipsis 

33 

34from ...core import DimensionUniverse, Timespan, TimespanDatabaseRepresentation, ddl 

35from .._collectionType import CollectionType 

36from .._exceptions import MissingCollectionError 

37from ..interfaces import ChainedCollectionRecord, CollectionManager, CollectionRecord, RunRecord 

38from ..wildcards import CollectionWildcard 

39 

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

41 from ..interfaces import Database, DimensionRecordStorageManager 

42 

43 

44def _makeCollectionForeignKey( 

45 sourceColumnName: str, collectionIdName: str, **kwargs: Any 

46) -> ddl.ForeignKeySpec: 

47 """Define foreign key specification that refers to collections table. 

48 

49 Parameters 

50 ---------- 

51 sourceColumnName : `str` 

52 Name of the column in the referring table. 

53 collectionIdName : `str` 

54 Name of the column in collections table that identifies it (PK). 

55 **kwargs 

56 Additional keyword arguments passed directly to `ddl.ForeignKeySpec`. 

57 

58 Returns 

59 ------- 

60 spec : `ddl.ForeignKeySpec` 

61 Foreign key specification. 

62 

63 Notes 

64 ----- 

65 This method assumes fixed name ("collection") of a collections table. 

66 There is also a general assumption that collection primary key consists 

67 of a single column. 

68 """ 

69 return ddl.ForeignKeySpec("collection", source=(sourceColumnName,), target=(collectionIdName,), **kwargs) 

70 

71 

72CollectionTablesTuple = namedtuple("CollectionTablesTuple", ["collection", "run", "collection_chain"]) 

73 

74 

75def makeRunTableSpec( 

76 collectionIdName: str, collectionIdType: type, TimespanReprClass: type[TimespanDatabaseRepresentation] 

77) -> ddl.TableSpec: 

78 """Define specification for "run" table. 

79 

80 Parameters 

81 ---------- 

82 collectionIdName : `str` 

83 Name of the column in collections table that identifies it (PK). 

84 collectionIdType 

85 Type of the PK column in the collections table, one of the 

86 `sqlalchemy` types. 

87 TimespanReprClass : `type` [ `TimespanDatabaseRepresentation` ] 

88 Subclass of `TimespanDatabaseRepresentation` that encapsulates how 

89 timespans are stored in this database. 

90 

91 

92 Returns 

93 ------- 

94 spec : `ddl.TableSpec` 

95 Specification for run table. 

96 

97 Notes 

98 ----- 

99 Assumption here and in the code below is that the name of the identifying 

100 column is the same in both collections and run tables. The names of 

101 non-identifying columns containing run metadata are fixed. 

102 """ 

103 result = ddl.TableSpec( 

104 fields=[ 

105 ddl.FieldSpec(collectionIdName, dtype=collectionIdType, primaryKey=True), 

106 ddl.FieldSpec("host", dtype=sqlalchemy.String, length=128), 

107 ], 

108 foreignKeys=[ 

109 _makeCollectionForeignKey(collectionIdName, collectionIdName, onDelete="CASCADE"), 

110 ], 

111 ) 

112 for fieldSpec in TimespanReprClass.makeFieldSpecs(nullable=True): 

113 result.fields.add(fieldSpec) 

114 return result 

115 

116 

117def makeCollectionChainTableSpec(collectionIdName: str, collectionIdType: type) -> ddl.TableSpec: 

118 """Define specification for "collection_chain" table. 

119 

120 Parameters 

121 ---------- 

122 collectionIdName : `str` 

123 Name of the column in collections table that identifies it (PK). 

124 collectionIdType 

125 Type of the PK column in the collections table, one of the 

126 `sqlalchemy` types. 

127 

128 Returns 

129 ------- 

130 spec : `ddl.TableSpec` 

131 Specification for collection chain table. 

132 

133 Notes 

134 ----- 

135 Collection chain is simply an ordered one-to-many relation between 

136 collections. The names of the columns in the table are fixed and 

137 also hardcoded in the code below. 

138 """ 

139 return ddl.TableSpec( 

140 fields=[ 

141 ddl.FieldSpec("parent", dtype=collectionIdType, primaryKey=True), 

142 ddl.FieldSpec("position", dtype=sqlalchemy.SmallInteger, primaryKey=True), 

143 ddl.FieldSpec("child", dtype=collectionIdType, nullable=False), 

144 ], 

145 foreignKeys=[ 

146 _makeCollectionForeignKey("parent", collectionIdName, onDelete="CASCADE"), 

147 _makeCollectionForeignKey("child", collectionIdName), 

148 ], 

149 ) 

150 

151 

152class DefaultRunRecord(RunRecord): 

153 """Default `RunRecord` implementation. 

154 

155 This method assumes the same run table definition as produced by 

156 `makeRunTableSpec` method. The only non-fixed name in the schema 

157 is the PK column name, this needs to be passed in a constructor. 

158 

159 Parameters 

160 ---------- 

161 db : `Database` 

162 Registry database. 

163 key 

164 Unique collection ID, can be the same as ``name`` if ``name`` is used 

165 for identification. Usually this is an integer or string, but can be 

166 other database-specific type. 

167 name : `str` 

168 Run collection name. 

169 table : `sqlalchemy.schema.Table` 

170 Table for run records. 

171 idColumnName : `str` 

172 Name of the identifying column in run table. 

173 host : `str`, optional 

174 Name of the host where run was produced. 

175 timespan : `Timespan`, optional 

176 Timespan for this run. 

177 """ 

178 

179 def __init__( 

180 self, 

181 db: Database, 

182 key: Any, 

183 name: str, 

184 *, 

185 table: sqlalchemy.schema.Table, 

186 idColumnName: str, 

187 host: str | None = None, 

188 timespan: Timespan | None = None, 

189 ): 

190 super().__init__(key=key, name=name, type=CollectionType.RUN) 

191 self._db = db 

192 self._table = table 

193 self._host = host 

194 if timespan is None: 194 ↛ 196line 194 didn't jump to line 196, because the condition on line 194 was never false

195 timespan = Timespan(begin=None, end=None) 

196 self._timespan = timespan 

197 self._idName = idColumnName 

198 

199 def update(self, host: str | None = None, timespan: Timespan | None = None) -> None: 

200 # Docstring inherited from RunRecord. 

201 if timespan is None: 

202 timespan = Timespan(begin=None, end=None) 

203 row = { 

204 self._idName: self.key, 

205 "host": host, 

206 } 

207 self._db.getTimespanRepresentation().update(timespan, result=row) 

208 count = self._db.update(self._table, {self._idName: self.key}, row) 

209 if count != 1: 

210 raise RuntimeError(f"Run update affected {count} records; expected exactly one.") 

211 self._host = host 

212 self._timespan = timespan 

213 

214 @property 

215 def host(self) -> str | None: 

216 # Docstring inherited from RunRecord. 

217 return self._host 

218 

219 @property 

220 def timespan(self) -> Timespan: 

221 # Docstring inherited from RunRecord. 

222 return self._timespan 

223 

224 

225class DefaultChainedCollectionRecord(ChainedCollectionRecord): 

226 """Default `ChainedCollectionRecord` implementation. 

227 

228 This method assumes the same chain table definition as produced by 

229 `makeCollectionChainTableSpec` method. All column names in the table are 

230 fixed and hard-coded in the methods. 

231 

232 Parameters 

233 ---------- 

234 db : `Database` 

235 Registry database. 

236 key 

237 Unique collection ID, can be the same as ``name`` if ``name`` is used 

238 for identification. Usually this is an integer or string, but can be 

239 other database-specific type. 

240 name : `str` 

241 Collection name. 

242 table : `sqlalchemy.schema.Table` 

243 Table for chain relationship records. 

244 universe : `DimensionUniverse` 

245 Object managing all known dimensions. 

246 """ 

247 

248 def __init__( 

249 self, 

250 db: Database, 

251 key: Any, 

252 name: str, 

253 *, 

254 table: sqlalchemy.schema.Table, 

255 universe: DimensionUniverse, 

256 ): 

257 super().__init__(key=key, name=name, universe=universe) 

258 self._db = db 

259 self._table = table 

260 self._universe = universe 

261 

262 def _update(self, manager: CollectionManager, children: tuple[str, ...]) -> None: 

263 # Docstring inherited from ChainedCollectionRecord. 

264 rows = [] 

265 position = itertools.count() 

266 for child in manager.resolve_wildcard(CollectionWildcard.from_names(children), flatten_chains=False): 

267 rows.append( 

268 { 

269 "parent": self.key, 

270 "child": child.key, 

271 "position": next(position), 

272 } 

273 ) 

274 with self._db.transaction(): 

275 self._db.delete(self._table, ["parent"], {"parent": self.key}) 

276 self._db.insert(self._table, *rows) 

277 

278 def _load(self, manager: CollectionManager) -> tuple[str, ...]: 

279 # Docstring inherited from ChainedCollectionRecord. 

280 sql = ( 

281 sqlalchemy.sql.select( 

282 self._table.columns.child, 

283 ) 

284 .select_from(self._table) 

285 .where(self._table.columns.parent == self.key) 

286 .order_by(self._table.columns.position) 

287 ) 

288 return tuple(manager[row._mapping[self._table.columns.child]].name for row in self._db.query(sql)) 

289 

290 

291K = TypeVar("K") 

292 

293 

294class DefaultCollectionManager(Generic[K], CollectionManager): 

295 """Default `CollectionManager` implementation. 

296 

297 This implementation uses record classes defined in this module and is 

298 based on the same assumptions about schema outlined in the record classes. 

299 

300 Parameters 

301 ---------- 

302 db : `Database` 

303 Interface to the underlying database engine and namespace. 

304 tables : `CollectionTablesTuple` 

305 Named tuple of SQLAlchemy table objects. 

306 collectionIdName : `str` 

307 Name of the column in collections table that identifies it (PK). 

308 dimensions : `DimensionRecordStorageManager` 

309 Manager object for the dimensions in this `Registry`. 

310 

311 Notes 

312 ----- 

313 Implementation uses "aggressive" pre-fetching and caching of the records 

314 in memory. Memory cache is synchronized from database when `refresh` 

315 method is called. 

316 """ 

317 

318 def __init__( 

319 self, 

320 db: Database, 

321 tables: CollectionTablesTuple, 

322 collectionIdName: str, 

323 *, 

324 dimensions: DimensionRecordStorageManager, 

325 ): 

326 super().__init__() 

327 self._db = db 

328 self._tables = tables 

329 self._collectionIdName = collectionIdName 

330 self._records: dict[K, CollectionRecord] = {} # indexed by record ID 

331 self._dimensions = dimensions 

332 

333 def refresh(self) -> None: 

334 # Docstring inherited from CollectionManager. 

335 sql = sqlalchemy.sql.select( 

336 *(list(self._tables.collection.columns) + list(self._tables.run.columns)) 

337 ).select_from(self._tables.collection.join(self._tables.run, isouter=True)) 

338 # Put found records into a temporary instead of updating self._records 

339 # in place, for exception safety. 

340 records = [] 

341 chains = [] 

342 TimespanReprClass = self._db.getTimespanRepresentation() 

343 for row in self._db.query(sql).mappings(): 

344 collection_id = row[self._tables.collection.columns[self._collectionIdName]] 

345 name = row[self._tables.collection.columns.name] 

346 type = CollectionType(row["type"]) 

347 record: CollectionRecord 

348 if type is CollectionType.RUN: 

349 record = DefaultRunRecord( 

350 key=collection_id, 

351 name=name, 

352 db=self._db, 

353 table=self._tables.run, 

354 idColumnName=self._collectionIdName, 

355 host=row[self._tables.run.columns.host], 

356 timespan=TimespanReprClass.extract(row), 

357 ) 

358 elif type is CollectionType.CHAINED: 

359 record = DefaultChainedCollectionRecord( 

360 db=self._db, 

361 key=collection_id, 

362 table=self._tables.collection_chain, 

363 name=name, 

364 universe=self._dimensions.universe, 

365 ) 

366 chains.append(record) 

367 else: 

368 record = CollectionRecord(key=collection_id, name=name, type=type) 

369 records.append(record) 

370 self._setRecordCache(records) 

371 for chain in chains: 

372 try: 

373 chain.refresh(self) 

374 except MissingCollectionError: 

375 # This indicates a race condition in which some other client 

376 # created a new collection and added it as a child of this 

377 # (pre-existing) chain between the time we fetched all 

378 # collections and the time we queried for parent-child 

379 # relationships. 

380 # Because that's some other unrelated client, we shouldn't care 

381 # about that parent collection anyway, so we just drop it on 

382 # the floor (a manual refresh can be used to get it back). 

383 self._removeCachedRecord(chain) 

384 

385 def register( 

386 self, name: str, type: CollectionType, doc: str | None = None 

387 ) -> tuple[CollectionRecord, bool]: 

388 # Docstring inherited from CollectionManager. 

389 registered = False 

390 record = self._getByName(name) 

391 if record is None: 

392 row, inserted_or_updated = self._db.sync( 

393 self._tables.collection, 

394 keys={"name": name}, 

395 compared={"type": int(type)}, 

396 extra={"doc": doc}, 

397 returning=[self._collectionIdName], 

398 ) 

399 assert isinstance(inserted_or_updated, bool) 

400 registered = inserted_or_updated 

401 assert row is not None 

402 collection_id = row[self._collectionIdName] 

403 if type is CollectionType.RUN: 

404 TimespanReprClass = self._db.getTimespanRepresentation() 

405 row, _ = self._db.sync( 

406 self._tables.run, 

407 keys={self._collectionIdName: collection_id}, 

408 returning=("host",) + TimespanReprClass.getFieldNames(), 

409 ) 

410 assert row is not None 

411 record = DefaultRunRecord( 

412 db=self._db, 

413 key=collection_id, 

414 name=name, 

415 table=self._tables.run, 

416 idColumnName=self._collectionIdName, 

417 host=row["host"], 

418 timespan=TimespanReprClass.extract(row), 

419 ) 

420 elif type is CollectionType.CHAINED: 

421 record = DefaultChainedCollectionRecord( 

422 db=self._db, 

423 key=collection_id, 

424 name=name, 

425 table=self._tables.collection_chain, 

426 universe=self._dimensions.universe, 

427 ) 

428 else: 

429 record = CollectionRecord(key=collection_id, name=name, type=type) 

430 self._addCachedRecord(record) 

431 return record, registered 

432 

433 def remove(self, name: str) -> None: 

434 # Docstring inherited from CollectionManager. 

435 record = self._getByName(name) 

436 if record is None: 436 ↛ 437line 436 didn't jump to line 437, because the condition on line 436 was never true

437 raise MissingCollectionError(f"No collection with name '{name}' found.") 

438 # This may raise 

439 self._db.delete( 

440 self._tables.collection, [self._collectionIdName], {self._collectionIdName: record.key} 

441 ) 

442 self._removeCachedRecord(record) 

443 

444 def find(self, name: str) -> CollectionRecord: 

445 # Docstring inherited from CollectionManager. 

446 result = self._getByName(name) 

447 if result is None: 

448 raise MissingCollectionError(f"No collection with name '{name}' found.") 

449 return result 

450 

451 def __getitem__(self, key: Any) -> CollectionRecord: 

452 # Docstring inherited from CollectionManager. 

453 try: 

454 return self._records[key] 

455 except KeyError as err: 

456 raise MissingCollectionError(f"Collection with key '{key}' not found.") from err 

457 

458 def resolve_wildcard( 

459 self, 

460 wildcard: CollectionWildcard, 

461 *, 

462 collection_types: Set[CollectionType] = CollectionType.all(), 

463 done: set[str] | None = None, 

464 flatten_chains: bool = True, 

465 include_chains: bool | None = None, 

466 ) -> list[CollectionRecord]: 

467 # Docstring inherited 

468 if done is None: 468 ↛ 470line 468 didn't jump to line 470, because the condition on line 468 was never false

469 done = set() 

470 include_chains = include_chains if include_chains is not None else not flatten_chains 

471 

472 def resolve_nested(record: CollectionRecord, done: set[str]) -> Iterator[CollectionRecord]: 

473 if record.name in done: 

474 return 

475 if record.type in collection_types: 

476 done.add(record.name) 

477 if record.type is not CollectionType.CHAINED or include_chains: 

478 yield record 

479 if flatten_chains and record.type is CollectionType.CHAINED: 

480 done.add(record.name) 

481 for name in cast(ChainedCollectionRecord, record).children: 

482 # flake8 can't tell that we only delete this closure when 

483 # we're totally done with it. 

484 yield from resolve_nested(self.find(name), done) # noqa: F821 

485 

486 result: list[CollectionRecord] = [] 

487 

488 if wildcard.patterns is Ellipsis: 

489 for record in self._records.values(): 

490 result.extend(resolve_nested(record, done)) 

491 del resolve_nested 

492 return result 

493 for name in wildcard.strings: 

494 result.extend(resolve_nested(self.find(name), done)) 

495 if wildcard.patterns: 

496 for record in self._records.values(): 

497 if any(p.fullmatch(record.name) for p in wildcard.patterns): 

498 result.extend(resolve_nested(record, done)) 

499 del resolve_nested 

500 return result 

501 

502 def getDocumentation(self, key: Any) -> str | None: 

503 # Docstring inherited from CollectionManager. 

504 sql = ( 

505 sqlalchemy.sql.select(self._tables.collection.columns.doc) 

506 .select_from(self._tables.collection) 

507 .where(self._tables.collection.columns[self._collectionIdName] == key) 

508 ) 

509 return self._db.query(sql).scalar() 

510 

511 def setDocumentation(self, key: Any, doc: str | None) -> None: 

512 # Docstring inherited from CollectionManager. 

513 self._db.update(self._tables.collection, {self._collectionIdName: "key"}, {"key": key, "doc": doc}) 

514 

515 def _setRecordCache(self, records: Iterable[CollectionRecord]) -> None: 

516 """Set internal record cache to contain given records, 

517 old cached records will be removed. 

518 """ 

519 self._records = {} 

520 for record in records: 

521 self._records[record.key] = record 

522 

523 def _addCachedRecord(self, record: CollectionRecord) -> None: 

524 """Add single record to cache.""" 

525 self._records[record.key] = record 

526 

527 def _removeCachedRecord(self, record: CollectionRecord) -> None: 

528 """Remove single record from cache.""" 

529 del self._records[record.key] 

530 

531 @abstractmethod 

532 def _getByName(self, name: str) -> CollectionRecord | None: 

533 """Find collection record given collection name.""" 

534 raise NotImplementedError()