Chapter 9 · practice
Create, Import, and Evolve a Schema
Rebuild the Schema from Source
An empty database path is not yet a lending database. It needs the same three tables and rules every time, even when no earlier .db file is available to copy.
Four files are visible in this project:
| File | Role |
|---|---|
catalog_setup.py | The file you edit to create and later update the schema. |
catalog_db.py | The completed query and command |
data/items.csv | The item records you will import later. |
run_setup.py | The visible program that Run executes to call your functions with temporary databases. |
Open catalog_setup.py. The three CREATE TABLE items and loans tables and adds nullable email TEXT as the final members column.
Your work belongs in create_current_schema(connection). The function receives an open connection. Execute BEGIN first, then execute each of the three table statements separately. If every statement succeeds, call connection.commit(). If any statement raises an connection.rollback() and let that original exception continue.
Why write BEGIN yourself? A SQLite connection context can choose commit or rollback for data changes, but it does not begin this sequence of table-creation statements for you. Without an explicit start, a later failure can leave an earlier table behind. Here, all three tables need one outcome.
Do not close the connection. The caller supplied it and still owns its lifetime.
Press Run. run_setup.py opens a fresh in-memory connection and calls exactly:
create_current_schema(connection)
The new block should end like this:
== rebuild the schema ==
Call: create_current_schema(connection)
Tables: items, loans, members
Members columns: id, member_code, name, loan_limit, email
Schema version: 0
Transaction still open: no
The version remains 0 on purpose. You have made creation atomic; now that exact schema needs a stored version.
Submit also creates a deliberate late conflict. If members already exists, the second create fails. A correct rollback removes the items table created earlier in the same attempt while preserving the table that was already there.
Task
Complete create_current_schema(connection) in catalog_setup.py.
Execute a static BEGIN, then the supplied ITEMS_SQL, MEMBERS_SQL, and LOANS_SQL statements. Commit once after all three succeed. On an
Press Run and confirm that all three tables appear, email is the final member column, the version is still 0, and no