Skip to content

Examples and tests for async support in SQLModel #471

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/advanced/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ The **Advanced User Guide** is gradually growing, you can already read about som
At some point it will include:

* How to use `async` and `await` with the async session.
* See: `docs_src\tutorial_async` for working examples as equivalents to `docs_src\tutorial`
* Also see `tests\tutorial_async` for fully functioning pytest tests against the examples
*
* These examples and tests are also passing `mypy` static checking if #PR58 addressing Issue#54 is included
* also note the TODO: for PR#435 subclassing the SQLAlchemey requirements fully into SQLModel
*
* How to run migrations.
* How to combine **SQLModel** models with SQLAlchemy.
* ...and more. 🤓
1 change: 1 addition & 0 deletions docs_src/tutorial_async/.python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.10.7
Empty file.
Empty file.
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import asyncio
from typing import Annotated, Optional

# TODO change when https://github.com/tiangolo/sqlmodel/pull/435 accepted
# TODO replace following 3 lines with:
# ------ from sqlmodel import AsyncSession, create_async_engine, Field, SQLModel, select
from sqlalchemy.ext.asyncio import create_async_engine
from sqlmodel import Field, SQLModel


class Team(SQLModel, table=True):
id: Annotated[int, Field(primary_key=True)]
name: Annotated[str, Field(index=True)]
headquarters: str


class Hero(SQLModel, table=True):
id: Annotated[int, Field(primary_key=True)]
name: Annotated[str, Field(index=True)]
secret_name: str
age: Annotated[Optional[int], Field(default_factory=lambda: None, index=True)]

team_id: Annotated[
Optional[int], Field(default_factory=lambda: None, foreign_key="team.id")
]


sqlite_file_name = "database.db"
sqlite_url = f"sqlite+aiosqlite:///{sqlite_file_name}"

engine = create_async_engine(sqlite_url, echo=True)


async def create_db_and_tables() -> None:
meta = SQLModel.metadata

async with engine.begin() as conn:
await conn.run_sync(meta.drop_all)
await conn.run_sync(meta.create_all)


async def main() -> None:
await create_db_and_tables()


if __name__ == "__main__":
asyncio.run(main())
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import asyncio
from typing import Annotated, Optional

# TODO change when https://github.com/tiangolo/sqlmodel/pull/435 accepted
# TODO replace following 3 lines with:
# ------ from sqlmodel import AsyncSession, create_async_engine, Field, SQLModel, select
from sqlalchemy.ext.asyncio import create_async_engine
from sqlmodel import Field, SQLModel
from sqlmodel.ext.asyncio.session import AsyncSession


class Team(SQLModel, table=True):
id: Annotated[int, Field(primary_key=True)]
name: Annotated[str, Field(index=True)]
headquarters: str


class Hero(SQLModel, table=True):
id: Annotated[int, Field(primary_key=True)]
name: Annotated[str, Field(index=True)]
secret_name: str
age: Annotated[Optional[int], Field(default_factory=lambda: None, index=True)]

team_id: Annotated[
Optional[int], Field(default_factory=lambda: None, foreign_key="team.id")
]


sqlite_file_name = "database.db"
sqlite_url = f"sqlite+aiosqlite:///{sqlite_file_name}"

engine = create_async_engine(sqlite_url, echo=True)


async def create_db_and_tables() -> None:
meta = SQLModel.metadata

async with engine.begin() as conn:
await conn.run_sync(meta.drop_all)
await conn.run_sync(meta.create_all)


async def create_heroes() -> None:

async with AsyncSession(engine, expire_on_commit=False) as session:
team_preventers = Team(name="Preventers", headquarters="Sharp Tower")
team_z_force = Team(name="Z-Force", headquarters="Sister Margaret’s Bar")
session.add(team_preventers)
session.add(team_z_force)
await session.commit()

hero_deadpond = Hero(
name="Deadpond", secret_name="Dive Wilson", team_id=team_z_force.id
)
hero_rusty_man = Hero(
name="Rusty-Man",
secret_name="Tommy Sharp",
age=48,
team_id=team_preventers.id,
)
hero_spider_boy = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
session.add(hero_deadpond)
session.add(hero_rusty_man)
session.add(hero_spider_boy)
await session.commit()

await session.refresh(hero_deadpond)
await session.refresh(hero_rusty_man)
await session.refresh(hero_spider_boy)

print("Created hero:", hero_deadpond)
print("Created hero:", hero_rusty_man)
print("Created hero:", hero_spider_boy)

hero_spider_boy.team_id = team_preventers.id
session.add(hero_spider_boy)
await session.commit()
await session.refresh(hero_spider_boy)
print("Updated hero:", hero_spider_boy)

hero_spider_boy.team_id = None
session.add(hero_spider_boy)
await session.commit()
await session.refresh(hero_spider_boy)
print("No longer Preventer:", hero_spider_boy)


async def main() -> None:
await create_db_and_tables()
await create_heroes()


if __name__ == "__main__":
asyncio.run(main())
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import asyncio
from typing import Annotated, Optional

# TODO change when https://github.com/tiangolo/sqlmodel/pull/435 accepted
# TODO replace following 3 lines with:
# ------ from sqlmodel import AsyncSession, create_async_engine, Field, SQLModel, select
from sqlalchemy.ext.asyncio import create_async_engine
from sqlmodel import Field, SQLModel
from sqlmodel.ext.asyncio.session import AsyncSession


class Team(SQLModel, table=True):
id: Annotated[int, Field(primary_key=True)]
name: Annotated[str, Field(index=True)]
headquarters: str


class Hero(SQLModel, table=True):
id: Annotated[int, Field(primary_key=True)]
name: Annotated[str, Field(index=True)]
secret_name: str
age: Annotated[Optional[int], Field(default_factory=lambda: None, index=True)]

team_id: Annotated[
Optional[int], Field(default_factory=lambda: None, foreign_key="team.id")
]


sqlite_file_name = "database.db"
sqlite_url = f"sqlite+aiosqlite:///{sqlite_file_name}"

engine = create_async_engine(sqlite_url, echo=True)


async def create_db_and_tables() -> None:
meta = SQLModel.metadata

async with engine.begin() as conn:
await conn.run_sync(meta.drop_all)
await conn.run_sync(meta.create_all)


async def create_heroes() -> None:

async with AsyncSession(engine, expire_on_commit=False) as session:
team_preventers = Team(name="Preventers", headquarters="Sharp Tower")
team_z_force = Team(name="Z-Force", headquarters="Sister Margaret’s Bar")
session.add(team_preventers)
session.add(team_z_force)
await session.commit()

hero_deadpond = Hero(
name="Deadpond", secret_name="Dive Wilson", team_id=team_z_force.id
)
hero_rusty_man = Hero(
name="Rusty-Man",
secret_name="Tommy Sharp",
age=48,
team_id=team_preventers.id,
)
hero_spider_boy = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
session.add(hero_deadpond)
session.add(hero_rusty_man)
session.add(hero_spider_boy)
await session.commit()

await session.refresh(hero_deadpond)
await session.refresh(hero_rusty_man)
await session.refresh(hero_spider_boy)

print("Created hero:", hero_deadpond)
print("Created hero:", hero_rusty_man)
print("Created hero:", hero_spider_boy)


async def main() -> None:
await create_db_and_tables()
await create_heroes()


if __name__ == "__main__":
asyncio.run(main())
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import asyncio
from typing import Annotated, Optional

# TODO change when https://github.com/tiangolo/sqlmodel/pull/435 accepted
# TODO replace following 3 lines with:
# ------ from sqlmodel import AsyncSession, create_async_engine, Field, SQLModel, select
from sqlalchemy.ext.asyncio import create_async_engine
from sqlmodel import Field, SQLModel, select
from sqlmodel.ext.asyncio.session import AsyncSession


class Team(SQLModel, table=True):
id: Annotated[int, Field(primary_key=True)]
name: Annotated[str, Field(index=True)]
headquarters: str


class Hero(SQLModel, table=True):
id: Annotated[int, Field(primary_key=True)]
name: Annotated[str, Field(index=True)]
secret_name: str
age: Annotated[Optional[int], Field(default_factory=lambda: None, index=True)]

team_id: Annotated[
Optional[int], Field(default_factory=lambda: None, foreign_key="team.id")
]


sqlite_file_name = "database.db"
sqlite_url = f"sqlite+aiosqlite:///{sqlite_file_name}"

engine = create_async_engine(sqlite_url, echo=True)


async def create_db_and_tables() -> None:
meta = SQLModel.metadata

async with engine.begin() as conn:
await conn.run_sync(meta.drop_all)
await conn.run_sync(meta.create_all)


async def create_heroes() -> None:

async with AsyncSession(engine, expire_on_commit=False) as session:
team_preventers = Team(name="Preventers", headquarters="Sharp Tower")
team_z_force = Team(name="Z-Force", headquarters="Sister Margaret’s Bar")
session.add(team_preventers)
session.add(team_z_force)
await session.commit()

hero_deadpond = Hero(
name="Deadpond", secret_name="Dive Wilson", team_id=team_z_force.id
)
hero_rusty_man = Hero(
name="Rusty-Man",
secret_name="Tommy Sharp",
age=48,
team_id=team_preventers.id,
)
hero_spider_boy = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
session.add(hero_deadpond)
session.add(hero_rusty_man)
session.add(hero_spider_boy)
await session.commit()

await session.refresh(hero_deadpond)
await session.refresh(hero_rusty_man)
await session.refresh(hero_spider_boy)

print("Created hero:", hero_deadpond)
print("Created hero:", hero_rusty_man)
print("Created hero:", hero_spider_boy)


async def select_heroes() -> None:
async with AsyncSession(engine) as session:
statement = select(Hero, Team).where(Hero.team_id == Team.id)
results = await session.exec(statement)
for hero, team in results:
print("Hero:", hero, "Team:", team)


async def main() -> None:
await create_db_and_tables()
await create_heroes()
await select_heroes()


if __name__ == "__main__":
asyncio.run(main())
Loading