INSERT OR REPLACE + foreign key ON DELETE CASCADE working too good

前端 未结 3 597
谎友^
谎友^ 2020-12-16 13:08

I am currently trying to create an sqlite database where I can import a table from another sqlite database (can\'t attach) and add some extra data to each column.

Si

相关标签:
3条回答
  • 2020-12-16 13:37

    Assuming you only have a single foreign key relationship on a primary key in your referenced table (as you do in your example), this proved to be a fairly painless solution for me.

    Simply disable foreign key checks, run the replace query, then enable foreign keys again.

    If the replace query is the only query that runs while foreign keys are disabled, you can be assured that no foreign keys will be fouled up. If you are inserting a new row, nothing will have had a chance to be linked to it yet and if you are replacing a row, the existing row will not be removed or have its primary key changed by the query so the constraint will still hold once foreign keys are re-enabled.

    SQLlite code looks something like this:

    PRAGMA foreign_keys=OFF;
    INSERT OR REPLACE ...;
    PRAGMA foreign_keys=ON;
    
    0 讨论(0)
  • 2020-12-16 13:47

    It seems work if I replace the ON DELETE CASCADE part by a trigger like:

    CREATE TRIGGER on_delete_trigger
       AFTER DELETE ON base_data
       BEGIN
           DELETE FROM extra_data WHERE extra_data.remote_id=OLD.remote_id;
       END;
    

    That trigger is only triggered by a DELETE statement and should solve my problem so far.

    (Answer provided by the OP in the question)

    Additional info by jmathew, citing the documentation:

    When the REPLACE conflict resolution strategy deletes rows in order to satisfy a constraint, delete triggers fire if and only if recursive triggers are enabled.

    0 讨论(0)
  • 2020-12-16 13:49

    What about the reasons of such behavior, there's an explanation from PostgreSQL team:

    Yeah, this is per SQL spec as far as we can tell. Constraint checks can be deferred till end of transaction, but "referential actions" are not deferrable. They always happen during the triggering statement. For instance SQL99 describes the result of a cascade deletion as being that the referencing row is "marked for deletion" immediately, and then

    1. All rows that are marked for deletion are effectively deleted at the end of the SQL-statement, prior to the checking of any integrity constraints.
    0 讨论(0)
提交回复
热议问题