How to set the 'PRAGMA foreign_keys = ON' statement with SQLitePCL

↘锁芯ラ 提交于 2021-02-20 04:37:51

问题


I have been using SQLitePCL (currently ver 3.8.7.2), and now decided to experiment with Delete and Update Cascade by turning on the Foreign Key constraint. I understand this feature is disabled by default and according to SQLite documentation, the constraint must be enabled separately for each database connection.

The connection string only takes a database path (for SQLitePCL anyway) and doesn't allow more flexible composite connection string of the form data source=d:\foo\bar\mySqlite.db;foreign keys=ON. If I have to turn on the constaint for every connection as shown below, how to turn on the constraint?

I was expecting the ISQLiteStatement API to provide some means of injecting the PRAGMA foreign_keys = ON statement into my connection statement but see no obvious [Intellisense] method or property to achieve this. Exploring the SQLiteConnection API is not even a starter as turning on the foreign key constraint is per connection anyway.

Note: DeleteItemByIdQuery() and BindIdToDeleteItemByIdQuery() methods below return SQL Query strings and details omitted for brevity.

using (ISQLiteStatement statement = new SQLiteConnection("d:\foo\bar\mySqlite.db").Prepare(DeleteItemByIdQuery()))
{
    BindIdToDeleteItemByIdQuery(statement, id);
    SQLiteResult result = statement.Step();
}

Am I overlooking something simple, or is this impossible? Help!


回答1:


The PRAGMA statement is a normal SQL statement; just execute it.

To reduce the amount of typing, you can write a helper function for creating a connection and configuring it.




回答2:


Okay, I figured it out:

Keep the SQLiteConnection as an outer using block and execute a sequence of PRAGMA and the main statement within it. Funny I thought I tried the same before and didn't get the result I'm getting now -- other mistakes may have been at work then.

using (var conn = new SQLiteConnection(@"d:\foo\bar\mySqlite.db"))
{
    // First turn ON the FK constraint

    using (var statement = conn.Prepare(@"PRAGMA foreign_keys = ON"))
    {
        SQLiteResult result = statement.Step();
    }

    // Then Delete item that will Cascade deletion in referencing table(s)

    using (var statement = conn.Prepare(SqlDeleteItemById()))
    {
        SqlBindIdToDeleteItemById(statement, id);
        SQLiteResult result = statement.Step();
    }
}


来源:https://stackoverflow.com/questions/37797960/how-to-set-the-pragma-foreign-keys-on-statement-with-sqlitepcl

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