Coverage for python/lsst/daf/butler/registry/datasets/byDimensions/_storage.py: 95%

241 statements  

« prev     ^ index     » next       coverage.py v7.2.5, created at 2023-05-06 09:31 +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/>. 

21 

22 

23from __future__ import annotations 

24 

25__all__ = ("ByDimensionsDatasetRecordStorage",) 

26 

27import uuid 

28from collections.abc import Iterable, Iterator, Sequence, Set 

29from datetime import datetime 

30from typing import TYPE_CHECKING 

31 

32import astropy.time 

33import sqlalchemy 

34from lsst.daf.relation import Relation, sql 

35 

36from ....core import ( 

37 DataCoordinate, 

38 DatasetColumnTag, 

39 DatasetId, 

40 DatasetIdFactory, 

41 DatasetIdGenEnum, 

42 DatasetRef, 

43 DatasetType, 

44 DimensionKeyColumnTag, 

45 LogicalColumn, 

46 Timespan, 

47 ddl, 

48) 

49from ..._collection_summary import CollectionSummary 

50from ..._collectionType import CollectionType 

51from ..._exceptions import CollectionTypeError, ConflictingDefinitionError 

52from ...interfaces import DatasetRecordStorage 

53from ...queries import SqlQueryContext 

54from .tables import makeTagTableSpec 

55 

56if TYPE_CHECKING: 

57 from ...interfaces import CollectionManager, CollectionRecord, Database, RunRecord 

58 from .summaries import CollectionSummaryManager 

59 from .tables import StaticDatasetTablesTuple 

60 

61 

62class ByDimensionsDatasetRecordStorage(DatasetRecordStorage): 

63 """Dataset record storage implementation paired with 

64 `ByDimensionsDatasetRecordStorageManagerUUID`; see that class for more 

65 information. 

66 

67 Instances of this class should never be constructed directly; use 

68 `DatasetRecordStorageManager.register` instead. 

69 """ 

70 

71 def __init__( 

72 self, 

73 *, 

74 datasetType: DatasetType, 

75 db: Database, 

76 dataset_type_id: int, 

77 collections: CollectionManager, 

78 static: StaticDatasetTablesTuple, 

79 summaries: CollectionSummaryManager, 

80 tags: sqlalchemy.schema.Table, 

81 use_astropy_ingest_date: bool, 

82 calibs: sqlalchemy.schema.Table | None, 

83 ): 

84 super().__init__(datasetType=datasetType) 

85 self._dataset_type_id = dataset_type_id 

86 self._db = db 

87 self._collections = collections 

88 self._static = static 

89 self._summaries = summaries 

90 self._tags = tags 

91 self._calibs = calibs 

92 self._runKeyColumn = collections.getRunForeignKeyName() 

93 self._use_astropy = use_astropy_ingest_date 

94 

95 def delete(self, datasets: Iterable[DatasetRef]) -> None: 

96 # Docstring inherited from DatasetRecordStorage. 

97 # Only delete from common dataset table; ON DELETE foreign key clauses 

98 # will handle the rest. 

99 self._db.delete( 

100 self._static.dataset, 

101 ["id"], 

102 *[{"id": dataset.getCheckedId()} for dataset in datasets], 

103 ) 

104 

105 def associate(self, collection: CollectionRecord, datasets: Iterable[DatasetRef]) -> None: 

106 # Docstring inherited from DatasetRecordStorage. 

107 if collection.type is not CollectionType.TAGGED: 107 ↛ 108line 107 didn't jump to line 108, because the condition on line 107 was never true

108 raise TypeError( 

109 f"Cannot associate into collection '{collection.name}' " 

110 f"of type {collection.type.name}; must be TAGGED." 

111 ) 

112 protoRow = { 

113 self._collections.getCollectionForeignKeyName(): collection.key, 

114 "dataset_type_id": self._dataset_type_id, 

115 } 

116 rows = [] 

117 summary = CollectionSummary() 

118 for dataset in summary.add_datasets_generator(datasets): 

119 row = dict(protoRow, dataset_id=dataset.getCheckedId()) 

120 for dimension, value in dataset.dataId.items(): 

121 row[dimension.name] = value 

122 rows.append(row) 

123 # Update the summary tables for this collection in case this is the 

124 # first time this dataset type or these governor values will be 

125 # inserted there. 

126 self._summaries.update(collection, [self._dataset_type_id], summary) 

127 # Update the tag table itself. 

128 self._db.replace(self._tags, *rows) 

129 

