0%

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:

FileRole
catalog_setup.pyThe file you edit to create and later update the schema.
catalog_db.pyThe completed query and command you already built. Leave it unchanged.
data/items.csvThe item records you will import later.
run_setup.pyThe visible program that Run executes to call your functions with temporary databases.

Open catalog_setup.py. The three CREATE TABLE already hold the current design. Version 2 keeps the familiar 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 , call 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 , roll back and let the same exception continue. Leave the supplied connection open.

Press Run and confirm that all three tables appear, email is the final member column, the version is still 0, and no remains open.