Replies: 1 comment
-
Thanks for sharing this and good job to make this work 👍 This nicely identifies the main problem we have for supporting such constructs out of the box: Naming the result columns from the subqueries. It's something I want to address someday, but my idea is a bit different that this approach: Instead of mirroring the |
Beta Was this translation helpful? Give feedback.
-
One query I need requires querying through a lot of data with joins, all of which are aggregated before joining. The only way to get good performance with this I've found (in Postgres) is aggregating in a sub-select, the query and join against that.
In many cases, you could do this with a view. But in my case, the values selected for each column, which columns are used for grouping is dynamic, so a view isn't feasible. So, instead, I created this approach. Declare with a macro the columns/selection of the sub-select, create the sub-select, then query it as the 'from' or joined source.
This approach is heavily tailored to what I need, but I thought it worthwhile sharing in case it inspires similar functionality in core diesel. It's probably also not the best approach.
First, declare your sub-select columns:
Then, run your query. You need to turn the underlying queries in to a sub-select query source with
as_query_source()
. This results in the SQL above.The reason I used a struct where you must provide the selection for each column, rather than having that automatic from the macro, is for many columns I use a column selection type which lets me dynamically switch between selecting the column or null (i.e. skip the column), which requires providing a value to the selection at query time.
Below is the code for it, although it's far from well tested and leaves a bunch I didn't need unimplemented. It also may use some local changes to the diesel source (mod visibility), so mightn't compile. This is intended as inspiration/showing a potential approach, than a proper implementation.
Source code (long and messy)
Beta Was this translation helpful? Give feedback.
All reactions