19

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.

4

3 回答 3

30

我想我可以回答我自己的问题:文档说:默认情况下禁用外键约束(为了向后兼容),因此必须分别为每个数据库连接启用。烦人,但它现在终于工作了。

于 2013-03-08T21:36:33.553 回答
14

将它放在执行 SQL 命令的文件的顶部,它将在运行时启用外键。

db = SQLite3::Database.new("database.db")
db.execute("PRAGMA foreign_keys = ON")
于 2014-02-12T13:07:34.903 回答
13

默认情况下永久打开foreign_keys的一种方法是将以下行注入~/.sqliterc

PRAGMA foreign_keys = ON;

请注意,它将影响您的所有数据库...

于 2017-07-01T04:20:18.227 回答