8.1. SQLAlchemy About
ORM converts Python objects to database rows
ORM converts database rows to Python objects
ORM provides abstraction over database layer
ORM allows for object like interaction with database
ORM provides ability to migrate database schema
SQAlchemy is the most frequently used database ORM in Python [5]
It's not because you don't know how to write the query, it is because at the large scale you have to automate. It is about scaling up something which is very repetitive to do it by hand.
—Mike Bayer, SQLAlchemy creator [4]
8.1.1. ORM Pros
Support for database switching with minimal effort
Refactoring support (embedded SQL is not easily refactorable)
1-to-1 relation of Python class to database table
Historical migration and change history
8.1.2. ORM Cons
Some queries could be not well optimized
Another layer of abstraction
Another dependency
8.1.3. Database Support
SQLite3
PostgreSQL
Oracle
MySQL / MariaDB
MSSQL
8.1.4. Installation
$ pip install sqlalchemy
>>> import sqlalchemy
>>>
>>>
>>> sqlalchemy.__version__ > '1.4'
True
8.1.5. Architecture
Core
ORM
Plugin structure with injection points
8.1.6. 1.x vs. 2.x
future=True
flag tocreate_engine()
On 2023-01-26 SQLAlchemy 2.0 has been released [8]
For SQLAlchemy 1.4, the RemovedIn20Warning
deprecation class is emitted
only when an environment variable SQLALCHEMY_WARN_20
is set to either of
true
or 1
.
SQLALCHEMY_WARN_20=1 python -W always::DeprecationWarning myfile.py
8.1.7. Good Practices
Project Structure
What is the SQLAlchemy project layout
Where to store configuration (host, port, schema, username, password)
8.1.8. Alternative ORMs
8.1.9. References
8.1.10. References
Bayer, Mike. SQLAlchemy 2.0 - The One-Point-Four-Ening 2021. Year: 2022. Retrieved: 2022-01-26. URL: https://www.youtube.com/watch?v=1Va493SMTcY
Kennedy, Michael and Bayer, Mike. Year: 2021. Retrieved: 2022-01-30. URL: https://www.youtube.com/watch?v=q5Iv6RUxKC8
JetBrains s.r.o. https://www.jetbrains.com/lp/python-developers-survey-2020/#FrameworksLibraries
Phan, Manh. Unit of Work Pattern. Year: 2019. Retrieved: 2022-01-30. URL: https://ducmanhphan.github.io/
Ashif Iqbal Laskar. Unit-of-Work-Design-Pattern. Year: 2021. Retrieved: 2022-01-30. URL: http://www.ashifiqbal.com/technology/entity-framework/unit-of-work-design-pattern/
Bayer, Mike. SQLAlchemy 2.0.0 Released. Year: 2023. Retrieved: 2023-01-26. URL: https://www.sqlalchemy.org/blog/2023/01/26/sqlalchemy-2.0.0-released/