fastapi-sqlalchemy-asyncpg icon indicating copy to clipboard operation
fastapi-sqlalchemy-asyncpg copied to clipboard

add SQLAlchemy 2.0

Open grillazz opened this issue 2 years ago • 1 comments

grillazz avatar Feb 17 '23 11:02 grillazz

Doing performance improvements is the best way to learn how a tool actually works. I've used SQLAlchemy with Postgres and FastAPI for the last few months and I've learned that:

  1. Postgres does not automatically add indexes on foreign key and neither SQLAlchemy (Django, the other ORM I've used before did that by default). So add index=True on your foreign keys if necessary.

  2. You can define column properties with scalar subqueries outside the model definition: https://docs.sqlalchemy.org/en/20/orm/mapped_sql_expr.html#adding-column-property-to-an-existing-declarative-mapped-class

  3. I've also discovered query expressions, they are a saver for complex queries: https://docs.sqlalchemy.org/en/20/orm/queryguide/columns.html#loading-arbitrary-sql-expressions-onto-objects

  4. Extremely important for heavy queries how the relationship loading is done: https://docs.sqlalchemy.org/en/20/orm/queryguide/relationships.html

  5. If you are migration to 2.0, this is the holy bible: https://docs.sqlalchemy.org/en/14/changelog/migration_20.html#migration-orm-usage

I wonder why there was a need to create tools with yaml and adopt configuration engineering, when SQLAlchemy has a great choice of database drivers, it offers not only schema validation - but it enforces good data modeling practices and it provides a nice ORM to work with.

grillazz avatar Jun 21 '23 10:06 grillazz