Coverage for tests/test_postgresql.py: 46%

Shortcuts on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

113 statements  

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 @classmethod 

65 def setUpClass(cls): 

66 cls.root = makeTestTempDir(TESTDIR) 

67 cls.server = _startServer(cls.root) 

68 

69 @classmethod 

70 def tearDownClass(cls): 

71 # Clean up any lingering SQLAlchemy engines/connections 

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

73 gc.collect() 

74 cls.server.stop() 

75 removeTestTempDir(cls.root) 

76 

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

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

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

80 

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

82 return PostgresqlDatabase.fromUri( 

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

84 ) 

85 

86 @contextmanager 

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

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

89 

90 def testNameShrinking(self): 

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

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

93 """ 

94 db = self.makeEmptyDatabase(origin=1) 

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

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

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

98 # appear in sequences and constraints) is not. 

99 tableName = "a_table_with_a_very_very_long_42_char_name" 

100 fieldName1 = "a_column_with_a_very_very_long_43_char_name" 

101 fieldName2 = "another_column_with_a_very_very_long_49_char_name" 

102 context.addTable( 

103 tableName, 

104 ddl.TableSpec( 

105 fields=[ 

106 ddl.FieldSpec( 

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

108 ), 

109 ddl.FieldSpec( 

110 fieldName2, 

111 dtype=sqlalchemy.String, 

112 length=16, 

113 nullable=False, 

114 ), 

115 ], 

116 unique={(fieldName2,)}, 

117 ), 

118 ) 

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

120 # first table. 

121 db.ensureTableExists( 

122 tableName + "_b", 

123 ddl.TableSpec( 

124 fields=[ 

125 ddl.FieldSpec( 

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

127 ), 

128 ddl.FieldSpec( 

129 fieldName2 + "_b", 

130 dtype=sqlalchemy.String, 

131 length=16, 

132 nullable=False, 

133 ), 

134 ], 

135 foreignKeys=[ 

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

137 ], 

138 ), 

139 ) 

140 

141 def test_RangeTimespanType(self): 

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

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

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

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

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

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

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

149 db = self.makeEmptyDatabase(origin=1) 

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

151 tbl = context.addTable( 

152 "tbl", 

153 ddl.TableSpec( 

154 fields=[ 

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

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

157 ], 

158 ), 

159 ) 

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

161 db.insert(tbl, *rows) 

162 

163 # Test basic round-trip through database. 

164 self.assertEqual(rows, [row._asdict() for row in db.query(tbl.select().order_by(tbl.columns.id))]) 

165 

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

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

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

169 return ( 

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

171 .select_from(tbl) 

172 .alias(alias) 

173 ) 

174 

175 sq1 = subquery("sq1") 

176 sq2 = subquery("sq2") 

177 query = sqlalchemy.sql.select( 

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

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

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

181 ) 

182 

183 # `columns` is deprecated since 1.4, but 

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

185 if hasattr(query, "selected_columns"): 

186 columns = query.selected_columns 

187 else: 

188 columns = query.columns 

189 

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

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

192 with warnings.catch_warnings(): 

193 warnings.filterwarnings( 

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

195 ) 

196 dbResults = { 

197 (row[columns.n1], row[columns.n2]): row[columns.overlaps] 

198 for row in db.query(query).mappings() 

199 } 

200 

201 pyResults = { 

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

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

204 } 

205 self.assertEqual(pyResults, dbResults) 

206 

207 

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

209class PostgresqlRegistryTests(RegistryTests): 

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

211 

212 Note 

213 ---- 

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

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

216 work sublasses have to have this class first in the bases list. 

217 """ 

218 

219 @classmethod 

220 def setUpClass(cls): 

221 cls.root = makeTestTempDir(TESTDIR) 

222 cls.server = _startServer(cls.root) 

223 

224 @classmethod 

225 def tearDownClass(cls): 

226 # Clean up any lingering SQLAlchemy engines/connections 

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

228 gc.collect() 

229 cls.server.stop() 

230 removeTestTempDir(cls.root) 

231 

232 @classmethod 

233 def getDataDir(cls) -> str: 

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

235 

236 def makeRegistry(self) -> Registry: 

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

238 config = self.makeRegistryConfig() 

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

240 config["namespace"] = namespace 

241 return Registry.createFromConfig(config) 

242 

243 

244class PostgresqlRegistryNameKeyCollMgrTestCase(PostgresqlRegistryTests, unittest.TestCase): 

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

246 

247 This test case uses NameKeyCollectionManager and 

248 ByDimensionsDatasetRecordStorageManager. 

249 """ 

250 

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

252 datasetsManager = "lsst.daf.butler.registry.datasets.byDimensions.ByDimensionsDatasetRecordStorageManager" 

253 

254 

255class PostgresqlRegistrySynthIntKeyCollMgrTestCase(PostgresqlRegistryTests, unittest.TestCase): 

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

257 

258 This test case uses SynthIntKeyCollectionManager and 

259 ByDimensionsDatasetRecordStorageManager. 

260 """ 

261 

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

263 datasetsManager = "lsst.daf.butler.registry.datasets.byDimensions.ByDimensionsDatasetRecordStorageManager" 

264 

265 

266class PostgresqlRegistryNameKeyCollMgrUUIDTestCase(PostgresqlRegistryTests, unittest.TestCase): 

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

268 

269 This test case uses NameKeyCollectionManager and 

270 ByDimensionsDatasetRecordStorageManagerUUID. 

271 """ 

272 

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

274 datasetsManager = ( 

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

276 ) 

277 

278 

279class PostgresqlRegistrySynthIntKeyCollMgrUUIDTestCase(PostgresqlRegistryTests, unittest.TestCase): 

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

281 

282 This test case uses SynthIntKeyCollectionManager and 

283 ByDimensionsDatasetRecordStorageManagerUUID. 

284 """ 

285 

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

287 datasetsManager = ( 

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

289 ) 

290 

291 

292if __name__ == "__main__": 292 ↛ 293line 292 didn't jump to line 293, because the condition on line 292 was never true

293 unittest.main()