smartyfy.mrindigi.com

Python Master Course V2 — 088. Transactions and Consistency

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 09 — DATABASES AND SQLITE · LESSON 088 / 200

Transactions and Consistency

Estimated study: 80–110 minutes · Prerequisite: preceding lesson, functions, exceptions and structured data.

Course hub

Video lesson

Video not yet available; this area is reserved for a verified video link or player.

Learning outcomes

Use commit and rollback to preserve invariants. Explain the technical mechanism, interpret outputs, diagnose failures, test edge cases and apply the skill in a realistic system.

Detailed explanation and architecture

A transaction groups changes into an all-or-nothing unit. SQLite context managers commit on success and roll back on exception, but closing connections remains a separate responsibility.

Implementation sequence: define a contract; model inputs and outputs; apply explicit validation; use standard-library tools where possible; handle expected failures; write tests; document assumptions. Keep persistence or networking separate from business decisions and output formatting.

Professional concerns: predictable error handling, security boundaries, data integrity, performance under realistic load, logging without secrets, and reproducible environments. An example that works once is not automatically a production-ready service.

Understand and apply: Transactions and Consistency

Transactions protect a multi-step invariant

A transaction groups changes that must succeed together. Moving stock from warehouse A to warehouse B requires subtracting from A and adding to B. If only the first operation succeeds, stock disappears. The invariant is that the combined quantity stays the same and neither quantity becomes negative. A transaction gives those statements one commit-or-rollback boundary.

Validate the requested transfer before starting database work: the quantity must be a positive integer and source and destination must differ. Reject booleans if they are not valid counts. Verify that both locations exist within the transaction; the example checks the affected row count and rolls back if either location is missing. Database constraints still protect the stored state if another caller bypasses this function. Keep a transaction short; do not wait for user input or make an unrelated HTTP call while holding it open.

Python example

import sqlite3
from contextlib import closing

def transfer(db, source, destination, amount):
    if type(amount) is not int or amount <= 0 or source == destination:
        raise ValueError("distinct locations and positive integer amount required")
    with db:
        changed = db.execute(
            "UPDATE stock SET qty = qty - ? WHERE place = ? AND qty >= ?",
            (amount, source, amount))
        if changed.rowcount != 1:
            raise ValueError("source missing or insufficient stock")
        changed = db.execute("UPDATE stock SET qty = qty + ? WHERE place = ?",
                             (amount, destination))
        if changed.rowcount != 1:
            raise ValueError("destination missing")

with closing(sqlite3.connect(":memory:")) as db:
    db.execute("CREATE TABLE stock(place TEXT NOT NULL PRIMARY KEY, qty INTEGER NOT NULL CHECK(qty >= 0))")
    with db:
        db.executemany("INSERT INTO stock VALUES (?, ?)", [("A", 10), ("B", 2)])
    transfer(db, "A", "B", 3)
    print(db.execute("SELECT * FROM stock ORDER BY place").fetchall())
    try:
        transfer(db, "A", "MISSING", 2)
    except ValueError as error:
        print(error)
    print(db.execute("SELECT * FROM stock ORDER BY place").fetchall())

Expected output

[('A', 7), ('B', 5)]
destination missing
[('A', 7), ('B', 5)]

The first transfer changes A from ten to seven and B from two to five. Their total stays twelve. During the second transfer, the debit initially matches A, but the destination update affects zero rows. Raising ValueError out of the with block rolls back that earlier debit. The caller catches the error outside the transaction, so the context manager sees the failure and can undo the entire operation.

A boundary is only useful when failures cross it

Catching an error inside a transaction and returning normally can accidentally commit earlier work. If the operation cannot meet its invariant, let an exception escape or explicitly roll back under a clearly designed transaction API. Likewise, nested with db blocks are not independent nested transactions; use savepoints when partial rollback is genuinely required.

