SQL transactions and secure input boundaries
Store data with parameterised queries and explicit transaction behaviour.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners who can read small Python functions and want to apply the listed foundations.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Explain bind values, never compose them as sql
- Apply choose a transaction boundary
- Reason about secure coding boundaries
Bind values, never compose them as SQL
A parameterized query keeps SQL instructions separate from supplied values. A placeholder represents data, not a table name or a fragment of SQL.
Understand first
A name containing quotes should be searched as a name. Joining it into query text can change the instruction instead of supplying a value.
Words you will see
- SQL
- A language for querying and changing relational data.
- Placeholder
- A marker whose value is bound separately by the database driver.
- Identifier
- A structural SQL name such as a table or column name.
Keep the query fixed
The fixture creates a private in-memory table and inserts two values using executemany with placeholders. A search string resembling SQL syntax is still one bound text value. It matches no stored name and cannot broaden the WHERE condition.
The one-element parameter tuple needs its trailing comma: (value,) is a tuple, while (value) is just parentheses around a value. Placeholder syntax differs across database drivers, so follow the chosen driver's API.
Binding is not authorization
A safe value binding does not decide whether a caller may read a record. Apply identity and permission checks separately. A placeholder also cannot choose a table or ORDER BY keyword; use fixed statements or a strict allowlist for those structural choices.
Only an isolated SQLite memory database is used here. Host Python normally includes sqlite3, but browser builds may omit it. Show the real error if unavailable. This fixture does not access production data or demonstrate every database's concurrency rules.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
connection = sqlite3.connect(":memory:")Create a connection that cannot read a production database.
connection.execute("CREATE TABLE names (name TEXT)")Create the fixture's table.
rows = connection.execute("SELECT name FROM names WHERE name = ?", (value,)).fetchall()Bind the entire supplied string as data.
connection.close()Release the connection even if a statement fails.
Parameterised queries keep a value separate from SQL syntax. Placeholders bind values, not table names or keywords; dynamic identifiers need a strict allowlist or another safe API. Parsing a value successfully is not the same as authorising the operation.
Conceptual SQL boundary
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- Fixed instructionSELECT name FROM names WHERE name = ?
- Separate valueDriver binds one text value, even if it resembles SQL.
- ResultOnly matching rows are returned; authorization remains separate.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. 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.
Change one thing; explain the difference.
Search an existing name.
Try: Set value to "Ada".
Exactly Ada is returned.
Add a quoted name.
Try: Insert ("O'Neil",) with the existing parameterized insert form.
The quote is stored as data without hand-built escaping.
Before you move on
Can SELECT ? FROM names use a parameter to select an arbitrary caller-named column safely?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. The placeholder supplies a value expression, not a column identifier. Choose a fixed trusted statement or an explicit allowlisted column.
Choose a transaction boundary
A transaction groups changes that must succeed or fail together. A failure should not leave half of a promised all-or-nothing operation committed.
Understand first
Two related inserts can conflict with a constraint. An explicit transaction boundary lets the first insert roll back when the second fails.
Words you will see
- Transaction
- A unit of database work committed or rolled back together.
- Constraint
- A database rule such as a unique key.
- Rollback
- Discarding uncommitted changes from a transaction.
Trace the failed batch
The table is created before the transaction. Inside with connection, the first insert supplies key 1 and the second repeats it. The primary-key constraint raises IntegrityError. Exiting the context rolls back the transaction before the handler runs.
The final count is zero because neither insert remains. A successful exit would commit the pair. SQLite's connection context manages transaction completion but does not close the connection; finally performs that separate lifetime responsibility.
Keep the scope honest
A database rollback cannot undo an HTTP payment that already happened. Cross-system operations require a recovery and idempotency design rather than a larger local with block. Do not label a local transaction a distributed guarantee.
Use explicit connection settings and test the database actually deployed. SQLite memory fixtures teach local constraints and rollback, not PostgreSQL lock scheduling. Browser sqlite3 support varies and must fail honestly when unavailable.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
connection.execute("CREATE TABLE events (id INTEGER PRIMARY KEY)")Create a uniqueness rule before the batch.
with connection:Commit on successful exit or roll back on a propagated error.
except sqlite3.IntegrityError:Handle the expected constraint failure after rollback.
print(connection.execute("SELECT COUNT(*) FROM events").fetchone()[0])Observe that the first insert was rolled back too.
Group changes that must succeed or fail together. Handle rollback and connection lifetime explicitly. A transaction in one database cannot roll back an already completed external HTTP side effect, so distributed work needs a recovery/idempotency design.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. 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.
Change one thing; explain the difference.
Use different keys.
Try: Change the second inserted value to 2.
The context commits and the final count is two.
Move the first insert outside the batch and commit it.
Try: Call connection.commit() before entering the with block.
A later conflicting batch cannot roll back that already committed row.
Before you move on
If the first insert is explicitly committed before the second fails, will rolling back the second remove the first?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. A committed transaction is outside the later rollback boundary. Group both changes in one transaction for this all-or-nothing contract.
Query a private in-memory database
A private in-memory database can teach parameter binding and connection ownership without touching real user data. Transaction completion and connection closure are separate duties.
Understand first
The original sessions fixture records one study duration, then retrieves it with a bound topic value and always closes its connection.
Words you will see
- :memory:
- SQLite's special name for a connection-local in-memory database.
- fetchone
- A cursor operation returning the next row or None when no row remains.
- Connection lifetime
- The interval during which a program owns and must eventually close a database connection.
Read the original sessions program
The program creates sessions with topic text and integer minutes. Inside the transaction context it inserts lists and 20 as bound values. The query then binds lists as a one-element tuple and fetches one matching row.
row[0] reads the minutes field and prints 20. If the topic were absent, fetchone would return None and row[0] would fail. Handle that boundary explicitly when absence is expected instead of claiming every query returns a row.
Close separately from commit
with connection completes its transaction but does not close the connection. The finally block closes it on both normal and exceptional paths. This distinction matters when many requests could otherwise retain unused resources.
This is an isolated in-memory SQLite fixture, not durable storage or a deployment migration. Some browser runtimes lack sqlite3; leave their unsupported error visible and offer host execution. A successful local sample does not prove lock behavior on another database.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
connection = sqlite3.connect(':memory:')Create a private database for this connection.
with connection:Group the table setup and insertion under transaction handling.
print(row[0])Display the retrieved minutes from the one matching row.
connection.close()Close the resource independently of transaction completion.
Only an isolated in-memory SQLite database is used. Values are bound as parameters and the connection is always closed.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. 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.
Change one thing; explain the difference.
Change the duration.
Try: Insert 35 instead of 20.
The matching query prints 35.
Test absence honestly.
Try: Query tuples instead of lists.
fetchone returns None and the unchanged indexing line raises an actual TypeError.
Before you move on
Change the queried topic to tuples without inserting it. What should the application check before reading row[0]?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Check whether row is None. A missing row is a normal lookup outcome, not a zero-minute row or an empty tuple.
Separate syntax safety, domain validity and permission
Parameter binding keeps data values separate from SQL syntax. The SQLite example inserts lists and 20 through placeholders, then selects the stored minutes using another bound topic value. A topic that contains quotes should remain data rather than alter the statement. Binding does not make the value meaningful or the operation authorized: a negative duration can be safely bound yet violate the domain, and a valid identifier can still refer to another user's resource.
Placeholders stand for values, not table names, sorting directions, or arbitrary query fragments. Keep structural SQL fixed where possible; choose identifiers through a strict trusted allowlist when variation is required. Validate external record shape, string lengths, exact integer policy, and payload size before persistence. Avoid eval, untrusted pickle loading, and shell interpolation as alternate ways to interpret input. They cross execution boundaries that a database placeholder does not protect.
Choose the smallest correct transaction boundary
A transaction groups changes whose committed state must remain consistent. For two dependent writes, validate the request, begin the database unit of work, perform both changes, and commit only after both succeed. On a failure, roll back and propagate an appropriate error. Return a committed receipt rather than announcing success after the first statement. Keep slow external calls outside a lock-holding transaction unless a carefully justified protocol requires otherwise.
In the lesson fixture, the connection context manages commit or rollback around creation and insertion, while finally closes the connection afterward. These are separate responsibilities: leaving a transaction context does not imply every database API closes its connection. If a later query fails, cleanup must still run. Establish who owns the connection and transaction so a helper does not unexpectedly commit work that its caller intended to combine with another operation.
Reason about contention and external side effects
Concurrent writers can contend, and different engines and isolation levels expose different behavior. SQLite's private in-memory fixture demonstrates parameter use and local transaction structure, not PostgreSQL locking semantics or multi-user deployment readiness. Test unique constraints, rollback, and concurrent access with the database intended for deployment. Bound connection-pool waits and transaction duration so an overloaded service cannot accumulate unlimited requests waiting for scarce database resources.
A database rollback cannot undo a remote order or email already sent. If database state and an external effect must coordinate, define a recovery mechanism such as a transactional outbox with idempotent downstream handling. An idempotency receipt must share the authoritative commit boundary with the operation it represents. Retrying an entire transaction after a transient conflict requires knowing which effects occurred outside that boundary; otherwise retry can duplicate work despite correct local rollback.
Verify unhappy paths with isolated state
Create fresh database fixtures for tests and inspect committed state after each operation. Cover a valid insertion, zero minutes, invalid type, negative minutes, blank topic, and SQL-like text stored literally. Inject a failure between dependent statements and verify that neither remains committed. Add a constraint-conflict test and distinguish expected validation errors from programming defects. Counting rows after a rejected request is stronger evidence than merely asserting that an exception was raised.
Operational readiness adds migrations, least-privilege access, backup and restore checks, safe diagnostics, and a documented upgrade path. Do not expose raw SQL exceptions or complete personal records to callers. Keep query result sizes bounded and paginate large reads. Explain exactly what each test proves: an in-memory successful query verifies a narrow repository behavior, while durable recovery, authentication, and cross-process concurrency require separate integration and operational evidence.
Transfer question: A service inserts a session and sends a notification, then its database transaction rolls back. Can retrying the request repair this safely?
Not by itself. The notification may already exist even though the row does not. Repeating both steps could send a duplicate. Redesign the database transaction to commit the session and an outbox record together, then let a separate dispatcher deliver the notification using a stable effect identity and a receiver-aware deduplication policy. Test failure before commit, after commit before dispatch, and after delivery before acknowledgment. This does not create universal exactly-once delivery; it makes recovery explicit and confines the atomic guarantee to the database while the external effect has its own replay contract.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Rebuild: Query a private in-memory database
Without copying the worked code, reproduce its observable contract: Only an isolated in-memory SQLite database is used. Values are bound as parameters and the connection is always closed. Then change one boundary input and explain the result.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. 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.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. 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. Save work and place stores a private copy of edited code. Run results remain local learning feedback. 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.
Guided: query supplied session rows
Create a private SQLite fixture and return all durations for one exact topic using value binding.
The contract
- Input rows are (topic string, integer minutes) pairs and topic is a string argument.
- Return a new list of integer durations in insertion order, including duplicates; a missing topic returns [].
- Use sqlite3 with ':memory:' only and bound parameters. Never alter input, compose topic into SQL or access a real database; close the connection on every path.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. 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.
- matching rows in order
import copy source = [("lists",20),("tuples",5),("lists",10)] before = copy.deepcopy(source) result = topic_minutes(source, "lists") assert type(result) is list, "Wrong result type" expected = [20, 10] observed = result assert observed == expected, "Wrong result value" def same_types(actual, target): if type(actual) is not type(target): return False if type(target) in (list, tuple): return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target)) if type(target) is dict: return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target) return True assert same_types(observed, expected), "Wrong nested value type" assert source == before, "Caller input changed" assert result is not source, "Return a fresh container" assert all(type(value) is int for value in result) - empty database
import copy source = [] before = copy.deepcopy(source) result = topic_minutes(source, "lists") assert type(result) is list, "Wrong result type" expected = [] observed = result assert observed == expected, "Wrong result value" def same_types(actual, target): if type(actual) is not type(target): return False if type(target) in (list, tuple): return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target)) if type(target) is dict: return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target) return True assert same_types(observed, expected), "Wrong nested value type" assert source == before, "Caller input changed" assert result is not source, "Return a fresh container" - repeated durations
import copy source = [("x",4),("x",4)] before = copy.deepcopy(source) result = topic_minutes(source, "x") assert type(result) is list, "Wrong result type" expected = [4, 4] observed = result assert observed == expected, "Wrong result value" def same_types(actual, target): if type(actual) is not type(target): return False if type(target) in (list, tuple): return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target)) if type(target) is dict: return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target) return True assert same_types(observed, expected), "Wrong nested value type" assert source == before, "Caller input changed" assert result is not source, "Return a fresh container" - missing topic
import copy source = [("x",0)] before = copy.deepcopy(source) result = topic_minutes(source, "missing") assert type(result) is list, "Wrong result type" expected = [] observed = result assert observed == expected, "Wrong result value" def same_types(actual, target): if type(actual) is not type(target): return False if type(target) in (list, tuple): return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target)) if type(target) is dict: return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target) return True assert same_types(observed, expected), "Wrong nested value type" assert source == before, "Caller input changed" assert result is not source, "Return a fresh container" - SQL-looking value is data
import copy source = [("x",1),("y",2)] before = copy.deepcopy(source) result = topic_minutes(source, "x' OR 1=1 --") assert type(result) is list, "Wrong result type" expected = [] observed = result assert observed == expected, "Wrong result value" def same_types(actual, target): if type(actual) is not type(target): return False if type(target) in (list, tuple): return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target)) if type(target) is dict: return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target) return True assert same_types(observed, expected), "Wrong nested value type" assert source == before, "Caller input changed" assert result is not source, "Return a fresh container" - quoted topic and ownership
import copy source = [("O'Neil",7)] before = copy.deepcopy(source) result = topic_minutes(source, "O'Neil") assert type(result) is list, "Wrong result type" expected = [7] observed = result assert observed == expected, "Wrong result value" def same_types(actual, target): if type(actual) is not type(target): return False if type(target) in (list, tuple): return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target)) if type(target) is dict: return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target) return True assert same_types(observed, expected), "Wrong nested value type" assert source == before, "Caller input changed" assert result is not source, "Return a fresh container" result.append(8) assert source == before
Does binding the topic authorize the caller?
No. It separates data from SQL syntax only. Authorization remains an outer concern. With n inserted rows, this unindexed fixture scans O(n) rows and retains O(n) database data plus matching output.
Guided: insert a batch atomically
Insert integer IDs into a new private table with a primary key; reject a duplicate batch without keeping a partial prefix.
The contract
- Input is a finite list of integer IDs; duplicates violate the batch contract.
- Return (True, sorted_ids) on complete success or (False, []) when any duplicate triggers IntegrityError, including duplicates after a valid prefix.
- Empty input succeeds. Do not mutate input. Use one transaction in a new ':memory:' SQLite database and always close it.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. 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.
- successful sorted batch
import copy source = [3, 1, 2] before = copy.deepcopy(source) result = atomic_batch(source) assert type(result) is tuple, "Wrong result type" expected = (True, [1, 2, 3]) observed = result assert observed == expected, "Wrong result value" def same_types(actual, target): if type(actual) is not type(target): return False if type(target) in (list, tuple): return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target)) if type(target) is dict: return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target) return True assert same_types(observed, expected), "Wrong nested value type" assert source == before, "Caller input changed" assert type(result[0]) is bool and type(result[1]) is list and all(type(value) is int for value in result[1]) - empty successful transaction
import copy source = [] before = copy.deepcopy(source) result = atomic_batch(source) assert type(result) is tuple, "Wrong result type" expected = (True, []) observed = result assert observed == expected, "Wrong result value" def same_types(actual, target): if type(actual) is not type(target): return False if type(target) in (list, tuple): return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target)) if type(target) is dict: return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target) return True assert same_types(observed, expected), "Wrong nested value type" assert source == before, "Caller input changed" assert result[0] is True and type(result[1]) is list - immediate duplicate
import copy source = [4, 4] before = copy.deepcopy(source) result = atomic_batch(source) assert type(result) is tuple, "Wrong result type" expected = (False, []) observed = result assert observed == expected, "Wrong result value" def same_types(actual, target): if type(actual) is not type(target): return False if type(target) in (list, tuple): return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target)) if type(target) is dict: return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target) return True assert same_types(observed, expected), "Wrong nested value type" assert source == before, "Caller input changed" assert result[0] is False and type(result[1]) is list - late duplicate rolls back prefix
import copy source = [1, 2, 3, 1] before = copy.deepcopy(source) result = atomic_batch(source) assert type(result) is tuple, "Wrong result type" expected = (False, []) observed = result assert observed == expected, "Wrong result value" def same_types(actual, target): if type(actual) is not type(target): return False if type(target) in (list, tuple): return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target)) if type(target) is dict: return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target) return True assert same_types(observed, expected), "Wrong nested value type" assert source == before, "Caller input changed" - zero and negatives are valid IDs
import copy source = [0, -2, 5] before = copy.deepcopy(source) result = atomic_batch(source) assert type(result) is tuple, "Wrong result type" expected = (True, [-2, 0, 5]) observed = result assert observed == expected, "Wrong result value" def same_types(actual, target): if type(actual) is not type(target): return False if type(target) in (list, tuple): return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target)) if type(target) is dict: return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target) return True assert same_types(observed, expected), "Wrong nested value type" assert source == before, "Caller input changed" - returned rows are independent
import copy source = [8] before = copy.deepcopy(source) result = atomic_batch(source) assert type(result) is tuple, "Wrong result type" expected = (True, [8]) observed = result assert observed == expected, "Wrong result value" def same_types(actual, target): if type(actual) is not type(target): return False if type(target) in (list, tuple): return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target)) if type(target) is dict: return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target) return True assert same_types(observed, expected), "Wrong nested value type" assert source == before, "Caller input changed" assert result[1] is not source result[1].append(9) assert source == before
Would committing every insert preserve this contract?
No. A later duplicate could not roll back earlier commits. For n IDs, primary-key insertion typically takes O(n log n) index work, with O(n) storage; the transaction groups changes, not external side effects.
Transfer: choose a structural SQL option safely
The caller now chooses ascending or descending duration order. That choice is SQL structure, so value placeholders cannot implement it.
The contract
- Input rows are (topic string, integer minutes) pairs; direction must be exactly 'asc' or 'desc', otherwise raise ValueError even for empty input.
- Return new (topic, minutes) tuples sorted by duration in that direction; ties preserve insertion order and duplicates remain.
- Use an explicit allowlist to select a trusted SQL direction, never raw caller SQL. Use ':memory:' only, preserve input and always close the connection.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. 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.
- ascending durations
import copy source = [("b",20),("a",5)] before = copy.deepcopy(source) result = ordered_sessions(source, "asc") assert type(result) is list, "Wrong result type" expected = [("a",5),("b",20)] observed = result assert observed == expected, "Wrong result value" def same_types(actual, target): if type(actual) is not type(target): return False if type(target) in (list, tuple): return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target)) if type(target) is dict: return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target) return True assert same_types(observed, expected), "Wrong nested value type" assert source == before, "Caller input changed" assert result is not source, "Return a fresh container" assert all(type(row) is tuple and type(row[0]) is str and type(row[1]) is int for row in result) - empty rows and invalid choice
import copy source = [] before = copy.deepcopy(source) result = ordered_sessions(source, "desc") assert type(result) is list, "Wrong result type" expected = [] observed = result assert observed == expected, "Wrong result value" def same_types(actual, target): if type(actual) is not type(target): return False if type(target) in (list, tuple): return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target)) if type(target) is dict: return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target) return True assert same_types(observed, expected), "Wrong nested value type" assert source == before, "Caller input changed" assert result is not source, "Return a fresh container" for bad in ["DESC", "asc; DROP TABLE sessions", ""]: caught = False try: ordered_sessions(source, bad) except ValueError: caught = True assert caught and source == before - duplicate records remain
import copy source = [("x",4),("x",4)] before = copy.deepcopy(source) result = ordered_sessions(source, "asc") assert type(result) is list, "Wrong result type" expected = [("x",4),("x",4)] observed = result assert observed == expected, "Wrong result value" def same_types(actual, target): if type(actual) is not type(target): return False if type(target) in (list, tuple): return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target)) if type(target) is dict: return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target) return True assert same_types(observed, expected), "Wrong nested value type" assert source == before, "Caller input changed" assert result is not source, "Return a fresh container" - descending keeps tie order
import copy source = [("a",5),("z",5),("b",8)] before = copy.deepcopy(source) result = ordered_sessions(source, "desc") assert type(result) is list, "Wrong result type" expected = [("b",8),("a",5),("z",5)] observed = result assert observed == expected, "Wrong result value" def same_types(actual, target): if type(actual) is not type(target): return False if type(target) in (list, tuple): return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target)) if type(target) is dict: return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target) return True assert same_types(observed, expected), "Wrong nested value type" assert source == before, "Caller input changed" assert result is not source, "Return a fresh container" - signed duration ordering
import copy source = [("zero",0),("negative",-1)] before = copy.deepcopy(source) result = ordered_sessions(source, "asc") assert type(result) is list, "Wrong result type" expected = [("negative",-1),("zero",0)] observed = result assert observed == expected, "Wrong result value" def same_types(actual, target): if type(actual) is not type(target): return False if type(target) in (list, tuple): return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target)) if type(target) is dict: return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target) return True assert same_types(observed, expected), "Wrong nested value type" assert source == before, "Caller input changed" assert result is not source, "Return a fresh container" - output cannot reorder caller
import copy source = [("first",1),("second",2)] before = copy.deepcopy(source) result = ordered_sessions(source, "desc") assert type(result) is list, "Wrong result type" expected = [("second",2),("first",1)] observed = result assert observed == expected, "Wrong result value" def same_types(actual, target): if type(actual) is not type(target): return False if type(target) in (list, tuple): return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target)) if type(target) is dict: return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target) return True assert same_types(observed, expected), "Wrong nested value type" assert source == before, "Caller input changed" assert result is not source, "Return a fresh container" result.clear() assert source == before
Why is interpolating choices[direction] different from interpolating direction?
Only fixed trusted fragments can emerge from the allowlist. Raw caller text could become SQL syntax. Sorting n rows requires sorting work, typically O(n log n), plus database and output storage; value binding remains necessary for row values.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneLocks and isolation are real behaviour
Constraints are database-enforced invariants. Test rollback and isolation against the chosen engine rather than assuming every SQL database has the same locking behavior.
Understand first
An application-side check can miss conflicts. A UNIQUE constraint provides a final boundary even when repeated data reaches the write path.
Words you will see
- Invariant
- A rule that must remain true after every completed operation.
- Isolation
- Rules governing what concurrent transactions can observe.
- Contention
- Multiple operations competing for the same database resource.
Let the database reject duplicates
The table requires unique topic text. The first insertion is committed. A second transaction tries the same topic and raises IntegrityError. After rollback, the original committed row remains, so the count is one.
The constraint expresses a data rule even if application validation is bypassed. It does not decide who is authorized to insert, and it does not make an arbitrary sequence of reads and writes atomic unless they share the right transaction scope.
Do not simulate untested concurrency claims
This fixture is single-connection and sequential. It proves a constraint and transaction outcome, not deadlock handling, fairness or multi-writer throughput. SQLite and server databases differ in lock and isolation behavior.
A host integration lab should test competing writers, busy timeouts and recovery with controlled coordination rather than sleep-based guesses. Browser sqlite support may differ and a memory fixture must not be presented as a production concurrency benchmark.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
connection.execute("CREATE TABLE topics (name TEXT UNIQUE)")Declare the uniqueness invariant.
connection.execute("INSERT INTO topics VALUES (?)", ("lists",))Insert a bound topic; the first context commits it.
except sqlite3.IntegrityError:Observe rejection of the later conflicting transaction.
connection.close()Release the connection on all paths.
Concurrent writers can contend or deadlock depending on the database and isolation level. SQLite is useful for a local lab but does not reproduce every PostgreSQL concurrency rule. Test constraints and rollback with the database your application actually deploys.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. 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.
Change one thing; explain the difference.
Use a different topic.
Try: Insert "tuples" in the second transaction.
Two rows remain and no duplicate diagnostic prints.
Remove the uniqueness rule.
Try: Create the column without UNIQUE.
Both repeated values can be inserted, demonstrating why the invariant matters.
Before you move on
A duplicate transaction fails after a valid row was committed earlier. Should the database become empty?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. Only uncommitted work in the failed transaction is rolled back; the earlier successful transaction remains.
Secure coding boundaries
Parsing data is safer than executing it, but parsing alone is not validation or authorization. Bound input size, structure and allowed values before acting on them.
Understand first
A request that looks like a dictionary should not be passed to eval. JSON decoding plus explicit field rules gives a narrower data boundary.
Words you will see
- Untrusted input
- Data whose content the program must not assume is safe or authorized.
- Allowlist
- An explicit set of permitted choices.
- Domain validation
- Checking whether decoded values meet the application's meaning and limits.
Check size, shape and meaning
The fixed JSON text is bounded by character length before decoding. The decoded object must be a dictionary and minutes must have exact type int in the range 0 to 120. Exact type intentionally excludes bool, which otherwise behaves as an integer subclass.
The character bound is not a network byte bound; a real adapter must enforce bytes while reading too. JSON syntax can still contain an unwanted shape. Never replace validation with eval or unpickle unknown input, both of which cross into more dangerous behavior.
Constrain what happens next
A valid minute value does not grant permission to write someone else's session. Authorization belongs at the operation boundary. For dynamic SQL columns or sort direction, choose from fixed trusted fragments rather than joining caller text.
The browser fixture performs no shell, path, credential or database operation. Host applications must constrain file destinations and avoid shell=True for user-controlled commands. Report a rejected value as an error rather than silently accepting a success-shaped default.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
if len(text) > 80:Apply the small text-fixture bound before decoding.
data = json.loads(text)Parse data without executing Python source.
minutes = data.get("minutes")Make a missing value explicit as None.
if type(minutes) is not int or not 0 <= minutes <= 120:Reject wrong types, including bool, and out-of-range values.
Never eval untrusted text or unpickle untrusted input. Avoid shell=True for user-controlled commands, constrain file paths and limit payload sizes. Secrets belong in an approved secret store, not examples, logs or distributed packages.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. 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.
Change one thing; explain the difference.
Try a Boolean.
Try: Change the JSON to {"minutes":true}.
The exact-type guard rejects it.
Test the upper boundary.
Try: Change minutes to 120, then 121.
120 is accepted and 121 raises ValueError.
Before you move on
The JSON value is true instead of 20. Why does this contract reject it even though Python booleans behave numerically?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
The domain requires an actual integer minute count. type(value) is int excludes bool deliberately; accepting True as one minute would violate that contract.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.