Sqlite Foreign Keys Sqlite Foreign Keys sqlite sqlite

Sqlite Foreign Keys


According to the docs:

Assuming the library is compiled with foreign key constraints enabled, it must still be enabled by the application at runtime, using the PRAGMA foreign_keys command. For example:

sqlite> PRAGMA foreign_keys = ON;

Foreign key constraints are disabled by default (for backwards compatibility), so must be enabled separately for each database connection separately.

So, after your sqlite3_open(), you probably want to add the following:

sqlite3_exec(ppDb, "PRAGMA foreign_keys = ON;", 0, 0, 0);


I had difficulties with enabling foreign keys using HDBC-sqlite3 API because mentioned PRAGMA required to be invoked beyond transaction and the library opens in background a new transaction after connection gets established and after each commit. Still the workaround was easy:

main = do   conn <- connectSqlite3 "test.db"   runRaw conn "COMMIT; PRAGMA foreign_keys = ON; BEGIN TRANSACTION"