130 def disassociate(self, collection: CollectionRecord, datasets: Iterable[DatasetRef]) -> None: 

131 # Docstring inherited from DatasetRecordStorage. 

132 if collection.type is not CollectionType.TAGGED: 132 ↛ 133line 132 didn't jump to line 133, because the condition on line 132 was never true

133 raise TypeError( 

134 f"Cannot disassociate from collection '{collection.name}' " 

135 f"of type {collection.type.name}; must be TAGGED." 

136 ) 

137 rows = [ 

138 { 

139 "dataset_id": dataset.getCheckedId(), 

140 self._collections.getCollectionForeignKeyName(): collection.key, 

141 } 

142 for dataset in datasets 

143 ] 

144 self._db.delete(self._tags, ["dataset_id", self._collections.getCollectionForeignKeyName()], *rows) 

145 

146 def _buildCalibOverlapQuery( 

147 self, 

148 collection: CollectionRecord, 

149 data_ids: set[DataCoordinate] | None, 

150 timespan: Timespan, 

151 context: SqlQueryContext, 

152 ) -> Relation: 

153 relation = self.make_relation( 

154 collection, columns={"timespan", "dataset_id", "calib_pkey"}, context=context 

155 ).with_rows_satisfying( 

156 context.make_timespan_overlap_predicate( 

157 DatasetColumnTag(self.datasetType.name, "timespan"), timespan 

158 ), 

159 ) 

160 if data_ids is not None: 

161 relation = relation.join( 

162 context.make_data_id_relation( 

163 data_ids, self.datasetType.dimensions.required.names 

164 ).transferred_to(context.sql_engine), 

165 ) 

166 return relation 

167 

168 def certify( 

169 self, 

170 collection: CollectionRecord, 

171 datasets: Iterable[DatasetRef], 

172 timespan: Timespan, 

173 context: SqlQueryContext, 

174 ) -> None: 

175 # Docstring inherited from DatasetRecordStorage. 

176 if self._calibs is None: 176 ↛ 177line 176 didn't jump to line 177, because the condition on line 176 was never true

177 raise CollectionTypeError( 

178 f"Cannot certify datasets of type {self.datasetType.name}, for which " 

179 "DatasetType.isCalibration() is False." 

180 ) 

181 if collection.type is not CollectionType.CALIBRATION: 181 ↛ 182line 181 didn't jump to line 182, because the condition on line 181 was never true

182 raise CollectionTypeError( 

183 f"Cannot certify into collection '{collection.name}' " 

184 f"of type {collection.type.name}; must be CALIBRATION." 

185 ) 

186 TimespanReprClass = self._db.getTimespanRepresentation() 

187 protoRow = { 

188 self._collections.getCollectionForeignKeyName(): collection.key, 

189 "dataset_type_id": self._dataset_type_id, 

190 } 

191 rows = [] 

192 dataIds: set[DataCoordinate] | None = ( 

193 set() if not TimespanReprClass.hasExclusionConstraint() else None 

194 ) 

195 summary = CollectionSummary() 

196 for dataset in summary.add_datasets_generator(datasets): 

197 row = dict(protoRow, dataset_id=dataset.getCheckedId()) 

198 for dimension, value in dataset.dataId.items(): 

199 row[dimension.name] = value 

200 TimespanReprClass.update(timespan, result=row) 

201 rows.append(row) 

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

203 dataIds.add(dataset.dataId) 

204 # Update the summary tables for this collection in case this is the 

205 # first time this dataset type or these governor values will be 

206 # inserted there. 

207 self._summaries.update(collection, [self._dataset_type_id], summary) 

208 # Update the association table itself. 

209 if TimespanReprClass.hasExclusionConstraint(): 209 ↛ 212line 209 didn't jump to line 212, because the condition on line 209 was never true

210 # Rely on database constraint to enforce invariants; we just 

211 # reraise the exception for consistency across DB engines. 

212 try: 

213 self._db.insert(self._calibs, *rows) 

214 except sqlalchemy.exc.IntegrityError as err: 

215 raise ConflictingDefinitionError( 

216 f"Validity range conflict certifying datasets of type {self.datasetType.name} " 

217 f"into {collection.name} for range [{timespan.begin}, {timespan.end})." 

218 ) from err 

219 else: 

220 # Have to implement exclusion constraint ourselves. 

221 # Start by building a SELECT query for any rows that would overlap 

222 # this one. 

223 relation = self._buildCalibOverlapQuery(collection, dataIds, timespan, context) 

224 # Acquire a table lock to ensure there are no concurrent writes 

225 # could invalidate our checking before we finish the inserts. We 

226 # use a SAVEPOINT in case there is an outer transaction that a 

227 # failure here should not roll back. 

228 with self._db.transaction(lock=[self._calibs], savepoint=True): 

229 # Enter SqlQueryContext in case we need to use a temporary 

230 # table to include the give data IDs in the query. Note that 

231 # by doing this inside the transaction, we make sure it doesn't 

232 # attempt to close the session when its done, since it just 

233 # sees an already-open session that it knows it shouldn't 

234 # manage. 

235 with context: 

236 # Run the check SELECT query. 

237 conflicting = context.count(context.process(relation)) 

238 if conflicting > 0: 

239 raise ConflictingDefinitionError( 

240 f"{conflicting} validity range conflicts certifying datasets of type " 

241 f"{self.datasetType.name} into {collection.name} for range " 

242 f"[{timespan.begin}, {timespan.end})." 

243 ) 

244 # Proceed with the insert. 

245 self._db.insert(self._calibs, *rows) 

246 

247 def decertify( 

248 self, 

249 collection: CollectionRecord, 

250 timespan: Timespan, 

251 *, 

252 dataIds: Iterable[DataCoordinate] | None = None, 

253 context: SqlQueryContext, 

254 ) -> None: 

255 # Docstring inherited from DatasetRecordStorage. 

256 if self._calibs is None: 256 ↛ 257line 256 didn't jump to line 257, because the condition on line 256 was never true

257 raise CollectionTypeError( 

258 f"Cannot decertify datasets of type {self.datasetType.name}, for which " 

259 "DatasetType.isCalibration() is False." 

260 ) 

261 if collection.type is not CollectionType.CALIBRATION: 261 ↛ 262line 261 didn't jump to line 262, because the condition on line 261 was never true

262 raise CollectionTypeError( 

263 f"Cannot decertify from collection '{collection.name}' " 

264 f"of type {collection.type.name}; must be CALIBRATION." 

265 ) 

266 TimespanReprClass = self._db.getTimespanRepresentation() 

267 # Construct a SELECT query to find all rows that overlap our inputs. 

268 dataIdSet: set[DataCoordinate] | None 

269 if dataIds is not None: 

270 dataIdSet = set(dataIds) 

271 else: 

272 dataIdSet = None 

273 relation = self._buildCalibOverlapQuery(collection, dataIdSet, timespan, context) 

274 calib_pkey_tag = DatasetColumnTag(self.datasetType.name, "calib_pkey") 

275 dataset_id_tag = DatasetColumnTag(self.datasetType.name, "dataset_id") 

276 timespan_tag = DatasetColumnTag(self.datasetType.name, "timespan") 

277 data_id_tags = [ 

278 (name, DimensionKeyColumnTag(name)) for name in self.datasetType.dimensions.required.names 

279 ] 

280 # Set up collections to populate with the rows we'll want to modify. 

281 # The insert rows will have the same values for collection and 

282 # dataset type. 

283 protoInsertRow = { 

284 self._collections.getCollectionForeignKeyName(): collection.key, 

285 "dataset_type_id": self._dataset_type_id, 

286 } 

287 rowsToDelete = [] 

288 rowsToInsert = [] 

289 # Acquire a table lock to ensure there are no concurrent writes 

290 # between the SELECT and the DELETE and INSERT queries based on it. 

291 with self._db.transaction(lock=[self._calibs], savepoint=True): 

292 # Enter SqlQueryContext in case we need to use a temporary table to 

293 # include the give data IDs in the query (see similar block in 

294 # certify for details). 

295 with context: 

296 for row in context.fetch_iterable(relation): 

297 rowsToDelete.append({"id": row[calib_pkey_tag]}) 

298 # Construct the insert row(s) by copying the prototype row, 

299 # then adding the dimension column values, then adding 

300 # what's left of the timespan from that row after we 

301 # subtract the given timespan. 

302 newInsertRow = protoInsertRow.copy() 

303 newInsertRow["dataset_id"] = row[dataset_id_tag] 

304 for name, tag in data_id_tags: 

305 newInsertRow[name] = row[tag] 

306 rowTimespan = row[timespan_tag] 

307 assert rowTimespan is not None, "Field should have a NOT NULL constraint." 

308 for diffTimespan in rowTimespan.difference(timespan): 

309 rowsToInsert.append( 

310 TimespanReprClass.update(diffTimespan, result=newInsertRow.copy()) 

311 ) 

312 # Run the DELETE and INSERT queries. 

