Debian Codegraph @

cassandra/cqlengine/functions.py

raw
1 # Copyright DataStax, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 from datetime import datetime
16
17 from cassandra.cqlengine import UnicodeMixin, ValidationError
18
19 def get_total_seconds(td):
20 return td.total_seconds()
21
22 class QueryValue(UnicodeMixin):
23 """
24 Base class for query filter values. Subclasses of these classes can
25 be passed into .filter() keyword args
26 """
27
28 format_string = '%({0})s'
29
30 def __init__(self, value):
31 self.value = value
32 self.context_id = None
33
34 def __unicode__(self):
35 return self.format_string.format(self.context_id)
36
37 def set_context_id(self, ctx_id):
38 self.context_id = ctx_id
39
40 def get_context_size(self):
41 return 1
42
43 def update_context(self, ctx):
44 ctx[str(self.context_id)] = self.value
45
46
47 class BaseQueryFunction(QueryValue):
48 """
49 Base class for filtering functions. Subclasses of these classes can
50 be passed into .filter() and will be translated into CQL functions in
51 the resulting query
52 """
53 pass
54
55
56 class TimeUUIDQueryFunction(BaseQueryFunction):
57
58 def __init__(self, value):
59 """
60 :param value: the time to create bounding time uuid from
61 :type value: datetime
62 """
63 if not isinstance(value, datetime):
64 raise ValidationError('datetime instance is required')
65 super(TimeUUIDQueryFunction, self).__init__(value)
66
67 def to_database(self, val):
68 epoch = datetime(1970, 1, 1, tzinfo=val.tzinfo)
69 offset = get_total_seconds(epoch.tzinfo.utcoffset(epoch)) if epoch.tzinfo else 0
70 return int((get_total_seconds(val - epoch) - offset) * 1000)
71
72 def update_context(self, ctx):
73 ctx[str(self.context_id)] = self.to_database(self.value)
74
75
76 class MinTimeUUID(TimeUUIDQueryFunction):
77 """
78 return a fake timeuuid corresponding to the smallest possible timeuuid for the given timestamp
79
80 http://cassandra.apache.org/doc/cql3/CQL-3.0.html#timeuuidFun
81 """
82 format_string = 'MinTimeUUID(%({0})s)'
83
84
85 class MaxTimeUUID(TimeUUIDQueryFunction):
86 """
87 return a fake timeuuid corresponding to the largest possible timeuuid for the given timestamp
88
89 http://cassandra.apache.org/doc/cql3/CQL-3.0.html#timeuuidFun
90 """
91 format_string = 'MaxTimeUUID(%({0})s)'
92
93
94 class Token(BaseQueryFunction):
95 """
96 compute the token for a given partition key
97
98 http://cassandra.apache.org/doc/cql3/CQL-3.0.html#tokenFun
99 """
100 def __init__(self, *values):
101 if len(values) == 1 and isinstance(values[0], (list, tuple)):
102 values = values[0]
103 super(Token, self).__init__(values)
104 self._columns = None
105
106 def set_columns(self, columns):
107 self._columns = columns
108
109 def get_context_size(self):
110 return len(self.value)
111
112 def __unicode__(self):
113 token_args = ', '.join('%({0})s'.format(self.context_id + i) for i in range(self.get_context_size()))
114 return "token({0})".format(token_args)
115
116 def update_context(self, ctx):
117 for i, (col, val) in enumerate(zip(self._columns, self.value)):
118 ctx[str(self.context_id + i)] = col.to_database(val)