The conditional debit combines the stock check and update in one SQL statement. A separate SELECT followed by an unconditional UPDATE can use stale information when multiple writers compete. SQLite serializes writers, but applications still need short transactions, lock-error handling and bounded retries for suitable complete operations. A transaction does not make external email or network calls roll back with the database.

Test the exact available quantity, one more than available, zero, a boolean count, unknown source, unknown destination and a failure after the first update. Compare both rows and their total before and after failure. Call transfer with no unrelated pending transaction: it owns this transaction boundary. This example uses the course’s default legacy sqlite3 behavior; changing to autocommit mode requires redesigning that boundary.

Runnable Python example

Requires Python 3.10+. Save as lesson88.py and run using python or python3. The example uses local or in-memory data and makes no external network request.

import sqlite3
from contextlib import closing
with closing(sqlite3.connect(':memory:')) as c:
    c.execute('CREATE TABLE account(id INTEGER PRIMARY KEY, balance INTEGER NOT NULL)')
    c.execute('INSERT INTO account VALUES (?, ?)', (1, 100))
    c.commit()
    try:
        with c:
            c.execute('UPDATE account SET balance=balance-? WHERE id=?', (30, 1))
            raise ValueError('cancel')
    except ValueError:
        pass
    print(c.execute('SELECT balance FROM account WHERE id=?', (1,)).fetchone()[0])

Expected output:

100

Reasoning walkthrough

Read the imports and setup, identify the data model, then follow each operation until the final result. Change one input and predict the effect before running it. Consider the behavior with empty data, invalid types and missing resources.

Independent validation example

def positive_count(value):
    if not isinstance(value, int) or isinstance(value, bool) or value <= 0:
        raise ValueError("positive integer required")
    return value
assert positive_count(3) == 3
print("Input validated")

Expected: Input validated. Validation belongs at an explicit application boundary.

Guided real-world project

Build an atomic inventory transfer with rollback on insufficient stock.

  1. Write a specification with data schema, required operations and failure conditions.
  2. Implement a minimal solution using small named functions.
  3. Add input validation and deliberate error responses.
  4. Test typical, boundary and invalid inputs.
  5. Verify the result against an independently calculated expectation.
  6. Document setup, limitations and recovery steps.

Acceptance: deterministic tests, correct handling of rejected data, no undocumented destructive behavior, and a clear explanation of architecture. This project is an assignment; its full implementation has not been independently executed.

Common mistakes and debugging

  • Concatenating untrusted input into SQL or URLs without proper encoding and parameterization.
  • Assuming remote services or databases always succeed.
  • Omitting transaction or timeout boundaries.
  • Confusing transport status with validated application data.
  • Testing only success paths and ignoring empty or malformed responses.

To debug, reproduce the failure, inspect the smallest failing input, check types and constraints, and add a regression test.

Practice with explained answers

Make a prediction before opening each answer. Then trace the example and explain the result in your own words.

Why is the final quantity at A still 7 after the failed transfer?

The missing destination triggers ValueError after the debit. That exception exits the transaction block and rolls back the debit, restoring the previously committed quantities.

Why catch ValueError outside with db?

The transaction context manager must observe the exception to roll back automatically. Swallowing it inside the block can make an incomplete operation look successful.

Why combine qty >= amount with the UPDATE?

It tests availability as part of the same write. This avoids a separate read-check-write sequence that could make its decision from stale stock.

Does rollback undo an email sent inside the transaction?

No. It reverses database changes within that transaction. External side effects need a separate coordination design, which is why this function performs only database work.

Which assertion best checks the transfer invariant?

Assert that source plus destination quantity is unchanged on success and both rows are unchanged on failure. Checking only the returned message would miss partial writes.

Mastery checkpoint

Reproduce the sample, explain the design, complete the guided project, document three test cases and identify a realistic failure mode. No video, certificate or account-synced completion is claimed.

Course hub · Previous lesson 87 in hub · Continue with the next published lesson using the lesson navigation.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.