313 self._db.delete(self._calibs, ["id"], *rowsToDelete) 

314 self._db.insert(self._calibs, *rowsToInsert) 

315 

316 def make_relation( 

317 self, 

318 *collections: CollectionRecord, 

319 columns: Set[str], 

320 context: SqlQueryContext, 

321 ) -> Relation: 

322 # Docstring inherited from DatasetRecordStorage. 

323 collection_types = {collection.type for collection in collections} 

324 assert CollectionType.CHAINED not in collection_types, "CHAINED collections must be flattened." 

325 TimespanReprClass = self._db.getTimespanRepresentation() 

326 # 

327 # There are two kinds of table in play here: 

328 # 

329 # - the static dataset table (with the dataset ID, dataset type ID, 

330 # run ID/name, and ingest date); 

331 # 

332 # - the dynamic tags/calibs table (with the dataset ID, dataset type 

333 # type ID, collection ID/name, data ID, and possibly validity 

334 # range). 

335 # 

336 # That means that we might want to return a query against either table 

337 # or a JOIN of both, depending on which quantities the caller wants. 

338 # But the data ID is always included, which means we'll always include 

339 # the tags/calibs table and join in the static dataset table only if we 

340 # need things from it that we can't get from the tags/calibs table. 

341 # 

342 # Note that it's important that we include a WHERE constraint on both 

343 # tables for any column (e.g. dataset_type_id) that is in both when 

344 # it's given explicitly; not doing can prevent the query planner from 

345 # using very important indexes. At present, we don't include those 

346 # redundant columns in the JOIN ON expression, however, because the 

347 # FOREIGN KEY (and its index) are defined only on dataset_id. 

348 tag_relation: Relation | None = None 

349 calib_relation: Relation | None = None 

350 if collection_types != {CollectionType.CALIBRATION}: 

351 # We'll need a subquery for the tags table if any of the given 

352 # collections are not a CALIBRATION collection. This intentionally 

353 # also fires when the list of collections is empty as a way to 

354 # create a dummy subquery that we know will fail. 

355 # We give the table an alias because it might appear multiple times 

356 # in the same query, for different dataset types. 

357 tags_parts = sql.Payload[LogicalColumn](self._tags.alias(f"{self.datasetType.name}_tags")) 

358 if "timespan" in columns: 

359 tags_parts.columns_available[ 

360 DatasetColumnTag(self.datasetType.name, "timespan") 

361 ] = TimespanReprClass.fromLiteral(Timespan(None, None)) 

362 tag_relation = self._finish_single_relation( 

363 tags_parts, 

364 columns, 

365 [ 

366 (record, rank) 

367 for rank, record in enumerate(collections) 

368 if record.type is not CollectionType.CALIBRATION 

369 ], 

370 context, 

371 ) 

372 assert "calib_pkey" not in columns, "For internal use only, and only for pure-calib queries." 

373 if CollectionType.CALIBRATION in collection_types: 

374 # If at least one collection is a CALIBRATION collection, we'll 

375 # need a subquery for the calibs table, and could include the 

376 # timespan as a result or constraint. 

377 assert ( 

378 self._calibs is not None 

379 ), "DatasetTypes with isCalibration() == False can never be found in a CALIBRATION collection." 

380 calibs_parts = sql.Payload[LogicalColumn](self._calibs.alias(f"{self.datasetType.name}_calibs")) 

381 if "timespan" in columns: 

382 calibs_parts.columns_available[ 

383 DatasetColumnTag(self.datasetType.name, "timespan") 

384 ] = TimespanReprClass.from_columns(calibs_parts.from_clause.columns) 

385 if "calib_pkey" in columns: 

386 # This is a private extension not included in the base class 

387 # interface, for internal use only in _buildCalibOverlapQuery, 

388 # which needs access to the autoincrement primary key for the 

389 # calib association table. 

390 calibs_parts.columns_available[ 

391 DatasetColumnTag(self.datasetType.name, "calib_pkey") 

392 ] = calibs_parts.from_clause.columns.id 

393 calib_relation = self._finish_single_relation( 

394 calibs_parts, 

395 columns, 

396 [ 

397 (record, rank) 

398 for rank, record in enumerate(collections) 

399 if record.type is CollectionType.CALIBRATION 

400 ], 

401 context, 

402 ) 

403 if tag_relation is not None: 

404 if calib_relation is not None: 

405 # daf_relation's chain operation does not automatically 

406 # deduplicate; it's more like SQL's UNION ALL. To get UNION 

