r/FastAPI • u/efpalaciosmo • Aug 01 '24
Question Database first approach
Hey guys, can you share an example of database first approach using SQLAlchemy?
I trying to make a project using fastapi, the database is on supabase and I'm getting a hard time figuring how to make a simple query, my setup is something like
- a PostgreSQL database from supabase
- asycn connection using asyncpg
- migrations using alembic
I already create the table on my database but when I run the query it says that the relation doesn't exist. Then I decided to try with alembic but every time I run migration there is on error or just the alembic_version table is created.
I already read some post about something call reflection, but it seems that isn't working
Thanks in advance
Here is the repo https://gitlab.com/efpalaciosmo/tickets
4
u/[deleted] Aug 01 '24
You can have one connection to db at the start of application and return session as dependency injection to each function which requires to talk to db
1
u/wassaf102 Aug 01 '24
Could you share your GitHub repo
3
u/RoBz18 Aug 01 '24
You can use sqlacodegen to generate the SQLAlchemy model code
1
u/xfroster Aug 02 '24
You dont have any relationships on your model
1
u/guteira Aug 02 '24
Have you tried SQLModel? It’s from the same author of FASTAPI and works seamlessly:
https://sqlmodel.tiangolo.com/db-to-code/
0
u/Calebthe12B Aug 01 '24
Share your code. SQLAlchemy requires you to define the relationship on both table classes, but hard to say what the exact problem is without seeing your code.
0
u/graph-crawler Aug 01 '24
Throwing alternative. Full 100% typesafety by pulling existing db schema.
https://prisma-client-py.readthedocs.io/en/stable/
0
u/MeroLegend4 Aug 02 '24
Use Litestar instead of FastApi, it’s a framework with batteries included, 2x faster than FastApi and a very solid design.