Coverage for python/lsst/daf/butler/registry/attributes.py : 100%

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 implementation of the class that manages
23attributes for `Registry`.
24"""
26__all__ = ["DefaultButlerAttributeManager"]
28from typing import (
29 ClassVar,
30 Iterable,
31 Optional,
32 Tuple,
33)
35import sqlalchemy
37from ..core.ddl import TableSpec, FieldSpec
38from .interfaces import (
39 Database,
40 ButlerAttributeExistsError,
41 ButlerAttributeManager,
42 StaticTablesContext
43)
46class DefaultButlerAttributeManager(ButlerAttributeManager):
47 """An implementation of `ButlerAttributeManager` that stores attributes
48 in a database table.
50 Parameters
51 ----------
52 db : `Database`
53 Database engine interface for the namespace in which this table lives.
54 table : `sqlalchemy.schema.Table`
55 SQLAlchemy representation of the table that stores attributes.
56 """
57 def __init__(self, db: Database, table: sqlalchemy.schema.Table):
58 self._db = db
59 self._table = table
61 _TABLE_NAME: ClassVar[str] = "butler_attributes"
63 _TABLE_SPEC: ClassVar[TableSpec] = TableSpec(
64 fields=[
65 FieldSpec("name", dtype=sqlalchemy.String, length=1024, primaryKey=True),
66 FieldSpec("value", dtype=sqlalchemy.String, length=65535, nullable=False),
67 ],
68 )
70 @classmethod
71 def initialize(cls, db: Database, context: StaticTablesContext) -> ButlerAttributeManager:
72 # Docstring inherited from ButlerAttributeManager.
73 table = context.addTable(cls._TABLE_NAME, cls._TABLE_SPEC)
74 return cls(db=db, table=table)
76 def get(self, name: str, default: Optional[str] = None) -> Optional[str]:
77 # Docstring inherited from ButlerAttributeManager.
78 sql = sqlalchemy.sql.select([self._table.columns.value]).where(
79 self._table.columns.name == name
80 )
81 row = self._db.query(sql).fetchone()
82 if row is not None:
83 return row[0]
84 return default
86 def set(self, name: str, value: str, *, force: bool = False) -> None:
87 # Docstring inherited from ButlerAttributeManager.
88 if not name or not value:
89 raise ValueError("name and value cannot be empty")
90 if force:
91 self._db.replace(self._table, {
92 "name": name,
93 "value": value,
94 })
95 else:
96 try:
97 self._db.insert(self._table, {
98 "name": name,
99 "value": value,
100 })
101 except sqlalchemy.exc.IntegrityError as exc:
102 raise ButlerAttributeExistsError(f"attribute {name} already exists") from exc
104 def delete(self, name: str) -> bool:
105 # Docstring inherited from ButlerAttributeManager.
106 numRows = self._db.delete(self._table, ["name"], {"name": name})
107 return numRows > 0
109 def items(self) -> Iterable[Tuple[str, str]]:
110 # Docstring inherited from ButlerAttributeManager.
111 sql = sqlalchemy.sql.select([
112 self._table.columns.name,
113 self._table.columns.value,
114 ])
115 for row in self._db.query(sql):
116 yield row[0], row[1]