Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add groupByOrdered functions #252

Open
sake92 opened this issue Aug 9, 2024 · 0 comments
Open

Add groupByOrdered functions #252

sake92 opened this issue Aug 9, 2024 · 0 comments

Comments

@sake92
Copy link

sake92 commented Aug 9, 2024

Motivation

When querying relational databases you usually get a flat result (unless using an ORM).
But on the API layer you usually want to expose that information as structured object (usually JSON).
The current groupBy methods do not maintain the original ordering, so you have to be careful not to destroy the ordering you get from an SQL query.

Implementation

Here is my current implementation: https://github.com/sake92/squery/blob/main/squery/src/ba/sake/squery/utils/seqUtils.scala
It's using a mutable.LinkedHashMap.
Not sure if it can be optimized, I'm not a perf expert.

There are 3 variations:

  • def groupByOrdered[K, V](extractKey: T => K): Map[K, Seq[T]] -> just groups the results by key, and puts them in a map
  • def groupByOrdered[K, V](extractKey: T => K, extractValue: T => V): Map[K, Seq[V]] -> same as above, but you can extract the result value too, sometimes you don't need everything that query returned
  • def groupByOrderedOpt[K, V](extractKey: T => K, extractValue: T => Option[V]): Map[K, Seq[V]] -> same as above, but it flattens the Options, very useful when you have a LEFT JOIN
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant