'Fix Foreign key constraints for deleting from link tables.'

def upgrade_version_2(self):

    script = "                                DROP    TRIGGER    IF    EXISTS    fkc_delete_books_%(ltable)s_link;\n                                CREATE    TRIGGER    fkc_delete_on_%(table)s\n                                BEFORE    DELETE    ON    %(table)s\n                                BEGIN\n                                                SELECT    CASE\n                                                                WHEN    (SELECT    COUNT(id)    FROM    books_%(ltable)s_link    WHERE    %(ltable_col)s=OLD.id)    >    0\n                                                                THEN    RAISE(ABORT,    'Foreign    key    violation:    %(table)s    is    still    referenced')\n                                                END;\n                                END;\n                                DELETE    FROM    %(table)s    WHERE    (SELECT    COUNT(id)    FROM    books_%(ltable)s_link    WHERE    %(ltable_col)s=%(table)s.id)    <    1;\n                                "
    self.conn.executescript((script % dict(ltable='authors', table='authors', ltable_col='author')))
    self.conn.executescript((script % dict(ltable='publishers', table='publishers', ltable_col='publisher')))
    self.conn.executescript((script % dict(ltable='tags', table='tags', ltable_col='tag')))
    self.conn.executescript((script % dict(ltable='series', table='series', ltable_col='series')))
