What are sessions and transactions in SqlAlchemy?

Key takeaways:

  • Sessions represent a connection to the database, track changes, and manage transactions.

  • Transactions ensure data integrity by treating a series of database actions as a single unit of work.

  • Sessions are containers for transactions, and transactions are started and managed within sessions.

  • SQLAlchemy provides two types of transactions that allow developers flexibility in managing database operations:

    • Implicit transactions—automatically managed by SQLAlchemy.

    • Explicit transactions—manually controlled by the developer.

In SQLAlchemy, sessions and transactions are fundamental concepts that manage database interactions and ensure data integrity.

A session represents a connection to the database and encapsulates several operations into a single unit of work. Conversely, a transaction is a series of database actions handled as a single work unit, ensuring consistency and atomicity.

These concepts are crucial for developing reliable and scalable database applications in Python using SQLAlchemy.

Sessions in SQLAlchemy

A session in SQLAlchemy acts as a workspace for database operations, tracking and controlling modifications to database objects before they are committed or discarded. The session abstracts the complexity of database communication by providing a single interface for interacting with the database.

Key concepts

  • Creation: The sessionmaker or scoped_session utilities are used to instantiate a session.

  • Usage: Database operations are performed within the scope of the session.

  • Commit: Modifications made during the session are stored in the database and made permanent.

  • Rollback: The session can be rolled back to its starting point, reversing any ongoing actions in the event of errors or unwanted modifications.

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# Create engine
engine = create_engine('sqlite:///example.db')
# Create session
Session = sessionmaker(bind=engine)
session = Session()
# Perform database operations within the session
# (e.g., querying, adding, updating, deleting objects)
  • Identity map: To guarantee that a single Python object represents every database object in a session, SQLAlchemy uses an identity map inside of sessions. Data integrity is guaranteed, and discrepancies are avoided. For example, when inserting a new entry, the identity map ensures that no duplicate entry is added.

  • Unit of work: Sessions function according to the unit of work pattern, which treats each database change made during a session as a logical transaction. As a result, atomicity, consistency, isolation, and durability, or ACID properties, are made possible.

Transactions in SQLAlchemy

In SQLAlchemy, a transaction is a series of database actions handled as a single work unit. By enforcing the ACID principles, transactions offer a way to guarantee data consistency and integrity.

Key concepts

  • Transaction management: The begin, commit, and rollback functions in SQLAlchemy enable explicit transaction management:

# Begin transaction
transaction = session.begin()
try:
# Perform database operations within the transaction
# (e.g., adding, updating, deleting objects)
# Commit transaction
session.commit()
except:
# Rollback transaction in case of error
session.rollback()
raise
  • Isolation levels: SQLAlchemy supports different isolation levels for transactions, allowing developers to control the visibility and concurrency of database operations.

  • Nested transactions: SQLAlchemy gives better control over database tasks. It lets you use transactions inside sessions, but not all databases allow this. The way nested transactions work depends on the database engine.

Types of transactions

There are two types of transactions in SQLAlchemy:

  • Implicit transactions: Automatically handled by SQLAlchemy when operations are performed.

  • Explicit transactions: Manually managed by the developer using begin, commit, and rollback methods.

Code example

Here is a code example of sessions and transactions working in sync:

# Create a session factory using the sessionmaker class in SQLAlchemy
Session = sessionmaker(bind=engine)
# Use the session factory to create a session
session = Session()
try:
# Begin transaction
transaction = session.begin()
# Perform database operations within the transaction
new_user = User(name='john', fullname='John Doe', nickname='johnny')
session.add(new_user)
# Commit the transaction
session.commit()
print("New user added and committed to the database.")
# Query the database
user = session.query(User).filter_by(name='john').first()
print(f"User retrieved: {user.fullname} ({user.nickname})")
# Update the user
user.nickname = 'john_the_doe'
session.commit()
print("User updated and committed to the database.")
except Exception as e:
# Rollback the transaction in case of an error
session.rollback()
print(f"An error occurred: {e}")
finally:
# Close the session
session.close()

You can play around with the coding environment above to force-produce an error and see the working and benefits of SQLAlchemy sessions and transactions in action.

Sessions and transactions

Sessions and transactions are interrelated concepts. Transactions can be started within sessions, and session methods like session.commit() and session.rollback() control the transaction flow.

Additional session methods

  • session.flush(): Flushes changes to the database but does not commit.

  • session.execute(): Executes a raw SQL query.

  • session.add(): Adds an object to the session.

  • session.delete(): Deletes an object from the session.

  • session.query(): Queries the database.

Conclusion

In SQLAlchemy, sessions and transactions are essential components that control database interactions and guarantee data integrity. Sessions group database activities into a single, coherent unit of work, and transactions control the consistency and atomicity of database changes.

In SQLAlchemy, sessions and transactions help manage how the database works. A session groups tasks into one unit, making it easier to keep track of changes. Transactions make sure all changes are complete and correct.

Understanding these concepts is crucial to developing dependable and scalable database applications in Python using SQLAlchemy.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved