MCPcopy
hub / github.com/sqlalchemy/sqlalchemy / main

Function main

examples/sharding/separate_databases.py:251–321  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

249
250
251def main():
252 setup()
253
254 # save and load objects!
255
256 tokyo = WeatherLocation("Asia", "Tokyo")
257 newyork = WeatherLocation("North America", "New York")
258 toronto = WeatherLocation("North America", "Toronto")
259 london = WeatherLocation("Europe", "London")
260 dublin = WeatherLocation("Europe", "Dublin")
261 brasilia = WeatherLocation("South America", "Brasila")
262 quito = WeatherLocation("South America", "Quito")
263
264 tokyo.reports.append(Report(80.0))
265 newyork.reports.append(Report(75))
266 quito.reports.append(Report(85))
267
268 with Session() as sess:
269 sess.add_all(
270 [tokyo, newyork, toronto, london, dublin, brasilia, quito]
271 )
272
273 sess.commit()
274
275 t = sess.get(WeatherLocation, tokyo.id)
276 assert t.city == tokyo.city
277 assert t.reports[0].temperature == 80.0
278
279 # select across shards
280 asia_and_europe = sess.execute(
281 select(WeatherLocation).filter(
282 WeatherLocation.continent.in_(["Europe", "Asia"])
283 )
284 ).scalars()
285
286 assert {c.city for c in asia_and_europe} == {
287 "Tokyo",
288 "London",
289 "Dublin",
290 }
291
292 # optionally set a shard id for the query and all related loaders
293 north_american_cities_w_t = sess.execute(
294 select(WeatherLocation)
295 .filter(WeatherLocation.city.startswith("T"))
296 .options(set_shard_id("north_america"))
297 ).scalars()
298
299 # Tokyo not included since not in the north_america shard
300 assert {c.city for c in north_american_cities_w_t} == {
301 "Toronto",
302 }
303
304 # the Report class uses a simple integer primary key. So across two
305 # databases, a primary key will be repeated. The "identity_token"
306 # tracks in memory that these two identical primary keys are local to
307 # different shards.
308 newyork_report = newyork.reports[0]

Callers 1

Calls 15

selectFunction · 0.90
set_shard_idClass · 0.90
inspectFunction · 0.90
SessionClass · 0.85
setupFunction · 0.70
WeatherLocationClass · 0.70
ReportClass · 0.70
appendMethod · 0.45
add_allMethod · 0.45
commitMethod · 0.45
getMethod · 0.45
scalarsMethod · 0.45

Tested by

no test coverage detected