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

53 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-28 10:10 +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/>. 

21from __future__ import annotations 

22 

23"""The default concrete implementation of the class that manages 

24attributes for `Registry`. 

25""" 

26 

27__all__ = ["DefaultButlerAttributeManager"] 

28 

29from collections.abc import Iterable 

30from typing import ClassVar 

31 

32import sqlalchemy 

33 

34from ..core.ddl import FieldSpec, TableSpec 

35from .interfaces import ( 

36 ButlerAttributeExistsError, 

37 ButlerAttributeManager, 

38 Database, 

39 StaticTablesContext, 

40 VersionTuple, 

41) 

42 

43# Schema version 1.0.1 signifies that we do not write schema digests. Writing 

44# is done by the `versions` module, but table is controlled by this manager. 

45_VERSION = VersionTuple(1, 0, 1) 

46 

47 

48class DefaultButlerAttributeManager(ButlerAttributeManager): 

49 """An implementation of `ButlerAttributeManager` that stores attributes 

50 in a database table. 

51 

52 Parameters 

53 ---------- 

54 db : `Database` 

55 Database engine interface for the namespace in which this table lives. 

56 table : `sqlalchemy.schema.Table` 

57 SQLAlchemy representation of the table that stores attributes. 

58 """ 

59 

60 def __init__( 

61 self, 

62 db: Database, 

63 table: sqlalchemy.schema.Table, 

64 registry_schema_version: VersionTuple | None = None, 

65 ): 

66 super().__init__(registry_schema_version=registry_schema_version) 

67 self._db = db 

68 self._table = table 

69 

70 _TABLE_NAME: ClassVar[str] = "butler_attributes" 

71 

72 _TABLE_SPEC: ClassVar[TableSpec] = TableSpec( 

73 fields=[ 

74 FieldSpec("name", dtype=sqlalchemy.String, length=1024, primaryKey=True), 

75 FieldSpec("value", dtype=sqlalchemy.String, length=65535, nullable=False), 

76 ], 

77 ) 

78 

79 @classmethod 

80 def initialize( 

81 cls, db: Database, context: StaticTablesContext, registry_schema_version: VersionTuple | None = None 

82 ) -> ButlerAttributeManager: 

83 # Docstring inherited from ButlerAttributeManager. 

84 table = context.addTable(cls._TABLE_NAME, cls._TABLE_SPEC) 

85 return cls(db=db, table=table, registry_schema_version=registry_schema_version) 

86 

87 def get(self, name: str, default: str | None = None) -> str | None: 

88 # Docstring inherited from ButlerAttributeManager. 

89 sql = sqlalchemy.sql.select(self._table.columns.value).where(self._table.columns.name == name) 

90 with self._db.query(sql) as sql_result: 

91 row = sql_result.fetchone() 

92 if row is not None: 

93 return row[0] 

94 return default 

95 

96 def set(self, name: str, value: str, *, force: bool = False) -> None: 

97 # Docstring inherited from ButlerAttributeManager. 

98 if not name or not value: 

99 raise ValueError("name and value cannot be empty") 

100 if force: 

101 self._db.replace( 

102 self._table, 

103 { 

104 "name": name, 

105 "value": value, 

106 }, 

107 ) 

108 else: 

109 try: 

110 self._db.insert( 

111 self._table, 

112 { 

113 "name": name, 

114 "value": value, 

115 }, 

116 ) 

117 except sqlalchemy.exc.IntegrityError as exc: 

118 raise ButlerAttributeExistsError(f"attribute {name} already exists") from exc 

119 

120 def delete(self, name: str) -> bool: 

121 # Docstring inherited from ButlerAttributeManager. 

122 numRows = self._db.delete(self._table, ["name"], {"name": name}) 

123 return numRows > 0 

124 

125 def items(self) -> Iterable[tuple[str, str]]: 

126 # Docstring inherited from ButlerAttributeManager. 

127 sql = sqlalchemy.sql.select( 

128 self._table.columns.name, 

129 self._table.columns.value, 

130 ) 

131 with self._db.query(sql) as sql_result: 

132 sql_rows = sql_result.fetchall() 

133 for row in sql_rows: 

134 yield row[0], row[1] 

135 

136 def empty(self) -> bool: 

137 # Docstring inherited from ButlerAttributeManager. 

138 sql = sqlalchemy.sql.select(sqlalchemy.sql.func.count()).select_from(self._table) 

139 with self._db.query(sql) as sql_result: 

140 count = sql_result.scalar() 

141 return count == 0 

142 

143 @classmethod 

144 def currentVersions(cls) -> list[VersionTuple]: 

145 # Docstring inherited from VersionedExtension. 

146 return [_VERSION]