SQLAlchemy‘s Layers of Abstraction

  • 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

  1. DBAPI: Implements protocol for connecting to a database
  2. The Dialect: Translates generic SQL instructions to database-specific instructions for the DBAPI + specific backend (MySQL, Postgres, etc.)
  3. The Connection Pool: Manages a pool of connections that we reuse
  4. The Engine: Connect to the db
  5. SQL Expressions: Write SQL using Python expressions
  6. SQLAlchemy ORM (optional): Write and query Python objects mapped to db tables, generating SQL expressions for you.

SQLAlchemy layers 的图
请添加图片描述

请添加图片描述

猜你喜欢

转载自blog.csdn.net/BSCHN123/article/details/121220082