Coverage for python/lsst/daf/butler/core/dimensions/_schema.py: 22%

97 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2022-10-12 09:01 +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__all__ = ("addDimensionForeignKey",) 

24 

25import copy 

26from typing import TYPE_CHECKING, Tuple 

27 

28from .. import ddl 

29from ..named import NamedValueSet 

30from ..timespan import TimespanDatabaseRepresentation 

31 

32if TYPE_CHECKING: # Imports needed only for type annotations; may be circular. 32 ↛ 33line 32 didn't jump to line 33, because the condition on line 32 was never true

33 from ._elements import Dimension, DimensionElement 

34 

35 

36def _makeForeignKeySpec(dimension: Dimension) -> ddl.ForeignKeySpec: 

37 """Make a `ddl.ForeignKeySpec`. 

38 

39 This will reference the table for the given `Dimension` table. 

40 

41 Most callers should use the higher-level `addDimensionForeignKey` function 

42 instead. 

43 

44 Parameters 

45 ---------- 

46 dimension : `Dimension` 

47 The dimension to be referenced. Caller guarantees that it is actually 

48 associated with a table. 

49 

50 Returns 

51 ------- 

52 spec : `ddl.ForeignKeySpec` 

53 A database-agnostic foreign key specification. 

54 """ 

55 source = [] 

56 target = [] 

57 for other in dimension.required: 

58 if other == dimension: 

59 target.append(dimension.primaryKey.name) 

60 else: 

61 target.append(other.name) 

62 source.append(other.name) 

63 return ddl.ForeignKeySpec(table=dimension.name, source=tuple(source), target=tuple(target)) 

64 

65 

66def addDimensionForeignKey( 

67 tableSpec: ddl.TableSpec, 

68 dimension: Dimension, 

69 *, 

70 primaryKey: bool, 

71 nullable: bool = False, 

72 constraint: bool = True, 

73) -> ddl.FieldSpec: 

74 """Add a field and possibly a foreign key to a table specification. 

75 

76 The field will reference the table for the given `Dimension`. 

77 

78 Parameters 

79 ---------- 

80 tableSpec : `ddl.TableSpec` 

81 Specification the field and foreign key are to be added to. 

82 dimension : `Dimension` 

83 Dimension to be referenced. If this dimension has required 

84 dependencies, those must have already been added to the table. A field 

85 will be added that correspond to this dimension's primary key, and a 

86 foreign key constraint will be added only if the dimension is 

87 associated with a table of its own. 

88 primaryKey : `bool` 

89 If `True`, the new field will be added as part of a compound primary 

90 key for the table. 

91 nullable : `bool`, optional 

92 If `False` (default) the new field will be added with a NOT NULL 

93 constraint. 

94 constraint : `bool` 

95 If `False` (`True` is default), just add the field, not the foreign 

96 key constraint. 

97 

98 Returns 

99 ------- 

100 fieldSpec : `ddl.FieldSpec` 

101 Specification for the field just added. 

102 """ 

103 # Add the dependency's primary key field, but use the dimension name for 

104 # the field name to make it unique and more meaningful in this table. 

105 fieldSpec = copy.copy(dimension.primaryKey) 

106 fieldSpec.name = dimension.name 

107 fieldSpec.primaryKey = primaryKey 

108 fieldSpec.nullable = nullable 

109 tableSpec.fields.add(fieldSpec) 

110 # Also add a foreign key constraint on the dependency table, but only if 

111 # there actually is one and we weren't told not to. 

112 if dimension.hasTable() and dimension.viewOf is None and constraint: 

113 tableSpec.foreignKeys.append(_makeForeignKeySpec(dimension)) 

114 return fieldSpec 

115 

116 

117class DimensionElementFields: 

118 """Class for constructing table schemas for `DimensionElement`. 

119 

120 This creates an object that constructs the table schema for a 

121 `DimensionElement` and provides a categorized view of its fields. 

122 

123 Parameters 

124 ---------- 

125 element : `DimensionElement` 

126 Element for which to make a table specification. 

127 

128 Notes 

129 ----- 

130 This combines the foreign key fields from dependencies, unique keys 

131 for true `Dimension` instances, metadata fields, and region/timestamp 

132 fields for spatial/temporal elements. 

133 

134 Callers should use `DimensionUniverse.makeSchemaSpec` if they want to 

135 account for elements that have no table or reference another table; this 

136 class simply creates a specification for the table an element _would_ have 

137 without checking whether it does have one. That can be useful in contexts 

138 (e.g. `DimensionRecord`) where we want to simulate the existence of such a 

139 table. 

140 """ 

141 

142 def __init__(self, element: DimensionElement): 

143 self.element = element 

144 self._tableSpec = ddl.TableSpec(fields=()) 

145 # Add the primary key fields of required dimensions. These continue to 

146 # be primary keys in the table for this dimension. 

147 self.required = NamedValueSet() 

148 self.dimensions = NamedValueSet() 

149 self.facts = NamedValueSet() 

150 self.standard = NamedValueSet() 

151 dependencies = [] 

152 for dimension in element.required: 

153 if dimension != element: 

154 fieldSpec = addDimensionForeignKey(self._tableSpec, dimension, primaryKey=True) 

155 dependencies.append(fieldSpec.name) 

156 else: 

157 fieldSpec = element.primaryKey # type: ignore 

158 # A Dimension instance is in its own required dependency graph 

159 # (always at the end, because of topological ordering). In 

160 # this case we don't want to rename the field. 

161 self._tableSpec.fields.add(fieldSpec) 

162 self.required.add(fieldSpec) 

