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

67 statements  

« prev     ^ index     » next       coverage.py v7.2.5, created at 2023-05-05 03:17 -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 

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: 

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[sqlalchemy.RowMapping]: 

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.ColumnElement]: 

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__( 

144 self, 

145 db: Database, 

146 metaTable: sqlalchemy.schema.Table, 

147 registry_schema_version: VersionTuple | None = None, 

148 ): 

149 super().__init__(registry_schema_version=registry_schema_version) 

150 self._db = db 

151 self._metaTable = metaTable 

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

153 

154 _META_TABLE_NAME: ClassVar[str] = "opaque_meta" 

155 

156 _META_TABLE_SPEC: ClassVar[TableSpec] = TableSpec( 

157 fields=[ 

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

159 ], 

160 ) 

161 

162 @classmethod 

163 def initialize( 

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

165 ) -> OpaqueTableStorageManager: 

166 # Docstring inherited from OpaqueTableStorageManager. 

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

168 return cls(db=db, metaTable=metaTable, registry_schema_version=registry_schema_version) 

169 

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

171 # Docstring inherited from OpaqueTableStorageManager. 

172 return self._storage.get(name) 

173 

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

175 # Docstring inherited from OpaqueTableStorageManager. 

176 result = self._storage.get(name) 

177 if result is None: 

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

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

180 # was initialized, that's fine. 

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

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

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

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

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

186 self._storage[name] = result 

187 return result 

188 

189 @classmethod 

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

191 # Docstring inherited from VersionedExtension. 

192 return [_VERSION]