Coverage for python/lsst/daf/butler/registry/collections/synthIntKey.py: 99%
58 statements
« prev ^ index » next coverage.py v7.3.1, created at 2023-10-02 07:59 +0000
« prev ^ index » next coverage.py v7.3.1, created at 2023-10-02 07:59 +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 software is dual licensed under the GNU General Public License and also
10# under a 3-clause BSD license. Recipients may choose which of these licenses
11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt,
12# respectively. If you choose the GPL option then the following text applies
13# (but note that there is still no warranty even if you opt for BSD instead):
14#
15# This program is free software: you can redistribute it and/or modify
16# it under the terms of the GNU General Public License as published by
17# the Free Software Foundation, either version 3 of the License, or
18# (at your option) any later version.
19#
20# This program is distributed in the hope that it will be useful,
21# but WITHOUT ANY WARRANTY; without even the implied warranty of
22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23# GNU General Public License for more details.
24#
25# You should have received a copy of the GNU General Public License
26# along with this program. If not, see <http://www.gnu.org/licenses/>.
27from __future__ import annotations
29__all__ = ["SynthIntKeyCollectionManager"]
31from collections.abc import Iterable
32from typing import TYPE_CHECKING, Any
34import sqlalchemy
36from ...core import TimespanDatabaseRepresentation, ddl
37from ..interfaces import CollectionRecord, VersionTuple
38from ._base import (
39 CollectionTablesTuple,
40 DefaultCollectionManager,
41 makeCollectionChainTableSpec,
42 makeRunTableSpec,
43)
45if TYPE_CHECKING:
46 from ..interfaces import Database, DimensionRecordStorageManager, StaticTablesContext
49_KEY_FIELD_SPEC = ddl.FieldSpec(
50 "collection_id", dtype=sqlalchemy.BigInteger, primaryKey=True, autoincrement=True
51)
54# This has to be updated on every schema change
55_VERSION = VersionTuple(2, 0, 0)
58def _makeTableSpecs(TimespanReprClass: type[TimespanDatabaseRepresentation]) -> CollectionTablesTuple:
59 return CollectionTablesTuple(
60 collection=ddl.TableSpec(
61 fields=[
62 _KEY_FIELD_SPEC,
63 ddl.FieldSpec("name", dtype=sqlalchemy.String, length=64, nullable=False),
64 ddl.FieldSpec("type", dtype=sqlalchemy.SmallInteger, nullable=False),
65 ddl.FieldSpec("doc", dtype=sqlalchemy.Text, nullable=True),
66 ],
67 unique=[("name",)],
68 ),
69 run=makeRunTableSpec("collection_id", sqlalchemy.BigInteger, TimespanReprClass),
70 collection_chain=makeCollectionChainTableSpec("collection_id", sqlalchemy.BigInteger),
71 )
74class SynthIntKeyCollectionManager(DefaultCollectionManager):
75 """A `CollectionManager` implementation that uses synthetic primary key
76 (auto-incremented integer) for collections table.
78 Most of the logic, including caching policy, is implemented in the base
79 class, this class only adds customizations specific to this particular
80 table schema.
82 Parameters
83 ----------
84 db : `Database`
85 Interface to the underlying database engine and namespace.
86 tables : `NamedTuple`
87 Named tuple of SQLAlchemy table objects.
88 collectionIdName : `str`
89 Name of the column in collections table that identifies it (PK).
90 dimensions : `DimensionRecordStorageManager`
91 Manager object for the dimensions in this `Registry`.
92 """
94 def __init__(
95 self,
96 db: Database,
97 tables: CollectionTablesTuple,
98 collectionIdName: str,
99 dimensions: DimensionRecordStorageManager,
100 registry_schema_version: VersionTuple | None = None,
101 ):
102 super().__init__(
103 db=db,
104 tables=tables,
105 collectionIdName=collectionIdName,
106 dimensions=dimensions,
107 registry_schema_version=registry_schema_version,
108 )
109 self._nameCache: dict[str, CollectionRecord] = {} # indexed by collection name
111 @classmethod
112 def initialize(
113 cls,
114 db: Database,
115 context: StaticTablesContext,
116 *,
117 dimensions: DimensionRecordStorageManager,
118 registry_schema_version: VersionTuple | None = None,
119 ) -> SynthIntKeyCollectionManager:
120 # Docstring inherited from CollectionManager.
121 return cls(
122 db,
123 tables=context.addTableTuple(_makeTableSpecs(db.getTimespanRepresentation())), # type: ignore
124 collectionIdName="collection_id",
125 dimensions=dimensions,
126 registry_schema_version=registry_schema_version,
127 )
129 @classmethod
130 def getCollectionForeignKeyName(cls, prefix: str = "collection") -> str:
131 # Docstring inherited from CollectionManager.
132 return f"{prefix}_id"
134 @classmethod
135 def getRunForeignKeyName(cls, prefix: str = "run") -> str:
136 # Docstring inherited from CollectionManager.
137 return f"{prefix}_id"
139 @classmethod
140 def addCollectionForeignKey(
141 cls,
142 tableSpec: ddl.TableSpec,
143 *,
144 prefix: str = "collection",
145 onDelete: str | None = None,
146 constraint: bool = True,
147 **kwargs: Any,
148 ) -> ddl.FieldSpec:
149 # Docstring inherited from CollectionManager.
150 original = _KEY_FIELD_SPEC
151 copy = ddl.FieldSpec(
152 cls.getCollectionForeignKeyName(prefix), dtype=original.dtype, autoincrement=False, **kwargs
153 )
154 tableSpec.fields.add(copy)
155 if constraint:
156 tableSpec.foreignKeys.append(
157 ddl.ForeignKeySpec(
158 "collection", source=(copy.name,), target=(original.name,), onDelete=onDelete
159 )
160 )
161 return copy
163 @classmethod
164 def addRunForeignKey(
165 cls,
166 tableSpec: ddl.TableSpec,
167 *,
168 prefix: str = "run",
169 onDelete: str | None = None,
170 constraint: bool = True,
171 **kwargs: Any,
172 ) -> ddl.FieldSpec:
173 # Docstring inherited from CollectionManager.
174 original = _KEY_FIELD_SPEC
175 copy = ddl.FieldSpec(
176 cls.getRunForeignKeyName(prefix), dtype=original.dtype, autoincrement=False, **kwargs
177 )
178 tableSpec.fields.add(copy)
179 if constraint: 179 ↛ 183line 179 didn't jump to line 183, because the condition on line 179 was never false
180 tableSpec.foreignKeys.append(
181 ddl.ForeignKeySpec("run", source=(copy.name,), target=(original.name,), onDelete=onDelete)
182 )
183 return copy
185 def _setRecordCache(self, records: Iterable[CollectionRecord]) -> None:
186 """Set internal record cache to contain given records,
187 old cached records will be removed.
188 """
189 self._records = {}
190 self._nameCache = {}
191 for record in records:
192 self._records[record.key] = record
193 self._nameCache[record.name] = record
195 def _addCachedRecord(self, record: CollectionRecord) -> None:
196 """Add single record to cache."""
197 self._records[record.key] = record
198 self._nameCache[record.name] = record
200 def _removeCachedRecord(self, record: CollectionRecord) -> None:
201 """Remove single record from cache."""
202 del self._records[record.key]
203 del self._nameCache[record.name]
205 def _getByName(self, name: str) -> CollectionRecord | None:
206 # Docstring inherited from DefaultCollectionManager.
207 return self._nameCache.get(name)
209 @classmethod
210 def currentVersions(cls) -> list[VersionTuple]:
211 # Docstring inherited from VersionedExtension.
212 return [_VERSION]