Coverage for python/lsst/daf/butler/registry/opaque.py: 30%

70 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2023-01-26 02:04 -0800

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 implementations of the classes that manage 

24opaque tables for `Registry`. 

25""" 

26 

27__all__ = ["ByNameOpaqueTableStorage", "ByNameOpaqueTableStorageManager"] 

28 

29import itertools 

30from typing import TYPE_CHECKING, Any, ClassVar, Dict, Iterable, Iterator, List, Optional 

31 

32import sqlalchemy 

33 

34from ..core.ddl import FieldSpec, TableSpec 

35from .interfaces import ( 

36 Database, 

37 OpaqueTableStorage, 

38 OpaqueTableStorageManager, 

39 StaticTablesContext, 

40 VersionTuple, 

41) 

42 

43if TYPE_CHECKING: 43 ↛ 44line 43 didn't jump to line 44, because the condition on line 43 was never true

44 from ..core.datastore import DatastoreTransaction 

45 

46# This has to be updated on every schema change 

47_VERSION = VersionTuple(0, 2, 0) 

48 

49 

50class ByNameOpaqueTableStorage(OpaqueTableStorage): 

51 """An implementation of `OpaqueTableStorage` that simply creates a true 

52 table for each different named opaque logical table. 

53 

54 A `ByNameOpaqueTableStorageManager` instance should always be used to 

55 construct and manage instances of this class. 

56 

57 Parameters 

58 ---------- 

59 db : `Database` 

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

61 name : `str` 

62 Name of the logical table (also used as the name of the actual table). 

63 table : `sqlalchemy.schema.Table` 

64 SQLAlchemy representation of the table, which must have already been 

65 created in the namespace managed by ``db`` (this is the responsibility 

66 of `ByNameOpaqueTableStorageManager`). 

67 """ 

68 

69 def __init__(self, *, db: Database, name: str, table: sqlalchemy.schema.Table): 

70 super().__init__(name=name) 

71 self._db = db 

72 self._table = table 

73 

74 def insert(self, *data: dict, transaction: DatastoreTransaction | None = None) -> None: 

75 # Docstring inherited from OpaqueTableStorage. 

76 # The provided transaction object can be ignored since we rely on 

77 # the database itself providing any rollback functionality. 

78 self._db.insert(self._table, *data) 

79 

80 def fetch(self, **where: Any) -> Iterator[dict]: 

81 # Docstring inherited from OpaqueTableStorage. 

82 

83 def _batch_in_clause( 

84 column: sqlalchemy.schema.Column, values: Iterable[Any] 

85 ) -> Iterator[sqlalchemy.sql.expression.ClauseElement]: 

86 """Split one long IN clause into a series of shorter ones.""" 

87 in_limit = 1000 

88 # We have to remove possible duplicates from values; and in many 

89 # cases it should be helpful to order the items in the clause. 

90 values = sorted(set(values)) 

91 for iposn in range(0, len(values), in_limit): 

92 in_clause = column.in_(values[iposn : iposn + in_limit]) 

93 yield in_clause 

94 

95 def _batch_in_clauses(**where: Any) -> Iterator[sqlalchemy.sql.expression.ClauseElement]: 

96 """Generate a sequence of WHERE clauses with a limited number of 

97 items in IN clauses. 

98 """ 

99 batches: List[Iterable[Any]] = [] 

100 for k, v in where.items(): 

101 column = self._table.columns[k] 

102 if isinstance(v, (list, tuple, set)): 

103 batches.append(_batch_in_clause(column, v)) 

104 else: 

105 # single "batch" for a regular eq operator 

106 batches.append([column == v]) 

107 

108 for clauses in itertools.product(*batches): 

109 yield sqlalchemy.sql.and_(*clauses) 

110 

111 sql = self._table.select() 

112 if where: 

113 # Split long IN clauses into shorter batches 

114 batched_sql = [sql.where(clause) for clause in _batch_in_clauses(**where)] 

115 else: 

116 batched_sql = [sql] 

117 for sql_batch in batched_sql: 

118 with self._db.query(sql_batch) as sql_result: 

119 sql_mappings = sql_result.mappings().fetchall() 

120 yield from sql_mappings 

121 

122 def delete(self, columns: Iterable[str], *rows: dict) -> None: 

123 # Docstring inherited from OpaqueTableStorage. 

124 self._db.delete(self._table, columns, *rows) 

125 

126 

127class ByNameOpaqueTableStorageManager(OpaqueTableStorageManager): 

128 """An implementation of `OpaqueTableStorageManager` that simply creates a 

129 true table for each different named opaque logical table. 

130 

131 Instances of this class should generally be constructed via the 

132 `initialize` class method instead of invoking ``__init__`` directly. 

133 

134 Parameters 

135 ---------- 

136 db : `Database` 

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

138 metaTable : `sqlalchemy.schema.Table` 

139 SQLAlchemy representation of the table that records which opaque 

140 logical tables exist. 

141 """ 

142 

143 def __init__(self, db: Database, metaTable: sqlalchemy.schema.Table): 

144 self._db = db 

145 self._metaTable = metaTable 

146 self._storage: Dict[str, OpaqueTableStorage] = {} 

147 

148 _META_TABLE_NAME: ClassVar[str] = "opaque_meta" 

149 

150 _META_TABLE_SPEC: ClassVar[TableSpec] = TableSpec( 

151 fields=[ 

152 FieldSpec("table_name", dtype=sqlalchemy.String, length=128, primaryKey=True), 

153 ], 

154 ) 

155 

156 @classmethod 

157 def initialize(cls, db: Database, context: StaticTablesContext) -> OpaqueTableStorageManager: 

158 # Docstring inherited from OpaqueTableStorageManager. 

159 metaTable = context.addTable(cls._META_TABLE_NAME, cls._META_TABLE_SPEC) 

160 return cls(db=db, metaTable=metaTable) 

161 

162 def get(self, name: str) -> Optional[OpaqueTableStorage]: 

163 # Docstring inherited from OpaqueTableStorageManager. 

164 return self._storage.get(name) 

165 

166 def register(self, name: str, spec: TableSpec) -> OpaqueTableStorage: 

167 # Docstring inherited from OpaqueTableStorageManager. 

168 result = self._storage.get(name) 

169 if result is None: 

170 # Create the table itself. If it already exists but wasn't in 

171 # the dict because it was added by another client since this one 

172 # was initialized, that's fine. 

173 table = self._db.ensureTableExists(name, spec) 

174 # Add a row to the meta table so we can find this table in the 

175 # future. Also okay if that already exists, so we use sync. 

176 self._db.sync(self._metaTable, keys={"table_name": name}) 

177 result = ByNameOpaqueTableStorage(name=name, table=table, db=self._db) 

178 self._storage[name] = result 

179 return result 

180 

181 @classmethod 

182 def currentVersion(cls) -> Optional[VersionTuple]: 

183 # Docstring inherited from VersionedExtension. 

184 return _VERSION 

185 

186 def schemaDigest(self) -> Optional[str]: 

187 # Docstring inherited from VersionedExtension. 

188 return self._defaultSchemaDigest([self._metaTable], self._db.dialect)