'Remove orphaned entries.'

def clean(self):

    def doit(ltable, table, ltable_col):
        st = ('DELETE    FROM    books_%s_link    WHERE    (SELECT    COUNT(id)    FROM    books    WHERE    id=book)    <    1;' % ltable)
        self.conn.execute(st)
        st = ('DELETE    FROM    %(table)s    WHERE    (SELECT    COUNT(id)    FROM    books_%(ltable)s_link    WHERE    %(ltable_col)s=%(table)s.id)    <    1;' % dict(ltable=ltable, table=table, ltable_col=ltable_col))
        self.conn.execute(st)
    for (ltable, table, ltable_col) in [('authors', 'authors', 'author'), ('publishers', 'publishers', 'publisher'), ('tags', 'tags', 'tag'), ('series', 'series', 'series'), ('languages', 'languages', 'lang_code')]:
        doit(ltable, table, ltable_col)
    for (id_, tag) in self.conn.get('SELECT    id,    name    FROM    tags', all=True):
        if (not tag.strip()):
            self.conn.execute('DELETE    FROM    books_tags_link    WHERE    tag=?', (id_,))
            self.conn.execute('DELETE    FROM    tags    WHERE    id=?', (id_,))
    self.clean_custom()
    self.conn.commit()