407 # in SQL here, we add an explicit deduplication. 

408 return tag_relation.chain(calib_relation).without_duplicates() 

409 else: 

410 return tag_relation 

411 elif calib_relation is not None: 

412 return calib_relation 

413 else: 

414 raise AssertionError("Branch should be unreachable.") 

415 

416 def _finish_single_relation( 

417 self, 

418 payload: sql.Payload[LogicalColumn], 

419 requested_columns: Set[str], 

420 collections: Sequence[tuple[CollectionRecord, int]], 

421 context: SqlQueryContext, 

422 ) -> Relation: 

423 """Helper method for `make_relation`. 

424 

425 This handles adding columns and WHERE terms that are not specific to 

426 either the tags or calibs tables. 

427 

428 Parameters 

429 ---------- 

430 payload : `lsst.daf.relation.sql.Payload` 

431 SQL query parts under construction, to be modified in-place and 

432 used to construct the new relation. 

433 requested_columns : `~collections.abc.Set` [ `str` ] 

434 Columns the relation should include. 

435 collections : `Sequence` [ `tuple` [ `CollectionRecord`, `int` ] ] 

436 Collections to search for the dataset and their ranks. 

437 context : `SqlQueryContext` 

438 Context that manages engines and state for the query. 

439 

440 Returns 

441 ------- 

442 relation : `lsst.daf.relation.Relation` 

443 New dataset query relation. 

444 """ 

445 payload.where.append(payload.from_clause.columns.dataset_type_id == self._dataset_type_id) 

446 dataset_id_col = payload.from_clause.columns.dataset_id 

447 collection_col = payload.from_clause.columns[self._collections.getCollectionForeignKeyName()] 

448 # We always constrain and optionally retrieve the collection(s) via the 

449 # tags/calibs table. 

450 if len(collections) == 1: 

451 payload.where.append(collection_col == collections[0][0].key) 

452 if "collection" in requested_columns: 

453 payload.columns_available[ 

454 DatasetColumnTag(self.datasetType.name, "collection") 

455 ] = sqlalchemy.sql.literal(collections[0][0].key) 

456 else: 

457 assert collections, "The no-collections case should be in calling code for better diagnostics." 

458 payload.where.append(collection_col.in_([collection.key for collection, _ in collections])) 

459 if "collection" in requested_columns: 

460 payload.columns_available[ 

461 DatasetColumnTag(self.datasetType.name, "collection") 

462 ] = collection_col 

463 # Add rank if requested as a CASE-based calculation the collection 

464 # column. 

465 if "rank" in requested_columns: 

466 payload.columns_available[DatasetColumnTag(self.datasetType.name, "rank")] = sqlalchemy.sql.case( 

467 {record.key: rank for record, rank in collections}, 

468 value=collection_col, 

469 ) 

470 # Add more column definitions, starting with the data ID. 

471 for dimension_name in self.datasetType.dimensions.required.names: 

472 payload.columns_available[DimensionKeyColumnTag(dimension_name)] = payload.from_clause.columns[ 

473 dimension_name 

474 ] 

475 # We can always get the dataset_id from the tags/calibs table. 

476 if "dataset_id" in requested_columns: 

477 payload.columns_available[DatasetColumnTag(self.datasetType.name, "dataset_id")] = dataset_id_col 

478 # It's possible we now have everything we need, from just the 

479 # tags/calibs table. The things we might need to get from the static 

480 # dataset table are the run key and the ingest date. 

481 need_static_table = False 

482 if "run" in requested_columns: 

483 if len(collections) == 1 and collections[0][0].type is CollectionType.RUN: 

484 # If we are searching exactly one RUN collection, we 

485 # know that if we find the dataset in that collection, 

486 # then that's the datasets's run; we don't need to 

487 # query for it. 

488 payload.columns_available[ 

489 DatasetColumnTag(self.datasetType.name, "run") 

490 ] = sqlalchemy.sql.literal(collections[0][0].key) 

491 else: 

492 payload.columns_available[ 

493 DatasetColumnTag(self.datasetType.name, "run") 

494 ] = self._static.dataset.columns[self._runKeyColumn] 

495 need_static_table = True 

496 # Ingest date can only come from the static table. 

497 if "ingest_date" in requested_columns: 

498 need_static_table = True 

499 payload.columns_available[ 

500 DatasetColumnTag(self.datasetType.name, "ingest_date") 

501 ] = self._static.dataset.columns.ingest_date 

502 # If we need the static table, join it in via dataset_id and 

503 # dataset_type_id 

