Main program function.
()
| 46 | |
| 47 | |
| 48 | async 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 |
no test coverage detected