Exercise 2: Why PRAGMA foreign_keys = ON Is Set Explicitly on Every Connection — Possible Solution ==================================================================== WHAT THE CODE DOES ------------------------------ Per this chapter's own get_connection() function, every single connection opened by the application immediately runs conn.execute("PRAGMA foreign_keys = ON"), with the code comment explicitly stating this is "sqlite1-5's own gotcha, deliberately not forgotten." CONNECTING THIS TO SQLITE1-5'S OWN WARN-BOX ------------------------------ Per sqlite1-5's own warn-box, "SQLite genuinely supports foreign key constraints, but does not enforce them by default — enforcement must be explicitly turned on per connection with PRAGMA foreign_keys = ON;. Forgetting this setting silently allows orphaned or invalid foreign key references to be inserted with no error at all." Because this setting is per-CONNECTION rather than a permanent, database-wide setting, it has to be set every single time a new connection is opened — this capstone's own get_connection() function centralizes that step so it's genuinely impossible to open a connection through this application's own code without foreign key enforcement being turned on. WHAT COULD GO WRONG IN THIS SPECIFIC APPLICATION IF THAT LINE WERE REMOVED ------------------------------ The expenses table declares category_id INTEGER NOT NULL REFERENCES categories(id) — a genuine foreign key constraint intended to guarantee that every expense is linked to a real, existing category. If PRAGMA foreign_keys = ON were removed from get_connection(), that constraint would simply stop being enforced (per sqlite1-5's own default-off behavior), even though the table definition still LOOKS like it enforces it. Concretely, this would mean a bug elsewhere in the application — or a category accidentally deleted from the categories table after expenses already reference it — could leave expenses rows pointing at a category_id that no longer corresponds to any real category. The summary_by_category() function's own JOIN between expenses and categories would then silently exclude those orphaned expense rows from the report entirely (since an INNER JOIN naturally drops rows with no matching category), meaning the expense tracker's own summary totals could quietly become inaccurate, without any error ever being raised to reveal the underlying problem. WHY THIS WORKS AS AN ANSWER ------------------------------ It connects the specific line of capstone code directly back to sqlite1-5's own stated gotcha, and traces a concrete, specific consequence for THIS application (orphaned expenses silently dropped from summary totals) rather than describing the risk only in the abstract.