CS 220 — Web Applications, SQL and Software Engineering · Weeks 9–11
Transactions, parameterization and authorization
Full teaching sequence and cumulative subject work
Study the complete on-site source sections below, then work the original example, changed-condition problem and transfer laboratory. Complete CS50 SQL Writing, Viewing, Optimizing and Scaling. Study CS50 Web SQL, Models and Migrations and Scalability and Security. Explain atomicity and access policy separately.
Transactions and object-level authorization
Parameterization prevents submitted values from being interpreted as query syntax. It does not decide whether the requester may access the selected row. Constrain data operations by a trusted principal or by a verified permission relation. Prefer one bounded operation over a check followed by an unconstrained action that can race with changes.
A transaction groups database effects, but its isolation level and constraints determine which concurrent histories are allowed. A read-check-write sequence can oversell a resource if two workers both observe the same availability. Make the invariant enforceable at the update or constraint boundary.
Worked problem
Inventory is 1. Two transactions each read 1, approve one sale, and write 0. Both report success. Give an update that makes the final remaining inventory meaningful.
Trace the complete reasoning
The application authorized two sales from one unit even though the stored count ends at zero. The final value conceals the lost coordination.
Use an atomic conditional decrement such as UPDATE inventory SET quantity=quantity−1 WHERE id=? AND quantity>=1, within the sale transaction.
Require exactly one affected row before recording success. If no row changes, report unavailability and do not create a successful sale.
Rollback the decrement if the required local sale record cannot be committed. External payment still needs a separately coordinated workflow and retry policy.
Independent transfer problem
A parameterized order lookup filters only id. A user guesses another customer’s valid id. What additional condition is needed?
Compare the transfer solution
Scope the lookup or update to the verified customer, such as id=? AND customer_id=?, or a verified role/permission join. Derive the identity from trusted authentication, not a client field. Parameterization remains necessary but does not supply object-level authorization.
Learning objectives
- Explain and trace the mechanisms in transactions, parameterization and authorization.
- Apply the method to the worked example and changed-condition exercise.
- Identify assumptions, failure cases and the evidence needed to justify a result.
Study the mechanism
A transaction groups related changes into an operation with defined consistency behavior. If money is transferred, decrementing one account and incrementing the other must not leave a half-completed business operation. Transactions do not eliminate the need for constraints, isolation choices or correct application logic. A concurrency defect may appear only when two requests read the same old state before either writes.
Parameterized statements separate SQL structure from values. String concatenation lets submitted text change query syntax, creating injection risk. Parameters address values; dynamic column names and ordering still require allowlists or structured APIs. Parameterization does not decide who may access the resulting row. Authentication identifies a caller; authorization checks whether that caller may perform this operation on this object.
Never trust a customer_id submitted by the browser as proof of ownership. Bind requests to the authenticated identity and enforce object-level access on the server. A hidden admin button is presentation, not security. Test two fictional accounts and attempt to read or edit the other's order. Also examine logs and error messages: denying a write while revealing another person's confidential record is still a disclosure.
Worked example
import sqlite3
connection = sqlite3.connect(":memory:")
connection.execute("CREATE TABLE orders(id INTEGER PRIMARY KEY, owner TEXT, cents INTEGER)")
connection.execute("INSERT INTO orders VALUES(1, 'member-a', 500)")
def owned_order(order_id, verified_member_id):
return connection.execute(
"SELECT id, cents FROM orders WHERE id = ? AND owner = ?",
(order_id, verified_member_id)).fetchone()
assert owned_order(1, "member-a") == (1, 500)
assert owned_order(1, "member-b") is NoneThe query constrains both identifier and verified owner. The caller identity must come from a trusted session verification process, not a body field. Parameters prevent values from becoming query syntax. The in-memory example demonstrates object-level filtering and intentionally omits production session and connection management.
Check your understanding
What does parameterization fail to establish by itself?
- Whether the caller is allowed to access the selected row
- Separation of SQL values from syntax
- Correct handling of quoted value text
Answer and reasoning for every option
Correct: Whether the caller is allowed to access the selected row Authorization requires an independent access-control decision.
Reconsider: Separation of SQL values from syntax Value separation is exactly what parameterized statements provide.
Reconsider: Correct handling of quoted value text Proper parameter binding handles quotes without manual concatenation.
Transfer laboratory: The lost update
Two requests read stock 5, both sell 4 and both write stock 1. Explain the inconsistency and describe an atomic alternative.
Work through the full solution
Eight units were sold from five while the stored count suggests only four sold. Use an atomic conditional decrement such as UPDATE inventory SET stock=stock−4 WHERE id=? AND stock>=4, then check the affected-row count inside the appropriate transaction. Isolation and locking policies depend on the database. Do not rely on a browser-side availability check.
Evidence of understanding
Identify overselling, require an atomic condition and check whether the write actually occurred.
Complete on-site teaching readings
These are full attributed source sections, not previews. Read them alongside the original Academy explanation and code.
- Cross-site request forgery (CSRF) · Mozilla Contributors
- Cross-site scripting (XSS) · Mozilla Contributors
- 3.4. Transactions # · The PostgreSQL Global Development Group and The Regents of the University of California
- 3.2. Views # · The PostgreSQL Global Development Group and The Regents of the University of California
- 13.2. Transaction Isolation # · The PostgreSQL Global Development Group and The Regents of the University of California
- 5.8. Privileges # · The PostgreSQL Global Development Group and The Regents of the University of California
- PREPARE · The PostgreSQL Global Development Group and The Regents of the University of California
- 11.1. Introduction # · The PostgreSQL Global Development Group and The Regents of the University of California
- 14.1. Using EXPLAIN # · The PostgreSQL Global Development Group and The Regents of the University of California
- Django Tutorial Part 5: Creating our home page · Mozilla Contributors
- Django Tutorial Part 6: Generic list and detail views · Mozilla Contributors
- Django Tutorial Part 7: Sessions framework · Mozilla Contributors
- Django Tutorial Part 8: User authentication and permissions · Mozilla Contributors
- Django Tutorial Part 9: Working with forms · Mozilla Contributors
Open the complete practice sequence and cumulative assessment →