SQLite3 “forgets” to use foreign keys

2019-02-21 12:15发布

I'm using Ruby with SQLite3 and my attempts to use foreign keys in Sqlite3 were unfortunately not successful. According to sqlite3 --version, version 3.7.13 is installed. As far as I know, Sqlite3 supports foreign keys since version 3.6.x.

I know that foreign keys are deactivated by default and have to be activated with PRAGMA foreign_keys = ON;. In my Ruby db-create-script, I'm doing something like this:

sql = <<-SQL
  PRAGMA foreign_keys = ON;
  CREATE TABLE apps (
    id ....
  );
  CREATE TABLE requests (
    ...
    app_id INTEGER NOT NULL,
    FOREIGN KEY(app_id) REFERENCES apps(id),
  );
  ...
SQL
db.execute_batch(sql)

Unfortunately, I can happily insert rows into requests with unknown app-ids, it works, but of course it shouldn't.

Interesting: using the sqlite3 shell directly, I can observe the following behaviour:

$ sqlite3 database.db
sqlite> PRAGMA foreign_keys = ON;
sqlite> PRAGMA foreign_keys;
1 // as expected
sqlite> .quit
$ sqlite3 database.db
sqlite> PRAGMA foreign_keys;
0 // off ?!

Without quitting the sqlite3 shell, foreign keys are working after activating them (and not quitting the shell) and I'm not allowed to insert rows with unknown app_ids.

3条回答
The star\"
2楼-- · 2019-02-21 12:54

Put this at the top of the file that executes the SQL commands and it will enable foreign keys on runtime.

db = SQLite3::Database.new("database.db")
db.execute("PRAGMA foreign_keys = ON")
查看更多
霸刀☆藐视天下
3楼-- · 2019-02-21 12:55

One way of permanently turning on foreign_keys by default is to inject the following line into ~/.sqliterc:

PRAGMA foreign_keys = ON;

Please note that it will affect all your databases...

查看更多
ら.Afraid
4楼-- · 2019-02-21 13:00

I think I can answer my own question: The documentation says: Foreign key constraints are disabled by default (for backwards compatibility), so must be enabled for each database connection separately. Annoying, but it's finally working now.

查看更多
登录 后发表回答