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

Function async_main

examples/asyncio/async_orm.py:48–108  ·  view source on GitHub ↗

Main program function.

()

Source from the content-addressed store, hash-verified

46
47
48async def async_main():
49 """Main program function."""
50
51 engine = create_async_engine(
52 "postgresql+asyncpg://scott:tiger@localhost/test",
53 echo=True,
54 )
55
56 async with engine.begin() as conn:
57 await conn.run_sync(Base.metadata.drop_all)
58 async with engine.begin() as conn:
59 await conn.run_sync(Base.metadata.create_all)
60
61 # expire_on_commit=False will prevent attributes from being expired
62 # after commit.
63 async_session = async_sessionmaker(engine, expire_on_commit=False)
64
65 async with async_session() as session:
66 async with session.begin():
67 session.add_all(
68 [
69 A(bs=[B(), B()], data="a1"),
70 A(bs=[B()], data="a2"),
71 A(bs=[B(), B()], data="a3"),
72 ]
73 )
74
75 # for relationship loading, eager loading should be applied.
76 stmt = select(A).options(selectinload(A.bs))
77
78 # AsyncSession.execute() is used for 2.0 style ORM execution
79 # (same as the synchronous API).
80 result = await session.scalars(stmt)
81
82 # result is a buffered Result object.
83 for a1 in result:
84 print(a1)
85 print(f"created at: {a1.create_date}")
86 for b1 in a1.bs:
87 print(b1)
88
89 # for streaming ORM results, AsyncSession.stream() may be used.
90 result = await session.stream(stmt)
91
92 # result is a streaming AsyncResult object.
93 async for a1 in result.scalars():
94 print(a1)
95 for b1 in a1.bs:
96 print(b1)
97
98 result = await session.scalars(select(A).order_by(A.id))
99
100 a1 = result.first()
101
102 a1.data = "new data"
103
104 await session.commit()
105

Callers 1

async_orm.pyFile · 0.70

Calls 15

create_async_engineFunction · 0.90
async_sessionmakerClass · 0.90
selectinloadFunction · 0.90
async_sessionFunction · 0.85
selectFunction · 0.85
AClass · 0.70
BClass · 0.70
beginMethod · 0.45
run_syncMethod · 0.45
add_allMethod · 0.45
optionsMethod · 0.45
scalarsMethod · 0.45

Tested by

no test coverage detected