Coverage for python/lsst/daf/butler/registry/opaque.py: 33%
72 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-10-25 15:14 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-10-25 15:14 +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/>.
22"""The default concrete implementations of the classes that manage
23opaque tables for `Registry`.
24"""
26from __future__ import annotations
28__all__ = ["ByNameOpaqueTableStorage", "ByNameOpaqueTableStorageManager"]
30import itertools
31from collections.abc import Iterable, Iterator
32from typing import TYPE_CHECKING, Any, ClassVar
34import sqlalchemy
36from ..core.ddl import FieldSpec, TableSpec
37from .interfaces import (
38 Database,
39 OpaqueTableStorage,
40 OpaqueTableStorageManager,
41 StaticTablesContext,
42 VersionTuple,
43)
45if TYPE_CHECKING:
46 from ..core.datastore import DatastoreTransaction
48# This has to be updated on every schema change
49_VERSION = VersionTuple(0, 2, 0)
52class ByNameOpaqueTableStorage(OpaqueTableStorage):
53 """An implementation of `OpaqueTableStorage` that simply creates a true
54 table for each different named opaque logical table.
56 A `ByNameOpaqueTableStorageManager` instance should always be used to
57 construct and manage instances of this class.
59 Parameters
60 ----------
61 db : `Database`
62 Database engine interface for the namespace in which this table lives.
63 name : `str`
64 Name of the logical table (also used as the name of the actual table).
65 table : `sqlalchemy.schema.Table`
66 SQLAlchemy representation of the table, which must have already been
67 created in the namespace managed by ``db`` (this is the responsibility
68 of `ByNameOpaqueTableStorageManager`).
69 """
71 def __init__(self, *, db: Database, name: str, table: sqlalchemy.schema.Table):
72 super().__init__(name=name)
73 self._db = db
74 self._table = table
76 def insert(self, *data: dict, transaction: DatastoreTransaction | None = None) -> None:
77 # Docstring inherited from OpaqueTableStorage.
78 # The provided transaction object can be ignored since we rely on
79 # the database itself providing any rollback functionality.
80 self._db.insert(self._table, *data)
82 def ensure(self, *data: dict, transaction: DatastoreTransaction | None = None) -> None:
83 # Docstring inherited from OpaqueTableStorage.
84 # The provided transaction object can be ignored since we rely on
85 # the database itself providing any rollback functionality.
86 self._db.ensure(self._table, *data)
88 def replace(self, *data: dict, transaction: DatastoreTransaction | None = None) -> None:
89 # Docstring inherited from OpaqueTableStorage.
90 # The provided transaction object can be ignored since we rely on
91 # the database itself providing any rollback functionality.
92 self._db.replace(self._table, *data)
94 def fetch(self, **where: Any) -> Iterator[sqlalchemy.RowMapping]:
95 # Docstring inherited from OpaqueTableStorage.
97 def _batch_in_clause(
98 column: sqlalchemy.schema.Column, values: Iterable[Any]
99 ) -> Iterator[sqlalchemy.sql.expression.ClauseElement]:
100 """Split one long IN clause into a series of shorter ones."""
101 in_limit = 1000
102 # We have to remove possible duplicates from values; and in many
103 # cases it should be helpful to order the items in the clause.
104 values = sorted(set(values))
105 for iposn in range(0, len(values), in_limit):
106 in_clause = column.in_(values[iposn : iposn + in_limit])
107 yield in_clause
109 def _batch_in_clauses(**where: Any) -> Iterator[sqlalchemy.sql.expression.ColumnElement]:
110 """Generate a sequence of WHERE clauses with a limited number of
111 items in IN clauses.
112 """
113 batches: list[Iterable[Any]] = []
114 for k, v in where.items():
115 column = self._table.columns[k]
116 if isinstance(v, list | tuple | set):
117 batches.append(_batch_in_clause(column, v))
118 else:
119 # single "batch" for a regular eq operator
120 batches.append([column == v])
122 for clauses in itertools.product(*batches):
123 yield sqlalchemy.sql.and_(*clauses)
125 sql = self._table.select()
126 if where:
127 # Split long IN clauses into shorter batches
128 batched_sql = [sql.where(clause) for clause in _batch_in_clauses(**where)]
129 else:
130 batched_sql = [sql]
131 for sql_batch in batched_sql:
132 with self._db.query(sql_batch) as sql_result:
133 sql_mappings = sql_result.mappings().fetchall()
134 yield from sql_mappings
136 def delete(self, columns: Iterable[str], *rows: dict) -> None:
137 # Docstring inherited from OpaqueTableStorage.
138 self._db.delete(self._table, columns, *rows)
141class ByNameOpaqueTableStorageManager(OpaqueTableStorageManager):
142 """An implementation of `OpaqueTableStorageManager` that simply creates a
143 true table for each different named opaque logical table.
145 Instances of this class should generally be constructed via the
146 `initialize` class method instead of invoking ``__init__`` directly.
148 Parameters
149 ----------
150 db : `Database`
151 Database engine interface for the namespace in which this table lives.
152 metaTable : `sqlalchemy.schema.Table`
153 SQLAlchemy representation of the table that records which opaque
154 logical tables exist.
155 """
157 def __init__(
158 self,
159 db: Database,
160 metaTable: sqlalchemy.schema.Table,
161 registry_schema_version: VersionTuple | None = None,
162 ):
163 super().__init__(registry_schema_version=registry_schema_version)
164 self._db = db
165 self._metaTable = metaTable
166 self._storage: dict[str, OpaqueTableStorage] = {}
168 _META_TABLE_NAME: ClassVar[str] = "opaque_meta"
170 _META_TABLE_SPEC: ClassVar[TableSpec] = TableSpec(
171 fields=[
172 FieldSpec("table_name", dtype=sqlalchemy.String, length=128, primaryKey=True),
173 ],
174 )
176 @classmethod
177 def initialize(
178 cls, db: Database, context: StaticTablesContext, registry_schema_version: VersionTuple | None = None
179 ) -> OpaqueTableStorageManager:
180 # Docstring inherited from OpaqueTableStorageManager.
181 metaTable = context.addTable(cls._META_TABLE_NAME, cls._META_TABLE_SPEC)
182 return cls(db=db, metaTable=metaTable, registry_schema_version=registry_schema_version)
184 def get(self, name: str) -> OpaqueTableStorage | None:
185 # Docstring inherited from OpaqueTableStorageManager.
186 return self._storage.get(name)
188 def register(self, name: str, spec: TableSpec) -> OpaqueTableStorage:
189 # Docstring inherited from OpaqueTableStorageManager.
190 result = self._storage.get(name)
191 if result is None:
192 # Create the table itself. If it already exists but wasn't in
193 # the dict because it was added by another client since this one
194 # was initialized, that's fine.
195 table = self._db.ensureTableExists(name, spec)
196 # Add a row to the meta table so we can find this table in the
197 # future. Also okay if that already exists, so we use sync.
198 self._db.sync(self._metaTable, keys={"table_name": name})
199 result = ByNameOpaqueTableStorage(name=name, table=table, db=self._db)
200 self._storage[name] = result
201 return result
203 @classmethod
204 def currentVersions(cls) -> list[VersionTuple]:
205 # Docstring inherited from VersionedExtension.
206 return [_VERSION]