Reuse existing MemoryQueries from model

I changed `TransformBuilder._genScopedModel` to check whether this query already exists and return a scoped model for the existing query.

This fixes a bug involving missing queryIds for duplicate queries, and makes them faster too.