Extract some duplicated query building logic and add support for multi-level link queries

Eliminates the duplicated handling for IN clauses as well as a few other bits, and in the process got multi-level links close enough to working that I just went ahead and finished it.

@alazier @jpsim 
With the new organization I don't think we even need this here anymore. In all cases other than between where we have different code paths, add_contraint_to_query can instead figure out whether it is a link query and behave accordingly.