11from collections import namedtuple
22from typing import Any
33from typing import List
4- from typing import NamedTuple
54
65CONDITION_OR = "|"
76CONDITION_AND = "&"
1110CONDITION_LT = "<"
1211CONDITION_LE = "<="
1312
14- QueryCondition = namedtuple ("QueryCondition" , ("condition" , "query " , "pair " ))
13+ QueryCondition = namedtuple ("QueryCondition" , ("condition" , "pair " , "item " ))
1514
1615
1716class Condition :
1817 def __init__ (self , key : str , value : Any , condition_type : str ):
1918 self ._key = key
2019 self ._value = value
2120 self ._type = condition_type
22- self ._condition_set = [] # type: List[NamedTuple]
21+ self ._condition_set : List [QueryCondition ] = [
22+ QueryCondition (CONDITION_AND , {key : value }, self )
23+ ]
2324
2425 @staticmethod
2526 def get_empty_condition ():
@@ -32,13 +33,10 @@ def __or__(self, other):
3233 if not isinstance (other , Condition ):
3334 raise Exception ("Support the only Condition types" )
3435
35- self ._condition_set .append (
36- QueryCondition (
37- CONDITION_OR ,
38- other .build_query (),
39- {other ._key : other ._value } if type (other ) == Condition else {},
36+ for _condition in other ._condition_set :
37+ self ._condition_set .append (
38+ QueryCondition (CONDITION_OR , _condition .pair , _condition .item )
4039 )
41- )
4240 return self
4341
4442 def __and__ (self , other ):
@@ -52,19 +50,23 @@ def __and__(self, other):
5250 elif not isinstance (other , (Condition , EmptyCondition )):
5351 raise Exception ("Support the only Condition types" )
5452
55- self ._condition_set .append (
56- QueryCondition (
57- CONDITION_AND ,
58- other .build_query (),
59- {other ._key : other ._value } if type (other ) == Condition else {},
53+ for _condition in other ._condition_set :
54+ self ._condition_set .append (
55+ QueryCondition (CONDITION_AND , _condition .pair , _condition .item )
6056 )
61- )
6257 return self
6358
59+ def _build (self ):
60+ return f"{ self ._key } { self ._type } { self ._value } "
61+
6462 def build_query (self ):
65- return str (self ) + "" .join (
66- [f"{ condition [0 ]} { condition [1 ]} " for condition in self ._condition_set ]
67- )
63+ items = []
64+ for condition in self ._condition_set :
65+ if not items :
66+ items .append (condition .item ._build ())
67+ else :
68+ items .extend ([condition .condition , condition .item ._build ()])
69+ return "" .join (items )
6870
6971 def get_as_params_dict (self ) -> dict :
7072 params = None if isinstance (self , EmptyCondition ) else {self ._key : self ._value }
@@ -75,7 +77,7 @@ def get_as_params_dict(self) -> dict:
7577
7678class EmptyCondition (Condition ):
7779 def __init__ (self , * args , ** kwargs ): # noqa
78- ...
80+ self . _condition_set = []
7981
8082 def __or__ (self , other ):
8183 return other
0 commit comments