Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Data consistency in backend systems relies on the ACID guarantees of relational databases (Atomicity, Consistency, Isolation, Durability). In SQLAlchemy, transactions are governed by the Unit of Work pattern through the Session object.
Mastering transaction lifecycles, explicit commits, automated rollbacks, and nested savepoints ensures that database operations either complete in their entirety or leave data completely untouched in the presence of runtime exceptions.
session.begin())In SQLAlchemy 2.0, managing transactions inside a with session.begin(): context manager provides a guarantee:
session.commit() is issued automatically.session.rollback() is executed immediately before the exception propagates out.Consider an inter-account bank transfer. If funds are deducted from Account A, but the network or application crashes before depositing into Account B, money is permanently lost unless wrapped in an atomic transaction:
How data and code flow step-by-step
session.begin_nested())Relational databases support Savepoints within an active transaction. A savepoint allows you to roll back a specific portion of work without aborting the entire outer transaction.
In SQLAlchemy, savepoints are created using session.begin_nested():
| Construct | Mechanism | Scope |
|---|---|---|
with session.begin(): | Automatic commit / rollback | Outer transaction boundary |
session.commit() | Flushes changes and commits transaction | Explicit transaction commit |
session.rollback() | Reverts pending changes to database state | Explicit transaction abort |
session.begin_nested() | Emits SQL SAVEPOINT | Nested sub-transaction rollback |
session.flush() | Sends pending SQL to DB without committing | In-flight constraint validation |
session.flush() with session.commit()session.flush(): Sends SQL statements to the database engine and populates generated IDs, but keeps the transaction open.session.commit(): Persists the transaction permanently to disk.Once an exception occurs inside a transaction, the session enters an inactive state. Any subsequent query raises an InvalidRequestError until session.rollback() is called.
Demonstrate transaction rollback in SQLAlchemy by attempting a dual-account fund transfer where an error occurs midway through the operation.
What happens if an unhandled exception occurs inside a with session.begin(): block? A. The database drops all tables. B. SQLAlchemy automatically executes session.rollback(), reverting all uncommitted modifications made during that block, before propagating the exception. C. The partial changes are permanently written to disk. D. The process freezes.
session.begin() context manager automatically issues a rollback when an unhandled exception escapes the block, ensuring that no partially written data persists.What is the purpose of session.begin_nested() in SQLAlchemy? A. To open a separate operating system process. B. To establish a database Savepoint within an existing transaction, allowing partial rollback of sub-operations without aborting the parent transaction. C. To create a multi-threaded database server. D. To disable all database locks.
session.begin_nested() uses SQL savepoints to allow localized sub-transaction rollbacks while keeping the surrounding outer transaction intact.What is the difference between session.flush() and session.commit()? A. flush() deletes the database, while commit() saves it. B. flush() communicates pending SQL operations to the database transaction buffer without closing the transaction, while commit() permanently finalizes the transaction on disk. C. commit() only works on SQLite. D. There is no difference; they are aliases.
session.flush() pushes queued SQL DML statements (INSERT, UPDATE, DELETE) to the database process so generated IDs and constraints can be evaluated, while session.commit() permanently seals the transaction.Which ACID property guarantees that all database operations in a transaction succeed together or fail together with zero partial state? A. Atomicity B. Consistency C. Isolation D. Durability
What exception is raised by SQLAlchemy when an operation violates a unique=True column constraint during flush or commit? A. sqlalchemy.exc.IntegrityError B. ValueError C. sqlalchemy.exc.NotFoundError D. KeyError
sqlalchemy.exc.IntegrityError.In the next lesson, we will continue your advanced Python journey with Project: Blogging Platform Database (9: Advanced Database Handling).
👉 Continue to Next Lesson: Project: Blogging Platform Database →
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Relationships in Databases | Project: Blogging Platform Database |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.