504 if need_static_table: 

505 payload.from_clause = payload.from_clause.join( 

506 self._static.dataset, onclause=(dataset_id_col == self._static.dataset.columns.id) 

507 ) 

508 # Also constrain dataset_type_id in static table in case that helps 

509 # generate a better plan. 

510 # We could also include this in the JOIN ON clause, but my guess is 

511 # that that's a good idea IFF it's in the foreign key, and right 

512 # now it isn't. 

513 payload.where.append(self._static.dataset.columns.dataset_type_id == self._dataset_type_id) 

514 leaf = context.sql_engine.make_leaf( 

515 payload.columns_available.keys(), 

516 payload=payload, 

517 name=self.datasetType.name, 

518 parameters={record.name: rank for record, rank in collections}, 

519 ) 

520 return leaf 

521 

522 def getDataId(self, id: DatasetId) -> DataCoordinate: 

523 """Return DataId for a dataset. 

524 

525 Parameters 

526 ---------- 

527 id : `DatasetId` 

528 Unique dataset identifier. 

529 

530 Returns 

531 ------- 

532 dataId : `DataCoordinate` 

533 DataId for the dataset. 

534 """ 

535 # This query could return multiple rows (one for each tagged collection 

536 # the dataset is in, plus one for its run collection), and we don't 

537 # care which of those we get. 

538 sql = ( 

539 self._tags.select() 

540 .where( 

541 sqlalchemy.sql.and_( 

542 self._tags.columns.dataset_id == id, 

543 self._tags.columns.dataset_type_id == self._dataset_type_id, 

544 ) 

545 ) 

546 .limit(1) 

547 ) 

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

549 row = sql_result.mappings().fetchone() 

550 assert row is not None, "Should be guaranteed by caller and foreign key constraints." 

551 return DataCoordinate.standardize( 

552 {dimension.name: row[dimension.name] for dimension in self.datasetType.dimensions.required}, 

553 graph=self.datasetType.dimensions, 

554 ) 

555 

556 

557class ByDimensionsDatasetRecordStorageUUID(ByDimensionsDatasetRecordStorage): 

558 """Implementation of ByDimensionsDatasetRecordStorage which uses UUID for 

559 dataset IDs. 

560 """ 

561 

562 idMaker = DatasetIdFactory() 

563 """Factory for dataset IDs. In the future this factory may be shared with 

564 other classes (e.g. Registry).""" 

565 

566 def insert( 

567 self, 

568 run: RunRecord, 

569 dataIds: Iterable[DataCoordinate], 

570 idMode: DatasetIdGenEnum = DatasetIdGenEnum.UNIQUE, 

571 ) -> Iterator[DatasetRef]: 

572 # Docstring inherited from DatasetRecordStorage. 

573 

574 # Current timestamp, type depends on schema version. Use microsecond 

575 # precision for astropy time to keep things consistent with 

576 # TIMESTAMP(6) SQL type. 

577 timestamp: datetime | astropy.time.Time 

578 if self._use_astropy: 

579 # Astropy `now()` precision should be the same as `utcnow()` which 

580 # should mean microsecond. 

581 timestamp = astropy.time.Time.now() 

582 else: 

583 timestamp = datetime.utcnow() 

584 

585 # Iterate over data IDs, transforming a possibly-single-pass iterable 

586 # into a list. 

587 dataIdList = [] 

588 rows = [] 

589 summary = CollectionSummary() 

590 for dataId in summary.add_data_ids_generator(self.datasetType, dataIds): 

591 dataIdList.append(dataId) 

592 rows.append( 

593 { 

594 "id": self.idMaker.makeDatasetId(run.name, self.datasetType, dataId, idMode), 

595 "dataset_type_id": self._dataset_type_id, 

596 self._runKeyColumn: run.key, 

597 "ingest_date": timestamp, 

598 } 

599 ) 

600 

601 with self._db.transaction(): 

602 # Insert into the static dataset table. 

603 self._db.insert(self._static.dataset, *rows) 

604 # Update the summary tables for this collection in case this is the 

605 # first time this dataset type or these governor values will be 

606 # inserted there. 

607 self._summaries.update(run, [self._dataset_type_id], summary) 

608 # Combine the generated dataset_id values and data ID fields to 

609 # form rows to be inserted into the tags table. 

610 protoTagsRow = { 

611 "dataset_type_id": self._dataset_type_id, 

612 self._collections.getCollectionForeignKeyName(): run.key, 

613 } 

