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 Database, OpaqueTableStorageManager, OpaqueTableStorage, StaticTablesContext
42class ByNameOpaqueTableStorage(OpaqueTableStorage):
43 """An implementation of `OpaqueTableStorage` that simply creates a true
44 table for each different named opaque logical table.
46 A `ByNameOpaqueTableStorageManager` instance should always be used to
47 construct and manage instances of this class.
49 Parameters
50 ----------
51 db : `Database`
52 Database engine interface for the namespace in which this table lives.
53 name : `str`
54 Name of the logical table (also used as the name of the actual table).
55 table : `sqlalchemy.schema.Table`
56 SQLAlchemy representation of the table, which must have already been
57 created in the namespace managed by ``db`` (this is the responsibility
58 of `ByNameOpaqueTableStorageManager`).
59 """
60 def __init__(self, *, db: Database, name: str, table: sqlalchemy.schema.Table):
61 super().__init__(name=name)
62 self._db = db
63 self._table = table
65 def insert(self, *data: dict) -> None:
66 # Docstring inherited from OpaqueTableStorage.
67 self._db.insert(self._table, *data)
69 def fetch(self, **where: Any) -> Iterator[dict]:
70 # Docstring inherited from OpaqueTableStorage.
71 sql = self._table.select().where(
72 sqlalchemy.sql.and_(*[self._table.columns[k] == v for k, v in where.items()])
73 )
74 for row in self._db.query(sql):
75 yield dict(row)
77 def delete(self, **where: Any) -> None:
78 # Docstring inherited from OpaqueTableStorage.
79 self._db.delete(self._table, where.keys(), where)
82class ByNameOpaqueTableStorageManager(OpaqueTableStorageManager):
83 """An implementation of `OpaqueTableStorageManager` that simply creates a
84 true table for each different named opaque logical table.
86 Instances of this class should generally be constructed via the
87 `initialize` class method instead of invoking ``__init__`` directly.
89 Parameters
90 ----------
91 db : `Database`
92 Database engine interface for the namespace in which this table lives.
93 metaTable : `sqlalchemy.schema.Table`
94 SQLAlchemy representation of the table that records which opaque
95 logical tables exist.
96 """
97 def __init__(self, db: Database, metaTable: sqlalchemy.schema.Table):
98 self._db = db
99 self._metaTable = metaTable
100 self._storage: Dict[str, OpaqueTableStorage] = {}
102 _META_TABLE_NAME: ClassVar[str] = "opaque_meta"
104 _META_TABLE_SPEC: ClassVar[TableSpec] = TableSpec(
105 fields=[
106 FieldSpec("table_name", dtype=sqlalchemy.String, length=128, primaryKey=True),
107 ],
108 )
110 @classmethod
111 def initialize(cls, db: Database, context: StaticTablesContext) -> OpaqueTableStorageManager:
112 # Docstring inherited from OpaqueTableStorageManager.
113 metaTable = context.addTable(cls._META_TABLE_NAME, cls._META_TABLE_SPEC)
114 return cls(db=db, metaTable=metaTable)
116 def get(self, name: str) -> Optional[OpaqueTableStorage]:
117 # Docstring inherited from OpaqueTableStorageManager.
118 return self._storage.get(name)
120 def register(self, name: str, spec: TableSpec) -> OpaqueTableStorage:
121 # Docstring inherited from OpaqueTableStorageManager.
122 result = self._storage.get(name)
123 if result is None: 123 ↛ 133line 123 didn't jump to line 133, because the condition on line 123 was never false
124 # Create the table itself. If it already exists but wasn't in
125 # the dict because it was added by another client since this one
126 # was initialized, that's fine.
127 table = self._db.ensureTableExists(name, spec)
128 # Add a row to the meta table so we can find this table in the
129 # future. Also okay if that already exists, so we use sync.
130 self._db.sync(self._metaTable, keys={"table_name": name})
131 result = ByNameOpaqueTableStorage(name=name, table=table, db=self._db)
132 self._storage[name] = result
133 return result