Add support for subselects with CTEs.
I've merged an equivalent patch, which expands on your own and adds comments and test-cases: 6707199769e0f8878988242bca347f577e3f0e7b

Thank you very much for digging into this and finding such a concise solution.
By delaying the emission of CTEs and emitting them in the subquery's context, they are contained within its surrouding parentheses. To avoid adding extra parentheses to the CTE queries, force the context for the CTE list to not have the subquery flag.

This fixes #1809.