0%

Relate Tables Instead of Repeating Data · practice

Turn Foreign-Key Checks On

The schema now says where each loan ID must lead. A default connection still reported foreign_keys: 0, so SQLite did not enforce those promises. The setting belongs to the connection, not to the schema file.

Open connections.py. Its open_database(database_path) already opens the path it receives and returns the live connection. Add this line between those two actions:

connection.execute("PRAGMA foreign_keys = ON")

PRAGMA is SQLite’s statement for reading or changing a database setting. This one turns enforcement on for that connection. Keep the statement static. It has no learner-controlled to bind.

Press Run. run_relationships.py creates a temporary database, calls your function twice with the same displayed database_path, and asks each returned connection about its setting. It then tries a loan whose item ID does not exist.

The important lines are these:

first foreign_keys: 1
missing item: IntegrityError
second foreign_keys: 1
first still open: yes
second still open: yes

The two 1 values matter independently. Turning the check on for first does not turn it on for second, even though both connections open the same database file. Every call to open_database must configure the new connection it creates.

Your function also leaves both connections open. Opening a connection transfers its lifetime to the caller. The caller can run queries and later close it. Returning a closed connection, or keeping one global connection and returning it repeatedly, would break that promise.

Submit calls open_database with different paths and data. It checks missing items and members separately, stores a valid loan, and runs a harmless query afterward. Once that passes, the schema declaration and the connection setting are working together: the table describes the relationships, and every connection opened by your function enforces them.

Task

Complete open_database(database_path) in connections.py. Enable SQLite checks on the new connection before returning it.

Press Run and confirm that two separate calls both report foreign_keys: 1, a missing item raises IntegrityError, and both returned connections remain usable.