614 tagsRows = [ 

615 dict(protoTagsRow, dataset_id=row["id"], **dataId.byName()) 

616 for dataId, row in zip(dataIdList, rows) 

617 ] 

618 # Insert those rows into the tags table. 

619 self._db.insert(self._tags, *tagsRows) 

620 

621 for dataId, row in zip(dataIdList, rows): 

622 yield DatasetRef( 

623 datasetType=self.datasetType, 

624 dataId=dataId, 

625 id=row["id"], 

626 run=run.name, 

627 ) 

628 

629 def import_( 

630 self, 

631 run: RunRecord, 

632 datasets: Iterable[DatasetRef], 

633 idGenerationMode: DatasetIdGenEnum = DatasetIdGenEnum.UNIQUE, 

634 reuseIds: bool = False, 

635 ) -> Iterator[DatasetRef]: 

636 # Docstring inherited from DatasetRecordStorage. 

637 

638 # Current timestamp, type depends on schema version. 

639 if self._use_astropy: 

640 # Astropy `now()` precision should be the same as `utcnow()` which 

641 # should mean microsecond. 

642 timestamp = sqlalchemy.sql.literal(astropy.time.Time.now(), type_=ddl.AstropyTimeNsecTai) 

643 else: 

644 timestamp = sqlalchemy.sql.literal(datetime.utcnow()) 

645 

646 # Iterate over data IDs, transforming a possibly-single-pass iterable 

647 # into a list. 

648 dataIds = {} 

649 summary = CollectionSummary() 

650 for dataset in summary.add_datasets_generator(datasets): 

651 # Ignore unknown ID types, normally all IDs have the same type but 

652 # this code supports mixed types or missing IDs. 

653 datasetId = dataset.id if isinstance(dataset.id, uuid.UUID) else None 

654 if datasetId is None: 

655 datasetId = self.idMaker.makeDatasetId( 

656 run.name, self.datasetType, dataset.dataId, idGenerationMode 

657 ) 

658 dataIds[datasetId] = dataset.dataId 

659 

660 # We'll insert all new rows into a temporary table 

661 tableSpec = makeTagTableSpec(self.datasetType, type(self._collections), ddl.GUID, constraints=False) 

662 collFkName = self._collections.getCollectionForeignKeyName() 

663 protoTagsRow = { 

664 "dataset_type_id": self._dataset_type_id, 

665 collFkName: run.key, 

666 } 

667 tmpRows = [ 

668 dict(protoTagsRow, dataset_id=dataset_id, **dataId.byName()) 

669 for dataset_id, dataId in dataIds.items() 

670 ] 

671 with self._db.transaction(for_temp_tables=True): 

672 with self._db.temporary_table(tableSpec) as tmp_tags: 

673 # store all incoming data in a temporary table 

674 self._db.insert(tmp_tags, *tmpRows) 

675 

676 # There are some checks that we want to make for consistency 

677 # of the new datasets with existing ones. 

678 self._validateImport(tmp_tags, run) 

679 

680 # Before we merge temporary table into dataset/tags we need to 

681 # drop datasets which are already there (and do not conflict). 

682 self._db.deleteWhere( 

683 tmp_tags, 

684 tmp_tags.columns.dataset_id.in_(sqlalchemy.sql.select(self._static.dataset.columns.id)), 

685 ) 

686 

687 # Copy it into dataset table, need to re-label some columns. 

688 self._db.insert( 

689 self._static.dataset, 

690 select=sqlalchemy.sql.select( 

691 tmp_tags.columns.dataset_id.label("id"), 

692 tmp_tags.columns.dataset_type_id, 

693 tmp_tags.columns[collFkName].label(self._runKeyColumn), 

694 timestamp.label("ingest_date"), 

695 ), 

696 ) 

697 

698 # Update the summary tables for this collection in case this 

699 # is the first time this dataset type or these governor values 

700 # will be inserted there. 

701 self._summaries.update(run, [self._dataset_type_id], summary) 

702 

703 # Copy it into tags table. 

704 self._db.insert(self._tags, select=tmp_tags.select()) 

705 

706 # Return refs in the same order as in the input list. 

707 for dataset_id, dataId in dataIds.items(): 

708 yield DatasetRef( 

709 datasetType=self.datasetType, 

710 id=dataset_id, 

711 dataId=dataId, 

712 run=run.name, 

713 ) 

714 

715 def _validateImport(self, tmp_tags: sqlalchemy.schema.Table, run: RunRecord) -> None: 