163 self.dimensions.add(fieldSpec) 

164 self.standard.add(fieldSpec) 

165 # Add fields and foreign keys for implied dimensions. These are 

166 # primary keys in their own table, but should not be here. As with 

167 # required dependencies, we rename the fields with the dimension name. 

168 # We use element.implied instead of element.graph.implied because we 

169 # don't want *recursive* implied dependencies. 

170 self.implied = NamedValueSet() 

171 for dimension in element.implied: 

172 fieldSpec = addDimensionForeignKey(self._tableSpec, dimension, primaryKey=False, nullable=False) 

173 self.implied.add(fieldSpec) 

174 self.dimensions.add(fieldSpec) 

175 self.standard.add(fieldSpec) 

176 # Add non-primary unique keys and unique constraints for them. 

177 for fieldSpec in getattr(element, "alternateKeys", ()): 

178 self._tableSpec.fields.add(fieldSpec) 

179 self._tableSpec.unique.add(tuple(dependencies) + (fieldSpec.name,)) 

180 self.standard.add(fieldSpec) 

181 self.facts.add(fieldSpec) 

182 # Add other metadata fields. 

183 for fieldSpec in element.metadata: 

184 self._tableSpec.fields.add(fieldSpec) 

185 self.standard.add(fieldSpec) 

186 self.facts.add(fieldSpec) 

187 names = list(self.standard.names) 

188 # Add fields for regions and/or timespans. 

189 if element.spatial is not None: 

190 names.append("region") 

191 if element.temporal is not None: 

192 names.append(TimespanDatabaseRepresentation.NAME) 

193 self.names = tuple(names) 

194 

195 def makeTableSpec( 

196 self, 

197 TimespanReprClass: type[TimespanDatabaseRepresentation], 

198 ) -> ddl.TableSpec: 

199 """Construct a complete specification for a table. 

200 

201 The table could hold the records of this element. 

202 

203 Parameters 

204 ---------- 

205 TimespanReprClass : `type` [ `TimespanDatabaseRepresentation` ] 

206 Class object that specifies how timespans are represented in the 

207 database. 

208 

209 Returns 

210 ------- 

211 spec : `ddl.TableSpec` 

212 Specification for a table. 

213 """ 

214 if self.element.temporal is not None or self.element.spatial is not None: 

215 spec = ddl.TableSpec( 

216 fields=NamedValueSet(self._tableSpec.fields), 

217 unique=self._tableSpec.unique, 

218 indexes=self._tableSpec.indexes, 

219 foreignKeys=self._tableSpec.foreignKeys, 

220 ) 

221 if self.element.spatial is not None: 

222 spec.fields.add(ddl.FieldSpec.for_region()) 

223 if self.element.temporal is not None: 

224 spec.fields.update(TimespanReprClass.makeFieldSpecs(nullable=True)) 

225 else: 

226 spec = self._tableSpec 

227 return spec 

228 

229 def __str__(self) -> str: 

230 lines = [f"{self.element.name}: "] 

231 lines.extend(f" {field.name}: {field.getPythonType().__name__}" for field in self.standard) 

232 if self.element.spatial is not None: 

233 lines.append(" region: lsst.sphgeom.Region") 

234 if self.element.temporal is not None: 

235 lines.append(" timespan: lsst.daf.butler.Timespan") 

236 return "\n".join(lines) 

237 

238 element: DimensionElement 

239 """The dimension element these fields correspond to. 

240 

241 (`DimensionElement`) 

242 """ 

243 

244 required: NamedValueSet[ddl.FieldSpec] 

245 """The required dimension fields of this table. 

246 

247 They correspond to the element's required 

248 dimensions, in that order, i.e. `DimensionElement.required` 

249 (`NamedValueSet` [ `ddl.FieldSpec` ]). 

250 """ 

251 

252 implied: NamedValueSet[ddl.FieldSpec] 

253 """The implied dimension fields of this table. 

254 

255 They correspond to the element's implied 

256 dimensions, in that order, i.e. `DimensionElement.implied` 

257 (`NamedValueSet` [ `ddl.FieldSpec` ]). 

258 """ 

259 

260 dimensions: NamedValueSet[ddl.FieldSpec] 

261 """The direct and implied dimension fields of this table. 

262 

263 They correspond to the element's direct 

264 required and implied dimensions, in that order, i.e. 

265 `DimensionElement.dimensions` (`NamedValueSet` [ `ddl.FieldSpec` ]). 

266 """ 

267 

268 facts: NamedValueSet[ddl.FieldSpec] 

269 """The standard fields of this table that do not correspond to dimensions. 

270 

271 (`NamedValueSet` [ `ddl.FieldSpec` ]). 

272 

273 This is equivalent to ``standard - dimensions`` (but possibly in a 

274 different order). 

275 """ 

276 

277 standard: NamedValueSet[ddl.FieldSpec] 

278 """All standard fields that are expected to have the same form. 

279 

280 They are expected to have the same form in all 

281 databases; this is all fields other than those that represent a region 

282 and/or timespan (`NamedValueSet` [ `ddl.FieldSpec` ]). 

283 """ 

284 

285 names: Tuple[str, ...] 

286 """The names of all fields in the specification (`tuple` [ `str` ]). 

287 

288 This includes "region" and/or "timespan" if `element` is spatial and/or 

289 temporal (respectively). The actual database representation of these 

290 quantities may involve multiple fields (or even fields only on a different 

291 table), but the Python representation of those rows (i.e. `DimensionRecord` 

292 instances) will always contain exactly these fields. 

293 """