Refactored the query generation to better handle subqueries. Basic
subqueries now seem to be generating properly.