'Internal unlinked tx cleanup function, excluding the tracking table
`unlinked_tx`. This function is required by upgrade.py.'

def _clean_unlinked_tx(store, tx_id):

    unlinked_txins = store.selectall('\n                                                SELECT    txin_id    FROM    txin\n                                                WHERE    tx_id    =    ?', (tx_id,))
    for txin_id in unlinked_txins:
        store.sql('DELETE    FROM    unlinked_txin    WHERE    txin_id    =    ?', (txin_id,))
    store.sql('DELETE    FROM    txin    WHERE    tx_id    =    ?', (tx_id,))
    txout_pubkeys = set(store.selectall('\n                                                SELECT    pubkey_id    FROM    txout\n                                                WHERE    tx_id    =    ?    AND    pubkey_id    IS    NOT    NULL', (tx_id,)))
    msig_pubkeys = set()
    for pk_id in txout_pubkeys:
        msig_pubkeys.update(store.selectall('\n                                                                SELECT    pubkey_id    FROM    multisig_pubkey\n                                                                WHERE    multisig_id    =    ?', (pk_id,)))
    store.sql('DELETE    FROM    txout    WHERE    tx_id    =    ?', (tx_id,))
    for pk_id in txout_pubkeys.union(msig_pubkeys):
        (count,) = store.selectrow('\n                                                                SELECT    COUNT(pubkey_id)    FROM    txout\n                                                                WHERE    pubkey_id    =    ?', (pk_id,))
        if (count == 0):
            store.sql('DELETE    FROM    multisig_pubkey    WHERE    multisig_id    =    ?', (pk_id,))
            (count,) = store.selectrow('\n                                                                                SELECT    COUNT(pubkey_id)    FROM    multisig_pubkey\n                                                                                WHERE    pubkey_id    =    ?', (pk_id,))
            if (count == 0):
                store.sql('DELETE    FROM    pubkey    WHERE    pubkey_id    =    ?', (pk_id,))
    store.sql('DELETE    FROM    unlinked_tx    WHERE    tx_id    =    ?', (tx_id,))
    store.sql('DELETE    FROM    tx    WHERE    tx_id    =    ?', (tx_id,))
