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

53 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2023-10-27 09: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 """ 

66 

67 def __init__( 

68 self, 

69 db: Database, 

70 table: sqlalchemy.schema.Table, 

71 registry_schema_version: VersionTuple | None = None, 

72 ): 

73 super().__init__(registry_schema_version=registry_schema_version) 

74 self._db = db 

75 self._table = table 

76 

77 _TABLE_NAME: ClassVar[str] = "butler_attributes" 

78 

79 _TABLE_SPEC: ClassVar[TableSpec] = TableSpec( 

80 fields=[ 

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

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

83 ], 

84 ) 

85 

86 @classmethod 

87 def initialize( 

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

89 ) -> ButlerAttributeManager: 

90 # Docstring inherited from ButlerAttributeManager. 

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

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

93 

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

95 # Docstring inherited from ButlerAttributeManager. 

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

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

98 row = sql_result.fetchone() 

99 if row is not None: 

100 return row[0] 

101 return default 

102 

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

104 # Docstring inherited from ButlerAttributeManager. 

105 if not name or not value: 

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

107 if force: 

108 self._db.replace( 

109 self._table, 

110 { 

111 "name": name, 

112 "value": value, 

113 }, 

114 ) 

115 else: 

116 try: 

117 self._db.insert( 

118 self._table, 

119 { 

120 "name": name, 

121 "value": value, 

122 }, 

123 ) 

124 except sqlalchemy.exc.IntegrityError as exc: 

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

126 

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

128 # Docstring inherited from ButlerAttributeManager. 

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

130 return numRows > 0 

131 

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

133 # Docstring inherited from ButlerAttributeManager. 

134 sql = sqlalchemy.sql.select( 

135 self._table.columns.name, 

136 self._table.columns.value, 

137 ) 

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

139 sql_rows = sql_result.fetchall() 

140 for row in sql_rows: 

141 yield row[0], row[1] 

142 

143 def empty(self) -> bool: 

144 # Docstring inherited from ButlerAttributeManager. 

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

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

147 count = sql_result.scalar() 

148 return count == 0 

149 

150 @classmethod 

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

152 # Docstring inherited from VersionedExtension. 

153 return [_VERSION]