MCPcopy
hub / github.com/sqlalchemy/sqlalchemy / async_main

Function async_main

examples/asyncio/gather_orm_statements.py:66–107  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

64
65
66async def async_main():
67 engine = create_async_engine(
68 "postgresql+asyncpg://scott:tiger@localhost/test",
69 echo=True,
70 )
71
72 async with engine.begin() as conn:
73 await conn.run_sync(Base.metadata.drop_all)
74 await conn.run_sync(Base.metadata.create_all)
75
76 async_session = async_sessionmaker(engine, expire_on_commit=False)
77
78 async with async_session() as session, session.begin():
79 session.add_all([A(data="a_%d" % i) for i in range(100)])
80
81 statements = [
82 select(A).where(A.data == "a_%d" % random.choice(range(100)))
83 for i in range(30)
84 ]
85
86 frozen_results = await asyncio.gather(
87 *(
88 run_out_of_band(async_session, statement)
89 for statement in statements
90 )
91 )
92 results = [
93 # merge_results means the ORM objects from the result
94 # will be merged back into the original session.
95 # load=False means we can use the objects directly without
96 # re-selecting them. however this merge operation is still
97 # more expensive CPU-wise than a regular ORM load because the
98 # objects are copied into new instances
99 (
100 await session.run_sync(
101 merge_frozen_result, statement, result, load=False
102 )
103 )()
104 for statement, result in zip(statements, frozen_results)
105 ]
106
107 print(f"results: {[r.all() for r in results]}")
108
109
110asyncio.run(async_main())

Callers 1

Calls 11

create_async_engineFunction · 0.90
async_sessionmakerClass · 0.90
async_sessionFunction · 0.85
selectFunction · 0.85
run_out_of_bandFunction · 0.85
AClass · 0.70
beginMethod · 0.45
run_syncMethod · 0.45
add_allMethod · 0.45
whereMethod · 0.45
allMethod · 0.45

Tested by

no test coverage detected