简体   繁体   中英

SQLite3 “forgets” to use foreign keys

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.

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.

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")

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM