Coverage for tests/test_postgresql.py: 34%

111 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-07-12 10:56 -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/>. 

21 

22import gc 

23import itertools 

24import os 

25import secrets 

26import unittest 

27import warnings 

28from contextlib import contextmanager 

29 

30import astropy.time 

31 

32try: 

33 # It's possible but silly to have testing.postgresql installed without 

34 # having the postgresql server installed (because then nothing in 

35 # testing.postgresql would work), so we use the presence of that module 

36 # to test whether we can expect the server to be available. 

37 import testing.postgresql 

38except ImportError: 

39 testing = None 

40 

41import sqlalchemy 

42from lsst.daf.butler import Timespan, ddl 

43from lsst.daf.butler.registry import Registry 

44from lsst.daf.butler.registry.databases.postgresql import PostgresqlDatabase, _RangeTimespanType 

45from lsst.daf.butler.registry.tests import DatabaseTests, RegistryTests 

46from lsst.daf.butler.tests.utils import makeTestTempDir, removeTestTempDir 

47 

48TESTDIR = os.path.abspath(os.path.dirname(__file__)) 

49 

50 

51def _startServer(root): 

52 """Start a PostgreSQL server and create a database within it, returning 

53 an object encapsulating both. 

54 """ 

55 server = testing.postgresql.Postgresql(base_dir=root) 

56 engine = sqlalchemy.engine.create_engine(server.url()) 

57 with engine.begin() as connection: 

58 connection.execute(sqlalchemy.text("CREATE EXTENSION btree_gist;")) 

59 return server 

60 

61 

62@unittest.skipUnless(testing is not None, "testing.postgresql module not found") 

63class PostgresqlDatabaseTestCase(unittest.TestCase, DatabaseTests): 

64 """Test a postgres Registry.""" 

65 

66 @classmethod 

67 def setUpClass(cls): 

68 cls.root = makeTestTempDir(TESTDIR) 

69 cls.server = _startServer(cls.root) 

70 

71 @classmethod 

72 def tearDownClass(cls): 

73 # Clean up any lingering SQLAlchemy engines/connections 

74 # so they're closed before we shut down the server. 

75 gc.collect() 

76 cls.server.stop() 

77 removeTestTempDir(cls.root) 

78 

79 def makeEmptyDatabase(self, origin: int = 0) -> PostgresqlDatabase: 

80 namespace = f"namespace_{secrets.token_hex(8).lower()}" 

81 return PostgresqlDatabase.fromUri(origin=origin, uri=self.server.url(), namespace=namespace) 

82 

83 def getNewConnection(self, database: PostgresqlDatabase, *, writeable: bool) -> PostgresqlDatabase: 

84 return PostgresqlDatabase.fromUri( 

85 origin=database.origin, uri=self.server.url(), namespace=database.namespace, writeable=writeable 

86 ) 

87 

88 @contextmanager 

89 def asReadOnly(self, database: PostgresqlDatabase) -> PostgresqlDatabase: 

90 yield self.getNewConnection(database, writeable=False) 

91 

92 def testNameShrinking(self): 

93 """Test that too-long names for database entities other than tables 

94 and columns (which we preserve, and just expect to fit) are shrunk. 

95 """ 

96 db = self.makeEmptyDatabase(origin=1) 

97 with db.declareStaticTables(create=True) as context: 

98 # Table and field names are each below the 63-char limit even when 

99 # accounting for the prefix, but their combination (which will 

100 # appear in sequences and constraints) is not. 

101 tableName = "a_table_with_a_very_very_long_42_char_name" 

102 fieldName1 = "a_column_with_a_very_very_long_43_char_name" 

103 fieldName2 = "another_column_with_a_very_very_long_49_char_name" 

104 context.addTable( 

105 tableName, 

106 ddl.TableSpec( 

107 fields=[ 

108 ddl.FieldSpec( 

109 fieldName1, dtype=sqlalchemy.BigInteger, autoincrement=True, primaryKey=True 

110 ), 

111 ddl.FieldSpec( 

112 fieldName2, 

113 dtype=sqlalchemy.String, 

114 length=16, 

115 nullable=False, 

116 ), 

117 ], 

118 unique={(fieldName2,)}, 

119 ), 

120 ) 

121 # Add another table, this time dynamically, with a foreign key to the 

122 # first table. 

123 db.ensureTableExists( 

124 tableName + "_b", 

125 ddl.TableSpec( 

126 fields=[ 

127 ddl.FieldSpec( 

128 fieldName1 + "_b", dtype=sqlalchemy.BigInteger, autoincrement=True, primaryKey=True 

129 ), 

130 ddl.FieldSpec( 

131 fieldName2 + "_b", 

132 dtype=sqlalchemy.String, 

133 length=16, 

134 nullable=False, 

135 ), 

136 ], 

137 foreignKeys=[ 

138 ddl.ForeignKeySpec(tableName, source=(fieldName2 + "_b",), target=(fieldName2,)), 

139 ], 

140 ), 

141 ) 

142 

143 def test_RangeTimespanType(self): 

144 start = astropy.time.Time("2020-01-01T00:00:00", format="isot", scale="tai") 

145 offset = astropy.time.TimeDelta(60, format="sec") 

146 timestamps = [start + offset * n for n in range(3)] 

147 timespans = [Timespan(begin=None, end=None)] 

148 timespans.extend(Timespan(begin=None, end=t) for t in timestamps) 

149 timespans.extend(Timespan(begin=t, end=None) for t in timestamps) 

150 timespans.extend(Timespan(begin=a, end=b) for a, b in itertools.combinations(timestamps, 2)) 

151 db = self.makeEmptyDatabase(origin=1) 

