Skip to main content

SQLAlchemy Fundamentals

Every SQLAlchemy application follows the same workflow.
We’ll understand each of these building blocks one by one in this chapter.

Database URL

Before connecting to a database, SQLAlchemy needs to know:
  • Which database to use
  • Where it is located
  • How to connect
This information is provided using a Database URL.

General Format

To use a specific driver:
The driver is optional. Specify it only when you want SQLAlchemy to use a particular driver.

URL Components

Common URLs

Dialect

A Dialect identifies the database type. Examples:
SQLAlchemy generates the appropriate SQL based on the selected dialect.

Driver

A Driver is the Python library that communicates with the database.
Common drivers:

Engine

The Engine creates and manages database connections.
The Engine is responsible for:
  • Opening connections
  • Managing connection pooling
  • Sending SQL to the database
Think of it as the gateway to the database.

DeclarativeBase

Before defining models, SQLAlchemy needs a place to register them.
Every model inherits from Base.
Base automatically registers every model.

Registry

The collection of registered models is called the Registry.
SQLAlchemy manages the Registry automatically.

Metadata

Metadata stores information about every registered model, including:
  • Table names
  • Columns
  • Primary keys
  • Constraints
  • Relationships
Using Metadata, SQLAlchemy can create all tables.

Session

The Session is SQLAlchemy’s workspace for communicating with the database. Every database operation goes through a Session.

Creating a Session

Create a Session Factory.
Create a Session.
A Session Factory is created once, while Sessions are created whenever database operations are performed.

Git Analogy

Saving Changes

Start tracking a new object.
Save tracked changes.
Discard uncommitted changes.
Close the Session.

Query Execution

Every query follows the same workflow.

Build a Query

Execute the Query

Process the Result

Retrieving Results

Return all objects.
Return the first object.
Return exactly one object.
Return one object or None.
Retrieve directly by primary key.

Why scalars()?

When a query is executed,
execute() returns a Result object, not the actual Student objects.
To extract only the ORM objects, use scalars().
scalars() returns a ScalarResult, which is an iterable of Student objects.
Notice that it is still not a Python list.

Why all()?

Use all() to convert the ScalarResult into a list.
Result:
Without all(), you can still iterate over the results.

Complete Flow

Key Points

  • execute() returns a Result object.
  • scalars() extracts the ORM objects from the Result.
  • scalars() returns a ScalarResult, not a list.
  • all() converts the ScalarResult into a Python list.
  • first(), one(), and one_or_none() retrieve objects in different ways.
get() is a shortcut for retrieving an object using its primary key.

Quick Revision