716 """Validate imported refs against existing datasets. 

717 

718 Parameters 

719 ---------- 

720 tmp_tags : `sqlalchemy.schema.Table` 

721 Temporary table with new datasets and the same schema as tags 

722 table. 

723 run : `RunRecord` 

724 The record object describing the `~CollectionType.RUN` collection. 

725 

726 Raises 

727 ------ 

728 ConflictingDefinitionError 

729 Raise if new datasets conflict with existing ones. 

730 """ 

731 dataset = self._static.dataset 

732 tags = self._tags 

733 collFkName = self._collections.getCollectionForeignKeyName() 

734 

735 # Check that existing datasets have the same dataset type and 

736 # run. 

737 query = ( 

738 sqlalchemy.sql.select( 

739 dataset.columns.id.label("dataset_id"), 

740 dataset.columns.dataset_type_id.label("dataset_type_id"), 

741 tmp_tags.columns.dataset_type_id.label("new dataset_type_id"), 

742 dataset.columns[self._runKeyColumn].label("run"), 

743 tmp_tags.columns[collFkName].label("new run"), 

744 ) 

745 .select_from(dataset.join(tmp_tags, dataset.columns.id == tmp_tags.columns.dataset_id)) 

746 .where( 

747 sqlalchemy.sql.or_( 

748 dataset.columns.dataset_type_id != tmp_tags.columns.dataset_type_id, 

749 dataset.columns[self._runKeyColumn] != tmp_tags.columns[collFkName], 

750 ) 

751 ) 

752 .limit(1) 

753 ) 

754 with self._db.query(query) as result: 

755 if (row := result.first()) is not None: 

756 # Only include the first one in the exception message 

757 raise ConflictingDefinitionError( 

758 f"Existing dataset type or run do not match new dataset: {row._asdict()}" 

759 ) 

760 

761 # Check that matching dataset in tags table has the same DataId. 

762 query = ( 

763 sqlalchemy.sql.select( 

764 tags.columns.dataset_id, 

765 tags.columns.dataset_type_id.label("type_id"), 

766 tmp_tags.columns.dataset_type_id.label("new type_id"), 

767 *[tags.columns[dim] for dim in self.datasetType.dimensions.required.names], 

768 *[ 

769 tmp_tags.columns[dim].label(f"new {dim}") 

770 for dim in self.datasetType.dimensions.required.names 

771 ], 

772 ) 

773 .select_from(tags.join(tmp_tags, tags.columns.dataset_id == tmp_tags.columns.dataset_id)) 

774 .where( 

775 sqlalchemy.sql.or_( 

776 tags.columns.dataset_type_id != tmp_tags.columns.dataset_type_id, 

777 *[ 

778 tags.columns[dim] != tmp_tags.columns[dim] 

779 for dim in self.datasetType.dimensions.required.names 

780 ], 

781 ) 

782 ) 

783 .limit(1) 

784 ) 

785 

786 with self._db.query(query) as result: 

787 if (row := result.first()) is not None: 

788 # Only include the first one in the exception message 

789 raise ConflictingDefinitionError( 

790 f"Existing dataset type or dataId do not match new dataset: {row._asdict()}" 

791 ) 

792 

793 # Check that matching run+dataId have the same dataset ID. 

794 query = ( 

795 sqlalchemy.sql.select( 

796 tags.columns.dataset_type_id.label("dataset_type_id"), 

797 *[tags.columns[dim] for dim in self.datasetType.dimensions.required.names], 

798 tags.columns.dataset_id, 

799 tmp_tags.columns.dataset_id.label("new dataset_id"), 

800 tags.columns[collFkName], 

801 tmp_tags.columns[collFkName].label(f"new {collFkName}"), 

802 ) 

803 .select_from( 

804 tags.join( 

805 tmp_tags, 

806 sqlalchemy.sql.and_( 

807 tags.columns.dataset_type_id == tmp_tags.columns.dataset_type_id, 

808 tags.columns[collFkName] == tmp_tags.columns[collFkName], 

809 *[ 

810 tags.columns[dim] == tmp_tags.columns[dim] 

811 for dim in self.datasetType.dimensions.required.names 

812 ], 

813 ), 

814 ) 

815 ) 

816 .where(tags.columns.dataset_id != tmp_tags.columns.dataset_id) 

817 .limit(1) 

818 ) 

819 with self._db.query(query) as result: 

820 if (row := result.first()) is not None: 

821 # only include the first one in the exception message 

822 raise ConflictingDefinitionError( 

823 f"Existing dataset type and dataId does not match new dataset: {row._asdict()}" 

824 )