PageRenderTime 33ms CodeModel.GetById 24ms app.highlight 6ms RepoModel.GetById 0ms app.codeStats 0ms

/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 */
16package com.osinka.subset.query
17
18trait ConjunctionStrategy {
19  def conj(q1: Query, q2: Query): Query
20}
21
22object ConjunctionStrategy {
23  object Auto extends ConjunctionStrategy {
24    override def conj(q1: Query, q2: Query): Query = {
25      import collection.JavaConversions._
26
27      lazy val s1 = q1.get.keySet
28      lazy val s2 = q2.get.keySet
29
30      if (s1.isEmpty) q2
31      else if (s2.isEmpty) q1
32      else
33        (q1, q2) match {
34          case (Query.And(ql1), Query.And(ql2)) =>
35            Query.And(ql2 ::: ql1)
36
37          case (Query.And(ql1), _) =>
38            Query.And(q2 :: ql1)
39
40          case (_, Query.And(ql2)) =>
41            Query.And(ql2 ::: q1 :: Nil)
42
43          case _ if (s1 & s2).isEmpty =>
44            Query(q1.queryMutation ~ q2.queryMutation)
45
46          case _ =>
47            Query.And(q2 :: q1 :: Nil)
48        }
49    }
50  }
51
52  object AndQuery extends ConjunctionStrategy {
53    override def conj(q1: Query, q2: Query): Query = {
54      lazy val s1 = q1.get.keySet
55      lazy val s2 = q2.get.keySet
56
57      if (s1.isEmpty) q2
58      else if (s2.isEmpty) q1
59      else
60        (q1, q2) match {
61          case (Query.And(ql1), Query.And(ql2)) =>
62            Query.And(ql2 ::: ql1)
63
64          case (Query.And(ql1), _) =>
65            Query.And(q2 :: ql1)
66
67          case (_, Query.And(ql2)) =>
68            Query.And(ql2 ::: q1 :: Nil)
69
70          case _ =>
71            Query.And(q2 :: q1 :: Nil)
72        }
73    }
74  }
75
76  object Override extends ConjunctionStrategy {
77    override def conj(q1: Query, q2: Query): Query = Query(q1.queryMutation ~ q2.queryMutation)
78  }
79}