- Without SQLAlchemy, we’d only use a DBAPI to establish connections and execute SQL statements. Simple, but not scalable as complexity grows.
- SQLAlchemy offers several layers of abstraction and convenient tools for interacting with a database.
SQLAlchemy vs psycopg2
- SQLAlchemy generates SQL statements
- psycopg2 directly sends SQL statements to the database
- SQLAlchemy depends on psycopg2 or other database drivers to communicate with the database under the hood.
SQLAlchemy lets you traverse through all 3 layers of abstraction to interact with your database
- Can stay on the ORM level
- Can dive into database operations to run customized SQL code specific to the database, on the Expressions level.
- Can write raw SQL to execute, when needed, on the Engine level.
- Can more simply use psycopg2 in this case
Good Design
- Keep your code Pythonic. Work in classes and objects as much as possible.
- Makes switching to a different backend easy in the future
- Avoid writing raw SQL until absolutely necessary.
Layers of SQLAlchemy
- DBAPI: Implements protocol for connecting to a database
- The Dialect: Translates generic SQL instructions to database-specific instructions for the DBAPI + specific backend (MySQL, Postgres, etc.)
- The Connection Pool: Manages a pool of connections that we reuse
- The Engine: Connect to the db
- SQL Expressions: Write SQL using Python expressions
- SQLAlchemy ORM (optional): Write and query Python objects mapped to db tables, generating SQL expressions for you.
SQLAlchemy layers 的图