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