How to enable foreign key cascade delete by default in SQLite?

橙三吉。 提交于 2019-12-07 01:46:52

问题


SQLite v3.7.5

Is there a way to enable SQLite Foreign Keys with cascade delete enabled by default? Given the following example:

CREATE TABLE [Parent] (
[ParentId] INTEGER  NOT NULL PRIMARY KEY AUTOINCREMENT,
[Name] VARCHAR(50)  UNIQUE NOT NULL
);

CREATE TABLE [Child] (
[ChildId] INTEGER  PRIMARY KEY AUTOINCREMENT NOT NULL,
[ParentId] INTEGER  NOT NULL,
[Name] VARCHAR(50)  NOT NULL,
FOREIGN KEY(ChildId) REFERENCES Child(ParentId) ON DELETE CASCADE
);

The only way I've been able to enable the cascade delete is to execute the PRAGMA foreign_keys = true command before a transaction:

using( var conn = new SQLiteConnection( _conn ) )
{
    conn.Open();
    var pragma = new SQLiteCommand( "PRAGMA foreign_keys = true;", conn );
    pragma.ExecuteNonQuery();

    var cmd = new SQLiteCommand( "Delete from Parent where ParentId = 1", conn );
    cmd.ExecuteNonQuery();
}

Is there a setting on the database level that can be configured rather than having to call the pragma command before each transaction?

I've seen the triggers to enable cascade deletes, but am looking for something that would simply enable the PRAGMA foreign_keys = true at the database level.


回答1:


System.Data.SQLite 1.0.66 doesn't have it, but in the repository version of it, they have updated to sqlite 3.7.4 and have made a new connection string attribute "Foreign Keys". Who knows when this will be released officially? So you could set this in your connection string. The project lives here now: http://system.data.sqlite.org/index.html/doc/trunk/www/index.wiki




回答2:


No, not even with compile-time options.

The only way, so far, is to use pragma foreign_keys=on at run time. The particular danger is that every application that touches the database has to do that.

If a specific application doesn't run that pragma statement, it can insert data that will violate foreign key constraints, and other applications won't know it. That is, turning on foreign keys doesn't warn you of existing data that violates the constraint.




回答3:


No, there is no way currently (for backward compatibility). See the link you provided under (2):

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

However, this might be changed in the future:

(Note, however, that future releases of SQLite might change so that foreign key constraints enabled by default. Careful developers will not make any assumptions about whether or not foreign keys are enabled by default but will instead enable or disable them as necessary.)



来源:https://stackoverflow.com/questions/4981353/how-to-enable-foreign-key-cascade-delete-by-default-in-sqlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!