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

53 statements  

« prev     ^ index     » next       coverage.py v7.4.0, created at 2024-01-16 10:44 +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 software is dual licensed under the GNU General Public License and also 

10# under a 3-clause BSD license. Recipients may choose which of these licenses 

11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt, 

12# respectively. If you choose the GPL option then the following text applies 

13# (but note that there is still no warranty even if you opt for BSD instead): 

14# 

15# This program is free software: you can redistribute it and/or modify 

16# it under the terms of the GNU General Public License as published by 

17# the Free Software Foundation, either version 3 of the License, or 

18# (at your option) any later version. 

19# 

20# This program is distributed in the hope that it will be useful, 

21# but WITHOUT ANY WARRANTY; without even the implied warranty of 

22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

23# GNU General Public License for more details. 

24# 

25# You should have received a copy of the GNU General Public License 

26# along with this program. If not, see <http://www.gnu.org/licenses/>. 

27 

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

29attributes for `Registry`. 

30""" 

31 

32from __future__ import annotations 

33 

34__all__ = ["DefaultButlerAttributeManager"] 

35 

36from collections.abc import Iterable 

37from typing import ClassVar 

38 

39import sqlalchemy 

40 

41from ..ddl import FieldSpec, TableSpec 

42from .interfaces import ( 

43 ButlerAttributeExistsError, 

44 ButlerAttributeManager, 

45 Database, 

46 StaticTablesContext, 

47 VersionTuple, 

48) 

49 

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

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

52_VERSION = VersionTuple(1, 0, 1) 

53 

54 

55class DefaultButlerAttributeManager(ButlerAttributeManager): 

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

57 in a database table. 

58 

59 Parameters 

60 ---------- 

61 db : `Database` 

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

63 table : `sqlalchemy.schema.Table` 

64 SQLAlchemy representation of the table that stores attributes. 

65 registry_schema_version : `VersionTuple` or `None`, optional 

66 The version of the registry schema. 

67 """ 

68 

69 def __init__( 

70 self, 

71 db: Database, 

72 table: sqlalchemy.schema.Table, 

73 registry_schema_version: VersionTuple | None = None, 

74 ): 

75 super().__init__(registry_schema_version=registry_schema_version) 

76 self._db = db 

77 self._table = table 

78 

79 _TABLE_NAME: ClassVar[str] = "butler_attributes" 

80 

81 _TABLE_SPEC: ClassVar[TableSpec] = TableSpec( 

82 fields=[ 

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

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

85 ], 

86 ) 

87 

88 @classmethod 

89 def initialize( 

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

91 ) -> ButlerAttributeManager: 

92 # Docstring inherited from ButlerAttributeManager. 

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

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

95 

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

97 # Docstring inherited from ButlerAttributeManager. 

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

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

100 row = sql_result.fetchone() 

101 if row is not None: 

102 return row[0] 

103 return default 

104 

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

106 # Docstring inherited from ButlerAttributeManager. 

107 if not name or not value: 

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

109 if force: 

110 self._db.replace( 

111 self._table, 

112 { 

113 "name": name, 

114 "value": value, 

115 }, 

116 ) 

117 else: 

118 try: 

119 self._db.insert( 

120 self._table, 

121 { 

122 "name": name, 

123 "value": value, 

124 }, 

125 ) 

126 except sqlalchemy.exc.IntegrityError as exc: 

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

128 

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

130 # Docstring inherited from ButlerAttributeManager. 

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

132 return numRows > 0 

133 

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

135 # Docstring inherited from ButlerAttributeManager. 

136 sql = sqlalchemy.sql.select( 

137 self._table.columns.name, 

138 self._table.columns.value, 

139 ) 

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

141 sql_rows = sql_result.fetchall() 

142 for row in sql_rows: 

143 yield row[0], row[1] 

144 

145 def empty(self) -> bool: 

146 # Docstring inherited from ButlerAttributeManager. 

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

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

149 count = sql_result.scalar() 

150 return count == 0 

151 

152 @classmethod 

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

154 # Docstring inherited from VersionedExtension. 

155 return [_VERSION]