Skip to content

Add groupByOrdered functions #252

Open
@sake92

Description

@sake92

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions