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

def upgrade_version_2(self):

    script = u"                                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.db.execute((script % dict(ltable=u'authors', table=u'authors', ltable_col=u'author')))
    self.db.execute((script % dict(ltable=u'publishers', table=u'publishers', ltable_col=u'publisher')))
    self.db.execute((script % dict(ltable=u'tags', table=u'tags', ltable_col=u'tag')))
    self.db.execute((script % dict(ltable=u'series', table=u'series', ltable_col=u'series')))
