querybuilder
querybuilder copied to clipboard
Query assignments with side effects
I only just discovered that calling most methods on the existing Query modifies/mutates the query instance instead of returning new instance. So even if no left-side assignment is made the query is modified.
For instance
var qb = query.Query;
var countQuery = qb.AsCount();
both qb and countQuery are the same after applying qb.AsCount().
I am trying to manipulate queries based on certain conditions and would like to keep the original query for later.
I found Clone() method, is that the only way to go?
Yes this is by design, as you have mentioned .Clone()
is what you want here.
What about immutable query, would you consider supporting that?
There is no plan for this, unless there is a valid reason to do this, check this thread #176 anyway, we are open to discussing more this.
As the other guy pointed out EF is doing it in immutable way and the methods in SqlKata even though they are not extension methods they kinda look like extension methods and for those one typically assumes they return new instances.
I'm not sure whether memory consumption would go through the roof (I could be wrong though).
The way I found out about this is when I ran into issues when I wasn't doing the assignment and the original query mutated anyway.
I don't particularly mind the Clone() but it does introduce certain noise imo.
I would also vote for an immutable pattern. I'm not sure why you say that memory consumption would go up, since on each assignment the old object would fall out of scope (and eventually be garbage collected).
This remains open and I'd hope plans would be revealed if this is planned for any version or maybe the next major version?
I'd imagine going from mutated queries to immutable ones is a breaking change, isn't it?
Making the query immutable requires major rewriting, and honestly I don't see the clear benefit for it, the query.Clone()
provide a handy way to do that, when needed.|
so the example in question can be rewritten as
var qb = query.Query();
var countQuery = qb.Clone().AsCount();
So I will close this one, since there is no plan for it at the time being.