/src/main/scala/query/ConjunctionStrategy.scala

http://github.com/osinka/subset · Scala · 79 lines · 50 code · 14 blank · 15 comment · 7 complexity · 1971965b70fdebb62da3353b613a5d1e MD5 · raw file

  1. /**
  2. * Copyright (C) 2011 Alexander Azarov <azarov@osinka.com>
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.osinka.subset.query
  17. trait ConjunctionStrategy {
  18. def conj(q1: Query, q2: Query): Query
  19. }
  20. object ConjunctionStrategy {
  21. object Auto extends ConjunctionStrategy {
  22. override def conj(q1: Query, q2: Query): Query = {
  23. import collection.JavaConversions._
  24. lazy val s1 = q1.get.keySet
  25. lazy val s2 = q2.get.keySet
  26. if (s1.isEmpty) q2
  27. else if (s2.isEmpty) q1
  28. else
  29. (q1, q2) match {
  30. case (Query.And(ql1), Query.And(ql2)) =>
  31. Query.And(ql2 ::: ql1)
  32. case (Query.And(ql1), _) =>
  33. Query.And(q2 :: ql1)
  34. case (_, Query.And(ql2)) =>
  35. Query.And(ql2 ::: q1 :: Nil)
  36. case _ if (s1 & s2).isEmpty =>
  37. Query(q1.queryMutation ~ q2.queryMutation)
  38. case _ =>
  39. Query.And(q2 :: q1 :: Nil)
  40. }
  41. }
  42. }
  43. object AndQuery extends ConjunctionStrategy {
  44. override def conj(q1: Query, q2: Query): Query = {
  45. lazy val s1 = q1.get.keySet
  46. lazy val s2 = q2.get.keySet
  47. if (s1.isEmpty) q2
  48. else if (s2.isEmpty) q1
  49. else
  50. (q1, q2) match {
  51. case (Query.And(ql1), Query.And(ql2)) =>
  52. Query.And(ql2 ::: ql1)
  53. case (Query.And(ql1), _) =>
  54. Query.And(q2 :: ql1)
  55. case (_, Query.And(ql2)) =>
  56. Query.And(ql2 ::: q1 :: Nil)
  57. case _ =>
  58. Query.And(q2 :: q1 :: Nil)
  59. }
  60. }
  61. }
  62. object Override extends ConjunctionStrategy {
  63. override def conj(q1: Query, q2: Query): Query = Query(q1.queryMutation ~ q2.queryMutation)
  64. }
  65. }