Coverage for python/lsst/daf/butler/_column_type_info.py: 35%

61 statements  

« prev     ^ index     » next       coverage.py v7.11.0, created at 2025-11-06 01:33 -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 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 

28from __future__ import annotations 

29 

30__all__ = ("ColumnTypeInfo", "LogicalColumn") 

31 

32import dataclasses 

33import datetime 

34from collections.abc import Iterable 

35from typing import cast 

36 

37import astropy.time 

38import sqlalchemy 

39 

40from lsst.daf.relation import ColumnTag, sql 

41 

42from . import ddl 

43from ._column_tags import DatasetColumnTag, DimensionKeyColumnTag, DimensionRecordColumnTag 

44from .dimensions import Dimension, DimensionUniverse 

45from .timespan_database_representation import TimespanDatabaseRepresentation 

46 

47LogicalColumn = sqlalchemy.sql.ColumnElement | TimespanDatabaseRepresentation 

48"""A type alias for the types used to represent columns in SQL relations. 

49 

50This is the butler specialization of the `lsst.daf.relation.sql.LogicalColumn` 

51concept. 

52""" 

53 

54 

55@dataclasses.dataclass(frozen=True, eq=False) 

56class ColumnTypeInfo: 

57 """A struct that aggregates information about column types that can differ 

58 across data repositories due to `Registry` and dimension configuration. 

59 """ 

60 

61 timespan_cls: type[TimespanDatabaseRepresentation] 

62 """An abstraction around the column type or types used for timespans by 

63 this database engine. 

64 """ 

65 

66 universe: DimensionUniverse 

67 """Object that manages the definitions of all dimension and dimension 

68 elements. 

69 """ 

70 

71 dataset_id_spec: ddl.FieldSpec 

72 """Field specification for the dataset primary key column. 

73 """ 

74 

75 run_key_spec: ddl.FieldSpec 

76 """Field specification for the `~CollectionType.RUN` primary key column. 

77 """ 

78 

79 ingest_date_dtype: type[ddl.AstropyTimeNsecTai] | type[sqlalchemy.TIMESTAMP] 

80 """Type of the ``ingest_date`` column, can be either 

81 `~lsst.daf.butler.ddl.AstropyTimeNsecTai` or `sqlalchemy.TIMESTAMP`. 

82 """ 

83 

84 @property 

85 def ingest_date_pytype(self) -> type: 

86 """Python type corresponding to ``ingest_date`` column type. 

87 

88 Returns 

89 ------- 

90 `type` 

91 The Python type. 

92 """ 

93 if self.ingest_date_dtype is ddl.AstropyTimeNsecTai: 

94 return astropy.time.Time 

95 elif self.ingest_date_dtype is sqlalchemy.TIMESTAMP: 

96 return datetime.datetime 

97 else: 

98 raise TypeError(f"Unexpected type of ingest_date_dtype: {self.ingest_date_dtype}") 

99 

100 def make_relation_table_spec( 

101 self, 

102 columns: Iterable[ColumnTag], 

103 unique_keys: Iterable[Iterable[ColumnTag]] = (), 

104 ) -> ddl.TableSpec: 

105 """Create a specification for a table with the given relation columns. 

106 

107 This is used primarily to create temporary tables for query results. 

108 

109 Parameters 

110 ---------- 

111 columns : `~collections.abc.Iterable` [ `ColumnTag` ] 

112 Iterable of column identifiers. 

113 unique_keys : `~collections.abc.Iterable` \ 

114 [ `~collections.abc.Iterable` [ `ColumnTag` ] ] 

115 Unique constraints to add the table, as a nested iterable of 

116 (first) constraint and (second) the columns within that constraint. 

117 

118 Returns 

119 ------- 

120 spec : `ddl.TableSpec` 

121 Specification for a table. 

122 """ 

123 result = ddl.TableSpec(fields=()) 

124 columns = list(columns) 

125 if not columns: 

126 result.fields.add( 

127 ddl.FieldSpec( 

128 sql.Engine.EMPTY_COLUMNS_NAME, 

129 dtype=sql.Engine.EMPTY_COLUMNS_TYPE, 

130 nullable=True, 

131 ) 

132 ) 

133 for tag in columns: 

134 match tag: 

135 case DimensionKeyColumnTag(dimension=dimension_name): 

136 result.fields.add( 

137 dataclasses.replace( 

138 cast(Dimension, self.universe[dimension_name]).primaryKey, 

139 name=tag.qualified_name, 

140 primaryKey=False, 

141 nullable=False, 

142 ) 

143 ) 

144 case DimensionRecordColumnTag(column="region"): 

145 result.fields.add(ddl.FieldSpec.for_region(tag.qualified_name)) 

146 case DimensionRecordColumnTag(column="timespan") | DatasetColumnTag(column="timespan"): 

147 result.fields.update( 

148 self.timespan_cls.makeFieldSpecs(nullable=True, name=tag.qualified_name) 

149 ) 

150 case DimensionRecordColumnTag(element=element_name, column=column): 

151 element = self.universe[element_name] 

152 result.fields.add( 

153 dataclasses.replace( 

154 element.RecordClass.fields.facts[column], 

155 name=tag.qualified_name, 

156 nullable=True, 

157 primaryKey=False, 

158 ) 

159 ) 

160 case DatasetColumnTag(column="dataset_id"): 

161 result.fields.add( 

162 dataclasses.replace( 

163 self.dataset_id_spec, name=tag.qualified_name, primaryKey=False, nullable=False 

164 ) 

165 ) 

166 case DatasetColumnTag(column="run"): 

167 result.fields.add( 

168 dataclasses.replace( 

169 self.run_key_spec, name=tag.qualified_name, primaryKey=False, nullable=False 

170 ) 

171 ) 

172 case DatasetColumnTag(column="ingest_date"): 

173 result.fields.add( 

174 ddl.FieldSpec(tag.qualified_name, dtype=self.ingest_date_dtype, nullable=False) 

175 ) 

176 case _: 

177 raise TypeError(f"Unexpected column tag {tag}.") 

178 for unique_key in unique_keys: 

179 result.unique.add(tuple(tag.qualified_name for tag in unique_key)) 

180 return result