Coverage for python/lsst/daf/butler/registry/attributes.py: 32%
52 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 02:10 -0700
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 02:10 -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 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
23"""The default concrete implementation of the class that manages
24attributes for `Registry`.
25"""
27__all__ = ["DefaultButlerAttributeManager"]
29from typing import ClassVar, Iterable, Optional, Tuple
31import sqlalchemy
33from ..core.ddl import FieldSpec, TableSpec
34from .interfaces import (
35 ButlerAttributeExistsError,
36 ButlerAttributeManager,
37 Database,
38 StaticTablesContext,
39 VersionTuple,
40)
42# Schema version 1.0.1 signifies that we do not write schema digests. Writing
43# is done by the `versions` module, but table is controlled by this manager.
44_VERSION = VersionTuple(1, 0, 1)
47class DefaultButlerAttributeManager(ButlerAttributeManager):
48 """An implementation of `ButlerAttributeManager` that stores attributes
49 in a database table.
51 Parameters
52 ----------
53 db : `Database`
54 Database engine interface for the namespace in which this table lives.
55 table : `sqlalchemy.schema.Table`
56 SQLAlchemy representation of the table that stores attributes.
57 """
59 def __init__(
60 self,
61 db: Database,
62 table: sqlalchemy.schema.Table,
63 registry_schema_version: VersionTuple | None = None,
64 ):
65 super().__init__(registry_schema_version=registry_schema_version)
66 self._db = db
67 self._table = table
69 _TABLE_NAME: ClassVar[str] = "butler_attributes"
71 _TABLE_SPEC: ClassVar[TableSpec] = TableSpec(
72 fields=[
73 FieldSpec("name", dtype=sqlalchemy.String, length=1024, primaryKey=True),
74 FieldSpec("value", dtype=sqlalchemy.String, length=65535, nullable=False),
75 ],
76 )
78 @classmethod
79 def initialize(
80 cls, db: Database, context: StaticTablesContext, registry_schema_version: VersionTuple | None = None
81 ) -> ButlerAttributeManager:
82 # Docstring inherited from ButlerAttributeManager.
83 table = context.addTable(cls._TABLE_NAME, cls._TABLE_SPEC)
84 return cls(db=db, table=table, registry_schema_version=registry_schema_version)
86 def get(self, name: str, default: Optional[str] = None) -> Optional[str]:
87 # Docstring inherited from ButlerAttributeManager.
88 sql = sqlalchemy.sql.select(self._table.columns.value).where(self._table.columns.name == name)
89 with self._db.query(sql) as sql_result:
90 row = sql_result.fetchone()
91 if row is not None:
92 return row[0]
93 return default
95 def set(self, name: str, value: str, *, force: bool = False) -> None:
96 # Docstring inherited from ButlerAttributeManager.
97 if not name or not value:
98 raise ValueError("name and value cannot be empty")
99 if force:
100 self._db.replace(
101 self._table,
102 {
103 "name": name,
104 "value": value,
105 },
106 )
107 else:
108 try:
109 self._db.insert(
110 self._table,
111 {
112 "name": name,
113 "value": value,
114 },
115 )
116 except sqlalchemy.exc.IntegrityError as exc:
117 raise ButlerAttributeExistsError(f"attribute {name} already exists") from exc
119 def delete(self, name: str) -> bool:
120 # Docstring inherited from ButlerAttributeManager.
121 numRows = self._db.delete(self._table, ["name"], {"name": name})
122 return numRows > 0
124 def items(self) -> Iterable[Tuple[str, str]]:
125 # Docstring inherited from ButlerAttributeManager.
126 sql = sqlalchemy.sql.select(
127 self._table.columns.name,
128 self._table.columns.value,
129 )
130 with self._db.query(sql) as sql_result:
131 sql_rows = sql_result.fetchall()
132 for row in sql_rows:
133 yield row[0], row[1]
135 def empty(self) -> bool:
136 # Docstring inherited from ButlerAttributeManager.
137 sql = sqlalchemy.sql.select(sqlalchemy.sql.func.count()).select_from(self._table)
138 with self._db.query(sql) as sql_result:
139 count = sql_result.scalar()
140 return count == 0
142 @classmethod
143 def currentVersions(cls) -> list[VersionTuple]:
144 # Docstring inherited from VersionedExtension.
145 return [_VERSION]