Coverage for python/lsst/daf/butler/registry/opaque.py : 98%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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"""The default concrete implementations of the classes that manage
23opaque tables for `Registry`.
24"""
26__all__ = ["ByNameOpaqueTableStorage", "ByNameOpaqueTableStorageManager"]
28from typing import (
29 Any,
30 ClassVar,
31 Dict,
32 Iterator,
33 Optional,
34)
36import sqlalchemy
38from ..core.ddl import TableSpec, FieldSpec
39from .interfaces import (
40 Database,
41 OpaqueTableStorageManager,
42 OpaqueTableStorage,
43 StaticTablesContext,
44 VersionTuple
45)
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 """
70 def __init__(self, *, db: Database, name: str, table: sqlalchemy.schema.Table):
71 super().__init__(name=name)
72 self._db = db
73 self._table = table
75 def insert(self, *data: dict) -> None:
76 # Docstring inherited from OpaqueTableStorage.
77 self._db.insert(self._table, *data)
79 def fetch(self, **where: Any) -> Iterator[dict]:
80 # Docstring inherited from OpaqueTableStorage.
81 sql = self._table.select().where(
82 sqlalchemy.sql.and_(*[self._table.columns[k] == v for k, v in where.items()])
83 )
84 for row in self._db.query(sql):
85 yield dict(row)
87 def delete(self, **where: Any) -> None:
88 # Docstring inherited from OpaqueTableStorage.
89 self._db.delete(self._table, where.keys(), where)
92class ByNameOpaqueTableStorageManager(OpaqueTableStorageManager):
93 """An implementation of `OpaqueTableStorageManager` that simply creates a
94 true table for each different named opaque logical table.
96 Instances of this class should generally be constructed via the
97 `initialize` class method instead of invoking ``__init__`` directly.
99 Parameters
100 ----------
101 db : `Database`
102 Database engine interface for the namespace in which this table lives.
103 metaTable : `sqlalchemy.schema.Table`
104 SQLAlchemy representation of the table that records which opaque
105 logical tables exist.
106 """
107 def __init__(self, db: Database, metaTable: sqlalchemy.schema.Table):
108 self._db = db
109 self._metaTable = metaTable
110 self._storage: Dict[str, OpaqueTableStorage] = {}
112 _META_TABLE_NAME: ClassVar[str] = "opaque_meta"
114 _META_TABLE_SPEC: ClassVar[TableSpec] = TableSpec(
115 fields=[
116 FieldSpec("table_name", dtype=sqlalchemy.String, length=128, primaryKey=True),
117 ],
118 )
120 @classmethod
121 def initialize(cls, db: Database, context: StaticTablesContext) -> OpaqueTableStorageManager:
122 # Docstring inherited from OpaqueTableStorageManager.
123 metaTable = context.addTable(cls._META_TABLE_NAME, cls._META_TABLE_SPEC)
124 return cls(db=db, metaTable=metaTable)
126 def get(self, name: str) -> Optional[OpaqueTableStorage]:
127 # Docstring inherited from OpaqueTableStorageManager.
128 return self._storage.get(name)
130 def register(self, name: str, spec: TableSpec) -> OpaqueTableStorage:
131 # Docstring inherited from OpaqueTableStorageManager.
132 result = self._storage.get(name)
133 if result is None: 133 ↛ 143line 133 didn't jump to line 143, because the condition on line 133 was never false
134 # Create the table itself. If it already exists but wasn't in
135 # the dict because it was added by another client since this one
136 # was initialized, that's fine.
137 table = self._db.ensureTableExists(name, spec)
138 # Add a row to the meta table so we can find this table in the
139 # future. Also okay if that already exists, so we use sync.
140 self._db.sync(self._metaTable, keys={"table_name": name})
141 result = ByNameOpaqueTableStorage(name=name, table=table, db=self._db)
142 self._storage[name] = result
143 return result
145 @classmethod
146 def currentVersion(cls) -> Optional[VersionTuple]:
147 # Docstring inherited from VersionedExtension.
148 return _VERSION
150 def schemaDigest(self) -> Optional[str]:
151 # Docstring inherited from VersionedExtension.
152 return self._defaultSchemaDigest([self._metaTable], self._db.dialect)