152 with db.declareStaticTables(create=True) as context: 

153 tbl = context.addTable( 

154 "tbl", 

155 ddl.TableSpec( 

156 fields=[ 

157 ddl.FieldSpec(name="id", dtype=sqlalchemy.Integer, primaryKey=True), 

158 ddl.FieldSpec(name="timespan", dtype=_RangeTimespanType), 

159 ], 

160 ), 

161 ) 

162 rows = [{"id": n, "timespan": t} for n, t in enumerate(timespans)] 

163 db.insert(tbl, *rows) 

164 

165 # Test basic round-trip through database. 

166 with db.query(tbl.select().order_by(tbl.columns.id)) as sql_result: 

167 self.assertEqual(rows, [row._asdict() for row in sql_result]) 

168 

169 # Test that Timespan's Python methods are consistent with our usage of 

170 # half-open ranges and PostgreSQL operators on ranges. 

171 def subquery(alias: str) -> sqlalchemy.sql.FromClause: 

172 return ( 

173 sqlalchemy.sql.select(tbl.columns.id.label("id"), tbl.columns.timespan.label("timespan")) 

174 .select_from(tbl) 

175 .alias(alias) 

176 ) 

177 

178 sq1 = subquery("sq1") 

179 sq2 = subquery("sq2") 

180 query = sqlalchemy.sql.select( 

181 sq1.columns.id.label("n1"), 

182 sq2.columns.id.label("n2"), 

183 sq1.columns.timespan.overlaps(sq2.columns.timespan).label("overlaps"), 

184 ) 

185 

186 # `columns` is deprecated since 1.4, but 

187 # `selected_columns` method did not exist in 1.3. 

188 if hasattr(query, "selected_columns"): 

189 columns = query.selected_columns 

190 else: 

191 columns = query.columns 

192 

193 # SQLAlchemy issues a warning about cartesian product of two tables, 

194 # which we do intentionally. Disable that warning temporarily. 

195 with warnings.catch_warnings(): 

196 warnings.filterwarnings( 

197 "ignore", message=".*cartesian product", category=sqlalchemy.exc.SAWarning 

198 ) 

199 with db.query(query) as sql_result: 

200 dbResults = { 

201 (row[columns.n1], row[columns.n2]): row[columns.overlaps] for row in sql_result.mappings() 

202 } 

203 

204 pyResults = { 

205 (n1, n2): t1.overlaps(t2) 

206 for (n1, t1), (n2, t2) in itertools.product(enumerate(timespans), enumerate(timespans)) 

207 } 

208 self.assertEqual(pyResults, dbResults) 

209 

210 

211@unittest.skipUnless(testing is not None, "testing.postgresql module not found") 

212class PostgresqlRegistryTests(RegistryTests): 

213 """Tests for `Registry` backed by a PostgreSQL database. 

214 

215 Notes 

216 ----- 

217 This is not a subclass of `unittest.TestCase` but to avoid repetition it 

218 defines methods that override `unittest.TestCase` methods. To make this 

219 work subclasses have to have this class first in the bases list. 

220 """ 

221 

222 @classmethod 

223 def setUpClass(cls): 

224 cls.root = makeTestTempDir(TESTDIR) 

225 cls.server = _startServer(cls.root) 

226 

227 @classmethod 

228 def tearDownClass(cls): 

229 # Clean up any lingering SQLAlchemy engines/connections 

230 # so they're closed before we shut down the server. 

231 gc.collect() 

232 cls.server.stop() 

233 removeTestTempDir(cls.root) 

234 

235 @classmethod 

236 def getDataDir(cls) -> str: 

237 return os.path.normpath(os.path.join(os.path.dirname(__file__), "data", "registry")) 

238 

239 def makeRegistry(self, share_repo_with: Registry | None = None) -> Registry: 

240 if share_repo_with is None: 

241 namespace = f"namespace_{secrets.token_hex(8).lower()}" 

242 else: 

243 namespace = share_repo_with._db.namespace 

244 config = self.makeRegistryConfig() 

245 config["db"] = self.server.url() 

246 config["namespace"] = namespace 

247 if share_repo_with is None: 

248 return Registry.createFromConfig(config) 

249 else: 

250 return Registry.fromConfig(config) 

251 

252 

253class PostgresqlRegistryNameKeyCollMgrUUIDTestCase(PostgresqlRegistryTests, unittest.TestCase): 

254 """Tests for `Registry` backed by a PostgreSQL database. 

255 

256 This test case uses NameKeyCollectionManager and 

257 ByDimensionsDatasetRecordStorageManagerUUID. 

258 """ 

259 

260 collectionsManager = "lsst.daf.butler.registry.collections.nameKey.NameKeyCollectionManager" 

261 datasetsManager = ( 

262 "lsst.daf.butler.registry.datasets.byDimensions.ByDimensionsDatasetRecordStorageManagerUUID" 

263 ) 

264 

265 

266class PostgresqlRegistrySynthIntKeyCollMgrUUIDTestCase(PostgresqlRegistryTests, unittest.TestCase): 

267 """Tests for `Registry` backed by a PostgreSQL database. 

268 

269 This test case uses SynthIntKeyCollectionManager and 

270 ByDimensionsDatasetRecordStorageManagerUUID. 

271 """ 

272 

273 collectionsManager = "lsst.daf.butler.registry.collections.synthIntKey.SynthIntKeyCollectionManager" 

274 datasetsManager = ( 

275 "lsst.daf.butler.registry.datasets.byDimensions.ByDimensionsDatasetRecordStorageManagerUUID" 

276 ) 

277 

278 

279if __name__ == "__main__": 

280 unittest.main()