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

Function main

examples/sharding/separate_tables.py:265–334  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

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

Callers 1

separate_tables.pyFile · 0.70

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