Coverage for python/lsst/daf/butler/registry/collections/nameKey.py: 99%
117 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-10-09 03:22 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-10-09 03:22 -0700
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__ = ["NameKeyCollectionManager"]
31import logging
32from collections.abc import Iterable, Mapping
33from typing import TYPE_CHECKING, Any
35import sqlalchemy
37from ... import ddl
38from ..._collection_type import CollectionType
39from ...column_spec import COLLECTION_NAME_MAX_LENGTH
40from ...timespan_database_representation import TimespanDatabaseRepresentation
41from ..interfaces import ChainedCollectionRecord, CollectionRecord, RunRecord, VersionTuple
42from ._base import (
43 CollectionTablesTuple,
44 DefaultCollectionManager,
45 makeCollectionChainTableSpec,
46 makeRunTableSpec,
47)
49if TYPE_CHECKING:
50 from .._caching_context import CachingContext
51 from ..interfaces import Database, StaticTablesContext
54_KEY_FIELD_SPEC = ddl.FieldSpec(
55 "name", dtype=sqlalchemy.String, length=COLLECTION_NAME_MAX_LENGTH, primaryKey=True
56)
59# This has to be updated on every schema change
60_VERSION = VersionTuple(2, 0, 0)
63_LOG = logging.getLogger(__name__)
66def _makeTableSpecs(
67 TimespanReprClass: type[TimespanDatabaseRepresentation],
68) -> CollectionTablesTuple[ddl.TableSpec]:
69 return CollectionTablesTuple(
70 collection=ddl.TableSpec(
71 fields=[
72 _KEY_FIELD_SPEC,
73 ddl.FieldSpec("type", dtype=sqlalchemy.SmallInteger, nullable=False),
74 ddl.FieldSpec("doc", dtype=sqlalchemy.Text, nullable=True),
75 ],
76 ),
77 run=makeRunTableSpec("name", sqlalchemy.String, TimespanReprClass),
78 collection_chain=makeCollectionChainTableSpec("name", sqlalchemy.String),
79 )
82class NameKeyCollectionManager(DefaultCollectionManager[str]):
83 """A `CollectionManager` implementation that uses collection names for
84 primary/foreign keys and aggressively loads all collection/run records in
85 the database into memory.
87 Most of the logic, including caching policy, is implemented in the base
88 class, this class only adds customizations specific to this particular
89 table schema.
90 """
92 @classmethod
93 def initialize(
94 cls,
95 db: Database,
96 context: StaticTablesContext,
97 *,
98 caching_context: CachingContext,
99 registry_schema_version: VersionTuple | None = None,
100 ) -> NameKeyCollectionManager:
101 # Docstring inherited from CollectionManager.
102 return cls(
103 db,
104 tables=context.addTableTuple(_makeTableSpecs(db.getTimespanRepresentation())), # type: ignore
105 collectionIdName="name",
106 caching_context=caching_context,
107 registry_schema_version=registry_schema_version,
108 )
110 def clone(self, db: Database, caching_context: CachingContext) -> NameKeyCollectionManager:
111 return NameKeyCollectionManager(
112 db,
113 tables=self._tables,
114 collectionIdName=self._collectionIdName,
115 caching_context=caching_context,
116 registry_schema_version=self._registry_schema_version,
117 )
119 @classmethod
120 def getCollectionForeignKeyName(cls, prefix: str = "collection") -> str:
121 # Docstring inherited from CollectionManager.
122 return f"{prefix}_name"
124 @classmethod
125 def getRunForeignKeyName(cls, prefix: str = "run") -> str:
126 # Docstring inherited from CollectionManager.
127 return f"{prefix}_name"
129 @classmethod
130 def addCollectionForeignKey(
131 cls,
132 tableSpec: ddl.TableSpec,
133 *,
134 prefix: str = "collection",
135 onDelete: str | None = None,
136 constraint: bool = True,
137 **kwargs: Any,
138 ) -> ddl.FieldSpec:
139 # Docstring inherited from CollectionManager.
140 original = _KEY_FIELD_SPEC
141 copy = ddl.FieldSpec(
142 cls.getCollectionForeignKeyName(prefix), dtype=original.dtype, length=original.length, **kwargs
143 )
144 tableSpec.fields.add(copy)
145 if constraint:
146 tableSpec.foreignKeys.append(
147 ddl.ForeignKeySpec(
148 "collection", source=(copy.name,), target=(original.name,), onDelete=onDelete
149 )
150 )
151 return copy
153 @classmethod
154 def addRunForeignKey(
155 cls,
156 tableSpec: ddl.TableSpec,
157 *,
158 prefix: str = "run",
159 onDelete: str | None = None,
160 constraint: bool = True,
161 **kwargs: Any,
162 ) -> ddl.FieldSpec:
163 # Docstring inherited from CollectionManager.
164 original = _KEY_FIELD_SPEC
165 copy = ddl.FieldSpec(
166 cls.getRunForeignKeyName(prefix), dtype=original.dtype, length=original.length, **kwargs
167 )
168 tableSpec.fields.add(copy)
169 if constraint: 169 ↛ 173line 169 didn't jump to line 173 because the condition on line 169 was always true
170 tableSpec.foreignKeys.append(
171 ddl.ForeignKeySpec("run", source=(copy.name,), target=(original.name,), onDelete=onDelete)
172 )
173 return copy
175 def getParentChains(self, key: str) -> set[str]:
176 # Docstring inherited from CollectionManager.
177 table = self._tables.collection_chain
178 sql = (
179 sqlalchemy.sql.select(table.columns["parent"])
180 .select_from(table)
181 .where(table.columns["child"] == key)
182 )
183 with self._db.query(sql) as sql_result:
184 parent_names = set(sql_result.scalars().all())
185 return parent_names
187 def lookup_name_sql(
188 self, sql_key: sqlalchemy.ColumnElement[str], sql_from_clause: sqlalchemy.FromClause
189 ) -> tuple[sqlalchemy.ColumnElement[str], sqlalchemy.FromClause]:
190 # Docstring inherited.
191 return sql_key, sql_from_clause
193 def _fetch_by_name(self, names: Iterable[str], flatten_chains: bool) -> list[CollectionRecord[str]]:
194 # Docstring inherited from base class.
195 if flatten_chains:
196 sql_rows = self._query_recursive(names, _KEY_FIELD_SPEC.dtype)
198 # There may be duplicates in the result, select unique names.
199 unique_rows = {row[self._collectionIdName]: row for row in sql_rows}
201 records, chained_ids = self._rows_to_records(unique_rows.values())
202 records += self._rows_to_chains(sql_rows, chained_ids)
204 return records
205 else:
206 return self._fetch_by_key(names)
208 def _fetch_by_key(self, collection_ids: Iterable[str] | None) -> list[CollectionRecord[str]]:
209 # Docstring inherited from base class.
210 _LOG.debug("Fetching collection records using names %s.", collection_ids)
211 sql = sqlalchemy.sql.select(*self._tables.collection.columns, *self._tables.run.columns).select_from(
212 self._tables.collection.join(self._tables.run, isouter=True)
213 )
215 # "Rename" child column to "name" as expected by _rows_to_chains()
216 chain_sql = sqlalchemy.sql.select(
217 self._tables.collection_chain.columns["parent"],
218 self._tables.collection_chain.columns["position"],
219 self._tables.collection_chain.columns["child"].label("name"),
220 )
222 records: list[CollectionRecord[str]] = []
223 # We want to keep transactions as short as possible. When we fetch
224 # everything we want to quickly fetch things into memory and finish
225 # transaction. When we fetch just few records we need to process result
226 # of the first query before we can run the second one.
227 if collection_ids is not None:
228 sql = sql.where(self._tables.collection.columns[self._collectionIdName].in_(collection_ids))
229 with self._db.transaction():
230 with self._db.query(sql) as sql_result:
231 sql_rows = sql_result.mappings().fetchall()
233 records, chained_ids = self._rows_to_records(sql_rows)
235 if chained_ids:
236 # Retrieve chained collection compositions
237 chain_sql = chain_sql.where(
238 self._tables.collection_chain.columns["parent"].in_(chained_ids)
239 )
240 with self._db.query(chain_sql) as sql_result:
241 chain_rows = sql_result.mappings().fetchall()
243 records += self._rows_to_chains(chain_rows, chained_ids)
245 else:
246 with self._db.transaction():
247 with self._db.query(sql) as sql_result:
248 sql_rows = sql_result.mappings().fetchall()
249 with self._db.query(chain_sql) as sql_result:
250 chain_rows = sql_result.mappings().fetchall()
252 records, chained_ids = self._rows_to_records(sql_rows)
253 records += self._rows_to_chains(chain_rows, chained_ids)
255 return records
257 def _rows_to_records(self, rows: Iterable[Mapping]) -> tuple[list[CollectionRecord[str]], list[str]]:
258 """Convert rows returned from collection query to a list of records
259 and a list chained collection names.
260 """
261 records: list[CollectionRecord[str]] = []
262 TimespanReprClass = self._db.getTimespanRepresentation()
263 chained_ids: list[str] = []
264 for row in rows:
265 name = row["name"]
266 type = CollectionType(row["type"])
267 record: CollectionRecord[str]
268 if type is CollectionType.RUN:
269 record = RunRecord[str](
270 key=name,
271 name=name,
272 host=row[self._tables.run.columns.host],
273 timespan=TimespanReprClass.extract(row),
274 )
275 records.append(record)
276 elif type is CollectionType.CHAINED:
277 # Need to delay chained collection construction until to
278 # fetch their children names.
279 chained_ids.append(name)
280 else:
281 record = CollectionRecord[str](key=name, name=name, type=type)
282 records.append(record)
284 return records, chained_ids
286 def _rows_to_chains(self, rows: Iterable[Mapping], chained_ids: list[str]) -> list[CollectionRecord[str]]:
287 """Convert rows returned from collection chain query to a list of
288 records.
289 """
290 chains_defs: dict[str, list[tuple[int, str]]] = {chain_id: [] for chain_id in chained_ids}
291 for row in rows:
292 if row["parent"] is not None:
293 chains_defs[row["parent"]].append((row["position"], row["name"]))
295 records: list[CollectionRecord[str]] = []
296 for name, children in chains_defs.items():
297 children_names = [child for _, child in sorted(children)]
298 record = ChainedCollectionRecord[str](
299 key=name,
300 name=name,
301 children=children_names,
302 )
303 records.append(record)
305 return records
307 def _select_pkey_by_name(self, collection_name: str) -> sqlalchemy.Select:
308 table = self._tables.collection
309 return sqlalchemy.select(table.c.name.label("key"), table.c.type).where(
310 table.c.name == collection_name
311 )
313 @classmethod
314 def currentVersions(cls) -> list[VersionTuple]:
315 # Docstring inherited from VersionedExtension.
316 return [_VERSION]