SUPPLEMENTAL LIVE LAB / VERSION 1
See what a transaction actually keeps.
Query real disposable SQLite data, provoke a rollback, then inspect an index's actual query plan. No application database or cloud account is used.
For learners who can read Python functions, lists and exceptions. Repair those foundations with functions, validation and errors, and the database-service project. Time estimates are guidance, not a completion promise.
Before you run
Every Run starts a fresh browser-local Python worker and seeds a new in-memory SQLite database. Nothing reaches the product's database; rows vanish after the run. This is not a persistent database console, HTTP service, PostgreSQL lab or cloud sandbox.
One experiment at a time; Stop and leaving the page dispose it. The existing limits remain four seconds,16KiB output,256MiB Python heap and45 seconds for initial loading. There is no network, package installation, interactive stdin, host filesystem or system process access.
Edits and outputs in this supplemental lab are page-local, not cloud-saved or cross-device drafts. Download useful edited programs with their public checks before leaving. Reset asks before replacing edited source. Reading, revealing answers or passing these transparent checks awards no reading milestone, judge acceptance or mastery.
One transaction, two possible endings
This is a conceptual model for the authored example, not an instrumented trace of your edited program.
- Seed and commit three rows.
- Begin a change and tentatively insert a fourth row.
- An exception inside the transaction rolls back: three rows remain.
- A separate successful transaction commits: four rows remain until this disposable database closes.
The real query results below test this reasoning. A Python error after a completed commit cannot retroactively roll that commit back.
Seed a disposable table and inspect real rows
A database table stores rows with named columns. SQL describes which rows you want; a cursor is Python's handle for reading the result. Here each run creates its own in-memory sessions table. It cannot reach CareerPetal's application database, and no data survives the worker's disposal.
SELECT chooses columns, WHERE filters rows, and ORDER BY makes result ordering explicit. Without ORDER BY, row order is not a promise. A question-mark placeholder binds a value separately from SQL text. fetchall returns a list of row tuples; its memory grows with the number of returned rows.
Predict first: With a minimum of 15, which topics appear, and in what order?
lists then testing: 20 and 30 meet the inclusive threshold, while loops at 10 does not. ORDER BY topic sorts the selected rows; insertion order is irrelevant.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Code and output here are page-local and are not saved. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 1 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Inclusive filter and explicit ordering
assert rows == [('lists', 20), ('testing', 30)]
Change one thing, then explain
Change minimum from 15 to 25. Only testing should remain. Change >= to > and use minimum 20 to investigate the inclusive boundary.
Observe rollback separately from a successful commit
A transaction groups changes into one commit or rollback boundary. Commit makes the group durable within this database's lifetime; rollback discards its uncommitted changes. This is not a claim about a distributed service or a crash-proof business workflow.
The connection context manager commits when its block succeeds and rolls back when an exception escapes it. It does not close the connection. Commit the seed first so a later deliberate failure rolls back only the experiment. This example catches only the deliberately injected RuntimeError so it can inspect the resulting rows; real unexpected failures remain visible.
Predict first: Does the row inserted just before the deliberate failure remain? Does the later successful row remain?
The failed block rolls its row back, leaving three seed rows. The next block commits its row, leaving four. If the seed were uncommitted, its rows could roll back too.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Code and output here are page-local and are not saved. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 2 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Failed transaction has no retained row
assert before == 3 and after_rollback == 3
- Successful transaction commits exactly one row
assert after_commit == 4
Change one thing, then explain
Move the failure after the transaction block. The insert has already committed, so a later Python exception cannot undo it. Explain why this differs from an exception inside the block.
Keep SQL-looking input as literal data
SQL text and user-supplied values have different roles. Bind values with placeholders rather than pasting them into an SQL string. A value that contains quotes or SQL-looking text should remain one value, not become instructions.
Placeholders bind values, not table names or SQL operators. Dynamic identifiers need an explicit trusted allowlist. Parameter binding does not validate business rules, grant permissions or make an application universally secure.
Predict first: Will the SQL-looking topic drop the table when bound as a value?
No. SQLite receives the INSERT statement and the topic value separately. The entire topic is stored literally and the table remains queryable.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Code and output here are page-local and are not saved. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 1 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- The complete supplied value remains data
assert stored == [(topic, 20)] and table_count == 1
Change one thing, then explain
Replace the topic with a non-ASCII label or a label containing a quote. Bound values still round-trip. Do not turn the query into an interpolated string.
Optional depth: Inspect actual query plans before and after an index
An index is an additional lookup structure. For a selective equality query, it can avoid checking every table row, at a cost in storage and write maintenance. It does not change the required answer or guarantee that every query becomes faster.
EXPLAIN QUERY PLAN describes SQLite's chosen access strategy; it is not a measured timing or a full execution trace. Plan wording and optimizer choices depend on SQLite's version, schema, statistics and data. A small or unselective query may reasonably use a scan even when an index exists. This fixture has two matching rows among two thousand.
A scan can inspect n rows. A B-tree lookup is commonly described as O(log n + m) lookup/output work for m matches, with additional table lookups when the index is not covering. These are models, not measured latencies. Fetching all results still uses O(m) Python result memory.
Predict first: Should adding the topic index change the returned rows, or only the access strategy?
It should preserve the rows. The plan may change from a table scan to an indexed search; that is evidence of a chosen strategy, not proof of a speedup.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Code and output here are page-local and are not saved. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 2 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- The index does not change query semantics
assert before_rows == after_rows == [(0, 0), (1999, 19)]
- The declared index actually exists
assert 'sessions_topic' in indexes and before_plan and after_plan
Change one thing, then explain
Change the filter to the common topic and compare plans. Then select all rows. Explain why the optimizer might prefer a scan; never infer elapsed-time improvement from the plan label alone.
A core stopping point
You can stop after explaining rows, bound values and rollback versus commit, then complete the guided batch and independent transfer below. Query-plan depth is optional and is not required for a reading tick; this lab creates no reading ticks at all.
Guided practice and transfer
These are public local learning checks, not certified scores. Code and results here are not saved. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Code and output here are page-local and are not saved. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Insert a batch without partial commits
Write add_batch(db, records) for a caller-owned connection. Keep its ownership and transaction boundary explicit.
The contract
- The connection has a sessions table with UNIQUE topic and nonnegative minutes, and no pending transaction. Reject a connection with pending writes without committing or rolling them back.
- records must be a list of two-item tuples: nonblank string topic and exact nonnegative int minutes, excluding bool. Normalize surrounding topic whitespace. Empty input returns0.
- Bind values; return the number inserted only after commit. Invalid input raises ValueError. A database constraint failure propagates sqlite3.IntegrityError and rolls back the entire batch.
- Do not mutate records, close the caller's connection or erase earlier committed rows. Tests use fresh disposable connections; no app database is involved.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Code and output here are page-local and are not saved. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Empty batch and zero minutes
def _batch_db(): db = sqlite3.connect(":memory:") db.execute("CREATE TABLE sessions (topic TEXT UNIQUE, minutes INTEGER CHECK(minutes >= 0))") return db db = _batch_db() try: assert add_batch(db, []) == 0 assert add_batch(db, [(' lists ', 0)]) == 1 assert db.execute('SELECT * FROM sessions').fetchall() == [('lists', 0)] finally: db.close() - Late invalid input creates no row
def _batch_db(): db = sqlite3.connect(":memory:") db.execute("CREATE TABLE sessions (topic TEXT UNIQUE, minutes INTEGER CHECK(minutes >= 0))") return db for invalid in [True, -1, 1.5, '2', None]: db = _batch_db() try: try: add_batch(db, [('valid', 2), ('invalid', invalid)]) except ValueError: pass else: raise AssertionError('Reject invalid minutes') assert db.execute('SELECT COUNT(*) FROM sessions').fetchone()[0] == 0 finally: db.close() - Duplicate-topic constraint rolls back only this batch
def _batch_db(): db = sqlite3.connect(":memory:") db.execute("CREATE TABLE sessions (topic TEXT UNIQUE, minutes INTEGER CHECK(minutes >= 0))") return db db = _batch_db() try: db.execute('INSERT INTO sessions VALUES (?, ?)', ('earlier', 4)) db.commit() try: add_batch(db, [('lists', 1), ('lists', 2)]) except sqlite3.IntegrityError: pass else: raise AssertionError('Propagate the UNIQUE violation') assert db.execute('SELECT * FROM sessions').fetchall() == [('earlier', 4)] finally: db.close() - Values, input and caller connection are preserved
def _batch_db(): db = sqlite3.connect(":memory:") db.execute("CREATE TABLE sessions (topic TEXT UNIQUE, minutes INTEGER CHECK(minutes >= 0))") return db records = [("quote'); --", 2)] before = records.copy() db = _batch_db() try: assert add_batch(db, records) == 1 assert db.execute('SELECT * FROM sessions').fetchall() == records assert records == before db.execute('SELECT 1') finally: db.close() - Reject ambiguous transaction ownership
def _batch_db(): db = sqlite3.connect(":memory:") db.execute("CREATE TABLE sessions (topic TEXT UNIQUE, minutes INTEGER CHECK(minutes >= 0))") return db db = _batch_db() try: db.execute('INSERT INTO sessions VALUES (?, ?)', ('pending', 3)) try: add_batch(db, [('new', 1)]) except ValueError: pass else: raise AssertionError('Reject pending caller writes') assert db.in_transaction assert db.execute('SELECT * FROM sessions').fetchall() == [('pending', 3)] finally: db.close() - Reject malformed record boundaries
def _batch_db(): db = sqlite3.connect(":memory:") db.execute("CREATE TABLE sessions (topic TEXT UNIQUE, minutes INTEGER CHECK(minutes >= 0))") return db for records in [None, ('lists', 2), [()], [('lists',)], [('lists', 2, 3)], [('', 2)], [(None, 2)], [['lists', 2]]]: db = _batch_db() try: try: add_batch(db, records) except ValueError: pass else: raise AssertionError('Reject malformed records') assert db.execute('SELECT COUNT(*) FROM sessions').fetchone()[0] == 0 finally: db.close()
Why validate first if a transaction can roll back?
Validation gives clearer domain failures before SQL and avoids unnecessary writes. It does not eliminate database constraints, races or transaction failures. The transaction still protects all-or-nothing persistence when an insert fails.
Transfer a budget with two dependent updates
Change the requirement: move study minutes between existing budgets without losing or creating minutes on failure.
The contract
- transfer_minutes(db, source, target, amount) accepts a caller-owned connection with no pending transaction and a budgets table. Reject pending transactions without changing them.
- Use distinct nonblank exact string labels; do not normalize existing identities. amount is an exact positive int, excluding bool. Missing budgets or insufficient source minutes raise ValueError.
- Update both rows in one transaction with bound values. A target constraint failure propagates sqlite3.IntegrityError and must undo the source decrement.
- A successful call returns None, preserves the total and leaves the caller's connection open. No account, payment or distributed-transaction guarantee is implied.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Code and output here are page-local and are not saved. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Valid transfer preserves the total
def _budget_db(rows): db = sqlite3.connect(":memory:") db.execute("CREATE TABLE budgets (topic TEXT PRIMARY KEY, minutes INTEGER CHECK(minutes BETWEEN 0 AND 40))") db.executemany("INSERT INTO budgets VALUES (?, ?)", rows) db.commit() return db db = _budget_db([('python', 30), ('sql', 10)]) try: assert transfer_minutes(db, 'python', 'sql', 20) is None assert db.execute('SELECT * FROM budgets ORDER BY topic').fetchall() == [('python', 10), ('sql', 30)] finally: db.close() - Target failure undoes the source change
def _budget_db(rows): db = sqlite3.connect(":memory:") db.execute("CREATE TABLE budgets (topic TEXT PRIMARY KEY, minutes INTEGER CHECK(minutes BETWEEN 0 AND 40))") db.executemany("INSERT INTO budgets VALUES (?, ?)", rows) db.commit() return db db = _budget_db([('python', 30), ('sql', 30)]) try: try: transfer_minutes(db, 'python', 'sql', 20) except sqlite3.IntegrityError: pass else: raise AssertionError('Target maximum should fail') assert db.execute('SELECT * FROM budgets ORDER BY topic').fetchall() == [('python', 30), ('sql', 30)] finally: db.close() - Missing target cannot lose minutes
def _budget_db(rows): db = sqlite3.connect(":memory:") db.execute("CREATE TABLE budgets (topic TEXT PRIMARY KEY, minutes INTEGER CHECK(minutes BETWEEN 0 AND 40))") db.executemany("INSERT INTO budgets VALUES (?, ?)", rows) db.commit() return db db = _budget_db([('python', 30)]) try: try: transfer_minutes(db, 'python', 'missing', 5) except ValueError: pass else: raise AssertionError('Reject a missing target') assert db.execute('SELECT * FROM budgets').fetchall() == [('python', 30)] finally: db.close() - Invalid amounts cannot change balances
def _budget_db(rows): db = sqlite3.connect(":memory:") db.execute("CREATE TABLE budgets (topic TEXT PRIMARY KEY, minutes INTEGER CHECK(minutes BETWEEN 0 AND 40))") db.executemany("INSERT INTO budgets VALUES (?, ?)", rows) db.commit() return db for amount in [True, False, 0, -1, 1.5, '2', 31]: db = _budget_db([('python', 30), ('sql', 0)]) try: try: transfer_minutes(db, 'python', 'sql', amount) except ValueError: pass else: raise AssertionError('Reject invalid or unaffordable amount') assert db.execute('SELECT * FROM budgets ORDER BY topic').fetchall() == [('python', 30), ('sql', 0)] finally: db.close() - Distinct exact labels and missing source
def _budget_db(rows): db = sqlite3.connect(":memory:") db.execute("CREATE TABLE budgets (topic TEXT PRIMARY KEY, minutes INTEGER CHECK(minutes BETWEEN 0 AND 40))") db.executemany("INSERT INTO budgets VALUES (?, ?)", rows) db.commit() return db for source, target in [('python', 'python'), ('', 'sql'), (None, 'sql'), ('missing', 'sql')]: db = _budget_db([('python', 30), ('sql', 0)]) try: try: transfer_minutes(db, source, target, 2) except ValueError: pass else: raise AssertionError('Reject invalid identities') assert db.execute('SELECT * FROM budgets ORDER BY topic').fetchall() == [('python', 30), ('sql', 0)] finally: db.close() - Caller transaction remains pending and unchanged
def _budget_db(rows): db = sqlite3.connect(":memory:") db.execute("CREATE TABLE budgets (topic TEXT PRIMARY KEY, minutes INTEGER CHECK(minutes BETWEEN 0 AND 40))") db.executemany("INSERT INTO budgets VALUES (?, ?)", rows) db.commit() return db db = _budget_db([('python', 30), ('sql', 0)]) try: db.execute('UPDATE budgets SET minutes = ? WHERE topic = ?', (29, 'python')) try: transfer_minutes(db, 'python', 'sql', 2) except ValueError: pass else: raise AssertionError('Reject an already active transaction') assert db.in_transaction assert db.execute('SELECT * FROM budgets ORDER BY topic').fetchall() == [('python', 29), ('sql', 0)] finally: db.close()
Why does a successful first UPDATE not mean a successful transfer?
The business operation needs both updates. A missing target or a constraint can fail after the decrement. Commit only after both succeed; otherwise rollback must restore the source. This local database transaction does not coordinate external messages or another service.