aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/xyz/driver/pdsuicommon/db/Sorting.scala
blob: 4b2427c08dcebedf421704e1a9fc3ba583fcec9f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package xyz.driver.pdsuicommon.db

import xyz.driver.pdsuicommon.logging._

import scala.collection.generic.CanBuildFrom

sealed trait SortingOrder
object SortingOrder {

  case object Ascending extends SortingOrder
  case object Descending extends SortingOrder

}

sealed trait Sorting

object Sorting {

  val Empty = Sequential(Seq.empty)

  /**
    * @param tableName None if the table is default (same)
    * @param name      Dimension name
    * @param order     Order
    */
  case class Dimension(tableName: Option[String], name: String, order: SortingOrder) extends Sorting {
    def isForeign: Boolean = tableName.isDefined
  }

  case class Sequential(sorting: Seq[Dimension]) extends Sorting {
    override def toString: String = if (isEmpty(this)) "Empty" else super.toString
  }

  def isEmpty(input: Sorting): Boolean = {
    input match {
      case Sequential(Seq()) => true
      case _ => false
    }
  }

  def filter(sorting: Sorting, p: Dimension => Boolean): Seq[Dimension] = sorting match {
    case x: Dimension if p(x) => Seq(x)
    case x: Dimension => Seq.empty
    case Sequential(xs) => xs.filter(p)
  }

  def collect[B, That](sorting: Sorting)
                      (f: PartialFunction[Dimension, B])
                      (implicit bf: CanBuildFrom[Seq[Dimension], B, That]): That = sorting match {
    case x: Dimension if f.isDefinedAt(x) =>
      val r = bf.apply()
      r += f(x)
      r.result()

    case x: Dimension => bf.apply().result()
    case Sequential(xs) => xs.collect(f)
  }

  // Contains dimensions and ordering only, thus it is safe.
  implicit def toPhiString(x: Sorting): PhiString = Unsafe(x.toString)

}