| 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, timedelta |
| 16 |
import time |
| 17 |
|
| 18 |
from cassandra.query import FETCH_SIZE_UNSET |
| 19 |
from cassandra.cqlengine import columns |
| 20 |
from cassandra.cqlengine import UnicodeMixin |
| 21 |
from cassandra.cqlengine.functions import QueryValue |
| 22 |
from cassandra.cqlengine.operators import BaseWhereOperator, InOperator, EqualsOperator, IsNotNullOperator |
| 23 |
|
| 24 |
|
| 25 |
class StatementException(Exception): |
| 26 |
pass |
| 27 |
|
| 28 |
|
| 29 |
class ValueQuoter(UnicodeMixin): |
| 30 |
|
| 31 |
def __init__(self, value): |
| 32 |
self.value = value |
| 33 |
|
| 34 |
def __unicode__(self): |
| 35 |
from cassandra.encoder import cql_quote |
| 36 |
if isinstance(self.value, (list, tuple)): |
| 37 |
return '[' + ', '.join([cql_quote(v) for v in self.value]) + ']' |
| 38 |
elif isinstance(self.value, dict): |
| 39 |
return '{' + ', '.join([cql_quote(k) + ':' + cql_quote(v) for k, v in self.value.items()]) + '}' |
| 40 |
elif isinstance(self.value, set): |
| 41 |
return '{' + ', '.join([cql_quote(v) for v in self.value]) + '}' |
| 42 |
return cql_quote(self.value) |
| 43 |
|
| 44 |
def __eq__(self, other): |
| 45 |
if isinstance(other, self.__class__): |
| 46 |
return self.value == other.value |
| 47 |
return False |
| 48 |
|
| 49 |
|
| 50 |
class InQuoter(ValueQuoter): |
| 51 |
|
| 52 |
def __unicode__(self): |
| 53 |
from cassandra.encoder import cql_quote |
| 54 |
return '(' + ', '.join([cql_quote(v) for v in self.value]) + ')' |
| 55 |
|
| 56 |
|
| 57 |
class BaseClause(UnicodeMixin): |
| 58 |
|
| 59 |
def __init__(self, field, value): |
| 60 |
self.field = field |
| 61 |
self.value = value |
| 62 |
self.context_id = None |
| 63 |
|
| 64 |
def __unicode__(self): |
| 65 |
raise NotImplementedError |
| 66 |
|
| 67 |
def __hash__(self): |
| 68 |
return hash(self.field) ^ hash(self.value) |
| 69 |
|
| 70 |
def __eq__(self, other): |
| 71 |
if isinstance(other, self.__class__): |
| 72 |
return self.field == other.field and self.value == other.value |
| 73 |
return False |
| 74 |
|
| 75 |
def __ne__(self, other): |
| 76 |
return not self.__eq__(other) |
| 77 |
|
| 78 |
def get_context_size(self): |
| 79 |
""" returns the number of entries this clause will add to the query context """ |
| 80 |
return 1 |
| 81 |
|
| 82 |
def set_context_id(self, i): |
| 83 |
""" sets the value placeholder that will be used in the query """ |
| 84 |
self.context_id = i |
| 85 |
|
| 86 |
def update_context(self, ctx): |
| 87 |
""" updates the query context with this clauses values """ |
| 88 |
assert isinstance(ctx, dict) |
| 89 |
ctx[str(self.context_id)] = self.value |
| 90 |
|
| 91 |
|
| 92 |
class WhereClause(BaseClause): |
| 93 |
""" a single where statement used in queries """ |
| 94 |
|
| 95 |
def __init__(self, field, operator, value, quote_field=True): |
| 96 |
""" |
| 97 |
|
| 98 |
:param field: |
| 99 |
:param operator: |
| 100 |
:param value: |
| 101 |
:param quote_field: hack to get the token function rendering properly |
| 102 |
:return: |
| 103 |
""" |
| 104 |
if not isinstance(operator, BaseWhereOperator): |
| 105 |
raise StatementException( |
| 106 |
"operator must be of type {0}, got {1}".format(BaseWhereOperator, type(operator)) |
| 107 |
) |
| 108 |
super(WhereClause, self).__init__(field, value) |
| 109 |
self.operator = operator |
| 110 |
self.query_value = self.value if isinstance(self.value, QueryValue) else QueryValue(self.value) |
| 111 |
self.quote_field = quote_field |
| 112 |
|
| 113 |
def __unicode__(self): |
| 114 |
field = ('"{0}"' if self.quote_field else '{0}').format(self.field) |
| 115 |
return u'{0} {1} {2}'.format(field, self.operator, str(self.query_value)) |
| 116 |
|
| 117 |
def __hash__(self): |
| 118 |
return super(WhereClause, self).__hash__() ^ hash(self.operator) |
| 119 |
|
| 120 |
def __eq__(self, other): |
| 121 |
if super(WhereClause, self).__eq__(other): |
| 122 |
return self.operator.__class__ == other.operator.__class__ |
| 123 |
return False |
| 124 |
|
| 125 |
def get_context_size(self): |
| 126 |
return self.query_value.get_context_size() |
| 127 |
|
| 128 |
def set_context_id(self, i): |
| 129 |
super(WhereClause, self).set_context_id(i) |
| 130 |
self.query_value.set_context_id(i) |
| 131 |
|
| 132 |
def update_context(self, ctx): |
| 133 |
if isinstance(self.operator, InOperator): |
| 134 |
ctx[str(self.context_id)] = InQuoter(self.value) |
| 135 |
else: |
| 136 |
self.query_value.update_context(ctx) |
| 137 |
|
| 138 |
|
| 139 |
class IsNotNullClause(WhereClause): |
| 140 |
def __init__(self, field): |
| 141 |
super(IsNotNullClause, self).__init__(field, IsNotNullOperator(), '') |
| 142 |
|
| 143 |
def __unicode__(self): |
| 144 |
field = ('"{0}"' if self.quote_field else '{0}').format(self.field) |
| 145 |
return u'{0} {1}'.format(field, self.operator) |
| 146 |
|
| 147 |
def update_context(self, ctx): |
| 148 |
pass |
| 149 |
|
| 150 |
def get_context_size(self): |
| 151 |
return 0 |
| 152 |
|
| 153 |
# alias for convenience |
| 154 |
IsNotNull = IsNotNullClause |
| 155 |
|
| 156 |
|
| 157 |
class AssignmentClause(BaseClause): |
| 158 |
""" a single variable st statement """ |
| 159 |
|
| 160 |
def __unicode__(self): |
| 161 |
return u'"{0}" = %({1})s'.format(self.field, self.context_id) |
| 162 |
|
| 163 |
def insert_tuple(self): |
| 164 |
return self.field, self.context_id |
| 165 |
|
| 166 |
|
| 167 |
class ConditionalClause(BaseClause): |
| 168 |
""" A single variable iff statement """ |
| 169 |
|
| 170 |
def __unicode__(self): |
| 171 |
return u'"{0}" = %({1})s'.format(self.field, self.context_id) |
| 172 |
|
| 173 |
def insert_tuple(self): |
| 174 |
return self.field, self.context_id |
| 175 |
|
| 176 |
|
| 177 |
class ContainerUpdateTypeMapMeta(type): |
| 178 |
|
| 179 |
def __init__(cls, name, bases, dct): |
| 180 |
if not hasattr(cls, 'type_map'): |
| 181 |
cls.type_map = {} |
| 182 |
else: |
| 183 |
cls.type_map[cls.col_type] = cls |
| 184 |
super(ContainerUpdateTypeMapMeta, cls).__init__(name, bases, dct) |
| 185 |
|
| 186 |
|
| 187 |
class ContainerUpdateClause(AssignmentClause, metaclass=ContainerUpdateTypeMapMeta): |
| 188 |
|
| 189 |
def __init__(self, field, value, operation=None, previous=None): |
| 190 |
super(ContainerUpdateClause, self).__init__(field, value) |
| 191 |
self.previous = previous |
| 192 |
self._assignments = None |
| 193 |
self._operation = operation |
| 194 |
self._analyzed = False |
| 195 |
|
| 196 |
def _analyze(self): |
| 197 |
raise NotImplementedError |
| 198 |
|
| 199 |
def get_context_size(self): |
| 200 |
raise NotImplementedError |
| 201 |
|
| 202 |
def update_context(self, ctx): |
| 203 |
raise NotImplementedError |
| 204 |
|
| 205 |
|
| 206 |
class SetUpdateClause(ContainerUpdateClause): |
| 207 |
""" updates a set collection """ |
| 208 |
|
| 209 |
col_type = columns.Set |
| 210 |
|
| 211 |
_additions = None |
| 212 |
_removals = None |
| 213 |
|
| 214 |
def __unicode__(self): |
| 215 |
qs = [] |
| 216 |
ctx_id = self.context_id |
| 217 |
if (self.previous is None and |
| 218 |
self._assignments is None and |
| 219 |
self._additions is None and |
| 220 |
self._removals is None): |
| 221 |
qs += ['"{0}" = %({1})s'.format(self.field, ctx_id)] |
| 222 |
if self._assignments is not None: |
| 223 |
qs += ['"{0}" = %({1})s'.format(self.field, ctx_id)] |
| 224 |
ctx_id += 1 |
| 225 |
if self._additions is not None: |
| 226 |
qs += ['"{0}" = "{0}" + %({1})s'.format(self.field, ctx_id)] |
| 227 |
ctx_id += 1 |
| 228 |
if self._removals is not None: |
| 229 |
qs += ['"{0}" = "{0}" - %({1})s'.format(self.field, ctx_id)] |
| 230 |
|
| 231 |
return ', '.join(qs) |
| 232 |
|
| 233 |
def _analyze(self): |
| 234 |
""" works out the updates to be performed """ |
| 235 |
if self.value is None or self.value == self.previous: |
| 236 |
pass |
| 237 |
elif self._operation == "add": |
| 238 |
self._additions = self.value |
| 239 |
elif self._operation == "remove": |
| 240 |
self._removals = self.value |
| 241 |
elif self.previous is None: |
| 242 |
self._assignments = self.value |
| 243 |
else: |
| 244 |
# partial update time |
| 245 |
self._additions = (self.value - self.previous) or None |
| 246 |
self._removals = (self.previous - self.value) or None |
| 247 |
self._analyzed = True |
| 248 |
|
| 249 |
def get_context_size(self): |
| 250 |
if not self._analyzed: |
| 251 |
self._analyze() |
| 252 |
if (self.previous is None and |
| 253 |
not self._assignments and |
| 254 |
self._additions is None and |
| 255 |
self._removals is None): |
| 256 |
return 1 |
| 257 |
return int(bool(self._assignments)) + int(bool(self._additions)) + int(bool(self._removals)) |
| 258 |
|
| 259 |
def update_context(self, ctx): |
| 260 |
if not self._analyzed: |
| 261 |
self._analyze() |
| 262 |
ctx_id = self.context_id |
| 263 |
if (self.previous is None and |
| 264 |
self._assignments is None and |
| 265 |
self._additions is None and |
| 266 |
self._removals is None): |
| 267 |
ctx[str(ctx_id)] = set() |
| 268 |
if self._assignments is not None: |
| 269 |
ctx[str(ctx_id)] = self._assignments |
| 270 |
ctx_id += 1 |
| 271 |
if self._additions is not None: |
| 272 |
ctx[str(ctx_id)] = self._additions |
| 273 |
ctx_id += 1 |
| 274 |
if self._removals is not None: |
| 275 |
ctx[str(ctx_id)] = self._removals |
| 276 |
|
| 277 |
|
| 278 |
class ListUpdateClause(ContainerUpdateClause): |
| 279 |
""" updates a list collection """ |
| 280 |
|
| 281 |
col_type = columns.List |
| 282 |
|
| 283 |
_append = None |
| 284 |
_prepend = None |
| 285 |
|
| 286 |
def __unicode__(self): |
| 287 |
if not self._analyzed: |
| 288 |
self._analyze() |
| 289 |
qs = [] |
| 290 |
ctx_id = self.context_id |
| 291 |
if self._assignments is not None: |
| 292 |
qs += ['"{0}" = %({1})s'.format(self.field, ctx_id)] |
| 293 |
ctx_id += 1 |
| 294 |
|
| 295 |
if self._prepend is not None: |
| 296 |
qs += ['"{0}" = %({1})s + "{0}"'.format(self.field, ctx_id)] |
| 297 |
ctx_id += 1 |
| 298 |
|
| 299 |
if self._append is not None: |
| 300 |
qs += ['"{0}" = "{0}" + %({1})s'.format(self.field, ctx_id)] |
| 301 |
|
| 302 |
return ', '.join(qs) |
| 303 |
|
| 304 |
def get_context_size(self): |
| 305 |
if not self._analyzed: |
| 306 |
self._analyze() |
| 307 |
return int(self._assignments is not None) + int(bool(self._append)) + int(bool(self._prepend)) |
| 308 |
|
| 309 |
def update_context(self, ctx): |
| 310 |
if not self._analyzed: |
| 311 |
self._analyze() |
| 312 |
ctx_id = self.context_id |
| 313 |
if self._assignments is not None: |
| 314 |
ctx[str(ctx_id)] = self._assignments |
| 315 |
ctx_id += 1 |
| 316 |
if self._prepend is not None: |
| 317 |
ctx[str(ctx_id)] = self._prepend |
| 318 |
ctx_id += 1 |
| 319 |
if self._append is not None: |
| 320 |
ctx[str(ctx_id)] = self._append |
| 321 |
|
| 322 |
def _analyze(self): |
| 323 |
""" works out the updates to be performed """ |
| 324 |
if self.value is None or self.value == self.previous: |
| 325 |
pass |
| 326 |
|
| 327 |
elif self._operation == "append": |
| 328 |
self._append = self.value |
| 329 |
|
| 330 |
elif self._operation == "prepend": |
| 331 |
self._prepend = self.value |
| 332 |
|
| 333 |
elif self.previous is None: |
| 334 |
self._assignments = self.value |
| 335 |
|
| 336 |
elif len(self.value) < len(self.previous): |
| 337 |
# if elements have been removed, |
| 338 |
# rewrite the whole list |
| 339 |
self._assignments = self.value |
| 340 |
|
| 341 |
elif len(self.previous) == 0: |
| 342 |
# if we're updating from an empty |
| 343 |
# list, do a complete insert |
| 344 |
self._assignments = self.value |
| 345 |
else: |
| 346 |
|
| 347 |
# the max start idx we want to compare |
| 348 |
search_space = len(self.value) - max(0, len(self.previous) - 1) |
| 349 |
|
| 350 |
# the size of the sub lists we want to look at |
| 351 |
search_size = len(self.previous) |
| 352 |
|
| 353 |
for i in range(search_space): |
| 354 |
# slice boundary |
| 355 |
j = i + search_size |
| 356 |
sub = self.value[i:j] |
| 357 |
idx_cmp = lambda idx: self.previous[idx] == sub[idx] |
| 358 |
if idx_cmp(0) and idx_cmp(-1) and self.previous == sub: |
| 359 |
self._prepend = self.value[:i] or None |
| 360 |
self._append = self.value[j:] or None |
| 361 |
break |
| 362 |
|
| 363 |
# if both append and prepend are still None after looking |
| 364 |
# at both lists, an insert statement will be created |
| 365 |
if self._prepend is self._append is None: |
| 366 |
self._assignments = self.value |
| 367 |
|
| 368 |
self._analyzed = True |
| 369 |
|
| 370 |
|
| 371 |
class MapUpdateClause(ContainerUpdateClause): |
| 372 |
""" updates a map collection """ |
| 373 |
|
| 374 |
col_type = columns.Map |
| 375 |
|
| 376 |
_updates = None |
| 377 |
_removals = None |
| 378 |
|
| 379 |
def _analyze(self): |
| 380 |
if self._operation == "update": |
| 381 |
self._updates = self.value.keys() |
| 382 |
elif self._operation == "remove": |
| 383 |
self._removals = {v for v in self.value.keys()} |
| 384 |
else: |
| 385 |
if self.previous is None: |
| 386 |
self._updates = sorted([k for k, v in self.value.items()]) |
| 387 |
else: |
| 388 |
self._updates = sorted([k for k, v in self.value.items() if v != self.previous.get(k)]) or None |
| 389 |
self._analyzed = True |
| 390 |
|
| 391 |
def get_context_size(self): |
| 392 |
if self.is_assignment: |
| 393 |
return 1 |
| 394 |
return int((len(self._updates or []) * 2) + int(bool(self._removals))) |
| 395 |
|
| 396 |
def update_context(self, ctx): |
| 397 |
ctx_id = self.context_id |
| 398 |
if self.is_assignment: |
| 399 |
ctx[str(ctx_id)] = {} |
| 400 |
elif self._removals is not None: |
| 401 |
ctx[str(ctx_id)] = self._removals |
| 402 |
else: |
| 403 |
for key in self._updates or []: |
| 404 |
val = self.value.get(key) |
| 405 |
ctx[str(ctx_id)] = key |
| 406 |
ctx[str(ctx_id + 1)] = val |
| 407 |
ctx_id += 2 |
| 408 |
|
| 409 |
@property |
| 410 |
def is_assignment(self): |
| 411 |
if not self._analyzed: |
| 412 |
self._analyze() |
| 413 |
return self.previous is None and not self._updates and not self._removals |
| 414 |
|
| 415 |
def __unicode__(self): |
| 416 |
qs = [] |
| 417 |
|
| 418 |
ctx_id = self.context_id |
| 419 |
if self.is_assignment: |
| 420 |
qs += ['"{0}" = %({1})s'.format(self.field, ctx_id)] |
| 421 |
elif self._removals is not None: |
| 422 |
qs += ['"{0}" = "{0}" - %({1})s'.format(self.field, ctx_id)] |
| 423 |
ctx_id += 1 |
| 424 |
else: |
| 425 |
for _ in self._updates or []: |
| 426 |
qs += ['"{0}"[%({1})s] = %({2})s'.format(self.field, ctx_id, ctx_id + 1)] |
| 427 |
ctx_id += 2 |
| 428 |
|
| 429 |
return ', '.join(qs) |
| 430 |
|
| 431 |
|
| 432 |
class CounterUpdateClause(AssignmentClause): |
| 433 |
|
| 434 |
col_type = columns.Counter |
| 435 |
|
| 436 |
def __init__(self, field, value, previous=None): |
| 437 |
super(CounterUpdateClause, self).__init__(field, value) |
| 438 |
self.previous = previous or 0 |
| 439 |
|
| 440 |
def get_context_size(self): |
| 441 |
return 1 |
| 442 |
|
| 443 |
def update_context(self, ctx): |
| 444 |
ctx[str(self.context_id)] = abs(self.value - self.previous) |
| 445 |
|
| 446 |
def __unicode__(self): |
| 447 |
delta = self.value - self.previous |
| 448 |
sign = '-' if delta < 0 else '+' |
| 449 |
return '"{0}" = "{0}" {1} %({2})s'.format(self.field, sign, self.context_id) |
| 450 |
|
| 451 |
|
| 452 |
class BaseDeleteClause(BaseClause): |
| 453 |
pass |
| 454 |
|
| 455 |
|
| 456 |
class FieldDeleteClause(BaseDeleteClause): |
| 457 |
""" deletes a field from a row """ |
| 458 |
|
| 459 |
def __init__(self, field): |
| 460 |
super(FieldDeleteClause, self).__init__(field, None) |
| 461 |
|
| 462 |
def __unicode__(self): |
| 463 |
return '"{0}"'.format(self.field) |
| 464 |
|
| 465 |
def update_context(self, ctx): |
| 466 |
pass |
| 467 |
|
| 468 |
def get_context_size(self): |
| 469 |
return 0 |
| 470 |
|
| 471 |
|
| 472 |
class MapDeleteClause(BaseDeleteClause): |
| 473 |
""" removes keys from a map """ |
| 474 |
|
| 475 |
def __init__(self, field, value, previous=None): |
| 476 |
super(MapDeleteClause, self).__init__(field, value) |
| 477 |
self.value = self.value or {} |
| 478 |
self.previous = previous or {} |
| 479 |
self._analyzed = False |
| 480 |
self._removals = None |
| 481 |
|
| 482 |
def _analyze(self): |
| 483 |
self._removals = sorted([k for k in self.previous if k not in self.value]) |
| 484 |
self._analyzed = True |
| 485 |
|
| 486 |
def update_context(self, ctx): |
| 487 |
if not self._analyzed: |
| 488 |
self._analyze() |
| 489 |
for idx, key in enumerate(self._removals): |
| 490 |
ctx[str(self.context_id + idx)] = key |
| 491 |
|
| 492 |
def get_context_size(self): |
| 493 |
if not self._analyzed: |
| 494 |
self._analyze() |
| 495 |
return len(self._removals) |
| 496 |
|
| 497 |
def __unicode__(self): |
| 498 |
if not self._analyzed: |
| 499 |
self._analyze() |
| 500 |
return ', '.join(['"{0}"[%({1})s]'.format(self.field, self.context_id + i) for i in range(len(self._removals))]) |
| 501 |
|
| 502 |
|
| 503 |
class BaseCQLStatement(UnicodeMixin): |
| 504 |
""" The base cql statement class """ |
| 505 |
|
| 506 |
def __init__(self, table, timestamp=None, where=None, fetch_size=None, conditionals=None): |
| 507 |
super(BaseCQLStatement, self).__init__() |
| 508 |
self.table = table |
| 509 |
self.context_id = 0 |
| 510 |
self.context_counter = self.context_id |
| 511 |
self.timestamp = timestamp |
| 512 |
self.fetch_size = fetch_size if fetch_size else FETCH_SIZE_UNSET |
| 513 |
|
| 514 |
self.where_clauses = [] |
| 515 |
for clause in where or []: |
| 516 |
self._add_where_clause(clause) |
| 517 |
|
| 518 |
self.conditionals = [] |
| 519 |
for conditional in conditionals or []: |
| 520 |
self.add_conditional_clause(conditional) |
| 521 |
|
| 522 |
def _update_part_key_values(self, field_index_map, clauses, parts): |
| 523 |
for clause in filter(lambda c: c.field in field_index_map, clauses): |
| 524 |
parts[field_index_map[clause.field]] = clause.value |
| 525 |
|
| 526 |
def partition_key_values(self, field_index_map): |
| 527 |
parts = [None] * len(field_index_map) |
| 528 |
self._update_part_key_values(field_index_map, (w for w in self.where_clauses if w.operator.__class__ == EqualsOperator), parts) |
| 529 |
return parts |
| 530 |
|
| 531 |
def add_where(self, column, operator, value, quote_field=True): |
| 532 |
value = column.to_database(value) |
| 533 |
clause = WhereClause(column.db_field_name, operator, value, quote_field) |
| 534 |
self._add_where_clause(clause) |
| 535 |
|
| 536 |
def _add_where_clause(self, clause): |
| 537 |
clause.set_context_id(self.context_counter) |
| 538 |
self.context_counter += clause.get_context_size() |
| 539 |
self.where_clauses.append(clause) |
| 540 |
|
| 541 |
def get_context(self): |
| 542 |
""" |
| 543 |
returns the context dict for this statement |
| 544 |
:rtype: dict |
| 545 |
""" |
| 546 |
ctx = {} |
| 547 |
for clause in self.where_clauses or []: |
| 548 |
clause.update_context(ctx) |
| 549 |
return ctx |
| 550 |
|
| 551 |
def add_conditional_clause(self, clause): |
| 552 |
""" |
| 553 |
Adds a iff clause to this statement |
| 554 |
|
| 555 |
:param clause: The clause that will be added to the iff statement |
| 556 |
:type clause: ConditionalClause |
| 557 |
""" |
| 558 |
clause.set_context_id(self.context_counter) |
| 559 |
self.context_counter += clause.get_context_size() |
| 560 |
self.conditionals.append(clause) |
| 561 |
|
| 562 |
def _get_conditionals(self): |
| 563 |
return 'IF {0}'.format(' AND '.join([str(c) for c in self.conditionals])) |
| 564 |
|
| 565 |
def get_context_size(self): |
| 566 |
return len(self.get_context()) |
| 567 |
|
| 568 |
def update_context_id(self, i): |
| 569 |
self.context_id = i |
| 570 |
self.context_counter = self.context_id |
| 571 |
for clause in self.where_clauses: |
| 572 |
clause.set_context_id(self.context_counter) |
| 573 |
self.context_counter += clause.get_context_size() |
| 574 |
|
| 575 |
@property |
| 576 |
def timestamp_normalized(self): |
| 577 |
""" |
| 578 |
we're expecting self.timestamp to be either a long, int, a datetime, or a timedelta |
| 579 |
:return: |
| 580 |
""" |
| 581 |
if not self.timestamp: |
| 582 |
return None |
| 583 |
|
| 584 |
if isinstance(self.timestamp, int): |
| 585 |
return self.timestamp |
| 586 |
|
| 587 |
if isinstance(self.timestamp, timedelta): |
| 588 |
tmp = datetime.now() + self.timestamp |
| 589 |
else: |
| 590 |
tmp = self.timestamp |
| 591 |
|
| 592 |
return int(time.mktime(tmp.timetuple()) * 1e+6 + tmp.microsecond) |
| 593 |
|
| 594 |
def __unicode__(self): |
| 595 |
raise NotImplementedError |
| 596 |
|
| 597 |
def __repr__(self): |
| 598 |
return self.__unicode__() |
| 599 |
|
| 600 |
@property |
| 601 |
def _where(self): |
| 602 |
return 'WHERE {0}'.format(' AND '.join([str(c) for c in self.where_clauses])) |
| 603 |
|
| 604 |
|
| 605 |
class SelectStatement(BaseCQLStatement): |
| 606 |
""" a cql select statement """ |
| 607 |
|
| 608 |
def __init__(self, |
| 609 |
table, |
| 610 |
fields=None, |
| 611 |
count=False, |
| 612 |
where=None, |
| 613 |
order_by=None, |
| 614 |
limit=None, |
| 615 |
allow_filtering=False, |
| 616 |
distinct_fields=None, |
| 617 |
fetch_size=None): |
| 618 |
|
| 619 |
""" |
| 620 |
:param where |
| 621 |
:type where list of cqlengine.statements.WhereClause |
| 622 |
""" |
| 623 |
super(SelectStatement, self).__init__( |
| 624 |
table, |
| 625 |
where=where, |
| 626 |
fetch_size=fetch_size |
| 627 |
) |
| 628 |
|
| 629 |
self.fields = [fields] if isinstance(fields, str) else (fields or []) |
| 630 |
self.distinct_fields = distinct_fields |
| 631 |
self.count = count |
| 632 |
self.order_by = [order_by] if isinstance(order_by, str) else order_by |
| 633 |
self.limit = limit |
| 634 |
self.allow_filtering = allow_filtering |
| 635 |
|
| 636 |
def __unicode__(self): |
| 637 |
qs = ['SELECT'] |
| 638 |
if self.distinct_fields: |
| 639 |
if self.count: |
| 640 |
qs += ['DISTINCT COUNT({0})'.format(', '.join(['"{0}"'.format(f) for f in self.distinct_fields]))] |
| 641 |
else: |
| 642 |
qs += ['DISTINCT {0}'.format(', '.join(['"{0}"'.format(f) for f in self.distinct_fields]))] |
| 643 |
elif self.count: |
| 644 |
qs += ['COUNT(*)'] |
| 645 |
else: |
| 646 |
qs += [', '.join(['"{0}"'.format(f) for f in self.fields]) if self.fields else '*'] |
| 647 |
qs += ['FROM', self.table] |
| 648 |
|
| 649 |
if self.where_clauses: |
| 650 |
qs += [self._where] |
| 651 |
|
| 652 |
if self.order_by and not self.count: |
| 653 |
qs += ['ORDER BY {0}'.format(', '.join(str(o) for o in self.order_by))] |
| 654 |
|
| 655 |
if self.limit: |
| 656 |
qs += ['LIMIT {0}'.format(self.limit)] |
| 657 |
|
| 658 |
if self.allow_filtering: |
| 659 |
qs += ['ALLOW FILTERING'] |
| 660 |
|
| 661 |
return ' '.join(qs) |
| 662 |
|
| 663 |
|
| 664 |
class AssignmentStatement(BaseCQLStatement): |
| 665 |
""" value assignment statements """ |
| 666 |
|
| 667 |
def __init__(self, |
| 668 |
table, |
| 669 |
assignments=None, |
| 670 |
where=None, |
| 671 |
ttl=None, |
| 672 |
timestamp=None, |
| 673 |
conditionals=None): |
| 674 |
super(AssignmentStatement, self).__init__( |
| 675 |
table, |
| 676 |
where=where, |
| 677 |
conditionals=conditionals |
| 678 |
) |
| 679 |
self.ttl = ttl |
| 680 |
self.timestamp = timestamp |
| 681 |
|
| 682 |
# add assignments |
| 683 |
self.assignments = [] |
| 684 |
for assignment in assignments or []: |
| 685 |
self._add_assignment_clause(assignment) |
| 686 |
|
| 687 |
def update_context_id(self, i): |
| 688 |
super(AssignmentStatement, self).update_context_id(i) |
| 689 |
for assignment in self.assignments: |
| 690 |
assignment.set_context_id(self.context_counter) |
| 691 |
self.context_counter += assignment.get_context_size() |
| 692 |
|
| 693 |
def partition_key_values(self, field_index_map): |
| 694 |
parts = super(AssignmentStatement, self).partition_key_values(field_index_map) |
| 695 |
self._update_part_key_values(field_index_map, self.assignments, parts) |
| 696 |
return parts |
| 697 |
|
| 698 |
def add_assignment(self, column, value): |
| 699 |
value = column.to_database(value) |
| 700 |
clause = AssignmentClause(column.db_field_name, value) |
| 701 |
self._add_assignment_clause(clause) |
| 702 |
|
| 703 |
def _add_assignment_clause(self, clause): |
| 704 |
clause.set_context_id(self.context_counter) |
| 705 |
self.context_counter += clause.get_context_size() |
| 706 |
self.assignments.append(clause) |
| 707 |
|
| 708 |
@property |
| 709 |
def is_empty(self): |
| 710 |
return len(self.assignments) == 0 |
| 711 |
|
| 712 |
def get_context(self): |
| 713 |
ctx = super(AssignmentStatement, self).get_context() |
| 714 |
for clause in self.assignments: |
| 715 |
clause.update_context(ctx) |
| 716 |
return ctx |
| 717 |
|
| 718 |
|
| 719 |
class InsertStatement(AssignmentStatement): |
| 720 |
""" an cql insert statement """ |
| 721 |
|
| 722 |
def __init__(self, |
| 723 |
table, |
| 724 |
assignments=None, |
| 725 |
where=None, |
| 726 |
ttl=None, |
| 727 |
timestamp=None, |
| 728 |
if_not_exists=False): |
| 729 |
super(InsertStatement, self).__init__(table, |
| 730 |
assignments=assignments, |
| 731 |
where=where, |
| 732 |
ttl=ttl, |
| 733 |
timestamp=timestamp) |
| 734 |
|
| 735 |
self.if_not_exists = if_not_exists |
| 736 |
|
| 737 |
def __unicode__(self): |
| 738 |
qs = ['INSERT INTO {0}'.format(self.table)] |
| 739 |
|
| 740 |
# get column names and context placeholders |
| 741 |
fields = [a.insert_tuple() for a in self.assignments] |
| 742 |
columns, values = zip(*fields) |
| 743 |
|
| 744 |
qs += ["({0})".format(', '.join(['"{0}"'.format(c) for c in columns]))] |
| 745 |
qs += ['VALUES'] |
| 746 |
qs += ["({0})".format(', '.join(['%({0})s'.format(v) for v in values]))] |
| 747 |
|
| 748 |
if self.if_not_exists: |
| 749 |
qs += ["IF NOT EXISTS"] |
| 750 |
|
| 751 |
using_options = [] |
| 752 |
if self.ttl: |
| 753 |
using_options += ["TTL {}".format(self.ttl)] |
| 754 |
|
| 755 |
if self.timestamp: |
| 756 |
using_options += ["TIMESTAMP {}".format(self.timestamp_normalized)] |
| 757 |
|
| 758 |
if using_options: |
| 759 |
qs += ["USING {}".format(" AND ".join(using_options))] |
| 760 |
return ' '.join(qs) |
| 761 |
|
| 762 |
|
| 763 |
class UpdateStatement(AssignmentStatement): |
| 764 |
""" an cql update select statement """ |
| 765 |
|
| 766 |
def __init__(self, |
| 767 |
table, |
| 768 |
assignments=None, |
| 769 |
where=None, |
| 770 |
ttl=None, |
| 771 |
timestamp=None, |
| 772 |
conditionals=None, |
| 773 |
if_exists=False): |
| 774 |
super(UpdateStatement, self). __init__(table, |
| 775 |
assignments=assignments, |
| 776 |
where=where, |
| 777 |
ttl=ttl, |
| 778 |
timestamp=timestamp, |
| 779 |
conditionals=conditionals) |
| 780 |
|
| 781 |
self.if_exists = if_exists |
| 782 |
|
| 783 |
def __unicode__(self): |
| 784 |
qs = ['UPDATE', self.table] |
| 785 |
|
| 786 |
using_options = [] |
| 787 |
|
| 788 |
if self.ttl: |
| 789 |
using_options += ["TTL {0}".format(self.ttl)] |
| 790 |
|
| 791 |
if self.timestamp: |
| 792 |
using_options += ["TIMESTAMP {0}".format(self.timestamp_normalized)] |
| 793 |
|
| 794 |
if using_options: |
| 795 |
qs += ["USING {0}".format(" AND ".join(using_options))] |
| 796 |
|
| 797 |
qs += ['SET'] |
| 798 |
qs += [', '.join([str(c) for c in self.assignments])] |
| 799 |
|
| 800 |
if self.where_clauses: |
| 801 |
qs += [self._where] |
| 802 |
|
| 803 |
if len(self.conditionals) > 0: |
| 804 |
qs += [self._get_conditionals()] |
| 805 |
|
| 806 |
if self.if_exists: |
| 807 |
qs += ["IF EXISTS"] |
| 808 |
|
| 809 |
return ' '.join(qs) |
| 810 |
|
| 811 |
def get_context(self): |
| 812 |
ctx = super(UpdateStatement, self).get_context() |
| 813 |
for clause in self.conditionals: |
| 814 |
clause.update_context(ctx) |
| 815 |
return ctx |
| 816 |
|
| 817 |
def update_context_id(self, i): |
| 818 |
super(UpdateStatement, self).update_context_id(i) |
| 819 |
for conditional in self.conditionals: |
| 820 |
conditional.set_context_id(self.context_counter) |
| 821 |
self.context_counter += conditional.get_context_size() |
| 822 |
|
| 823 |
def add_update(self, column, value, operation=None, previous=None): |
| 824 |
value = column.to_database(value) |
| 825 |
col_type = type(column) |
| 826 |
container_update_type = ContainerUpdateClause.type_map.get(col_type) |
| 827 |
if container_update_type: |
| 828 |
previous = column.to_database(previous) |
| 829 |
clause = container_update_type(column.db_field_name, value, operation, previous) |
| 830 |
elif col_type == columns.Counter: |
| 831 |
clause = CounterUpdateClause(column.db_field_name, value, previous) |
| 832 |
else: |
| 833 |
clause = AssignmentClause(column.db_field_name, value) |
| 834 |
if clause.get_context_size(): # this is to exclude map removals from updates. Can go away if we drop support for C* < 1.2.4 and remove two-phase updates |
| 835 |
self._add_assignment_clause(clause) |
| 836 |
|
| 837 |
|
| 838 |
class DeleteStatement(BaseCQLStatement): |
| 839 |
""" a cql delete statement """ |
| 840 |
|
| 841 |
def __init__(self, table, fields=None, where=None, timestamp=None, conditionals=None, if_exists=False): |
| 842 |
super(DeleteStatement, self).__init__( |
| 843 |
table, |
| 844 |
where=where, |
| 845 |
timestamp=timestamp, |
| 846 |
conditionals=conditionals |
| 847 |
) |
| 848 |
self.fields = [] |
| 849 |
if isinstance(fields, str): |
| 850 |
fields = [fields] |
| 851 |
for field in fields or []: |
| 852 |
self.add_field(field) |
| 853 |
|
| 854 |
self.if_exists = if_exists |
| 855 |
|
| 856 |
def update_context_id(self, i): |
| 857 |
super(DeleteStatement, self).update_context_id(i) |
| 858 |
for field in self.fields: |
| 859 |
field.set_context_id(self.context_counter) |
| 860 |
self.context_counter += field.get_context_size() |
| 861 |
for t in self.conditionals: |
| 862 |
t.set_context_id(self.context_counter) |
| 863 |
self.context_counter += t.get_context_size() |
| 864 |
|
| 865 |
def get_context(self): |
| 866 |
ctx = super(DeleteStatement, self).get_context() |
| 867 |
for field in self.fields: |
| 868 |
field.update_context(ctx) |
| 869 |
for clause in self.conditionals: |
| 870 |
clause.update_context(ctx) |
| 871 |
return ctx |
| 872 |
|
| 873 |
def add_field(self, field): |
| 874 |
if isinstance(field, str): |
| 875 |
field = FieldDeleteClause(field) |
| 876 |
if not isinstance(field, BaseClause): |
| 877 |
raise StatementException("only instances of AssignmentClause can be added to statements") |
| 878 |
field.set_context_id(self.context_counter) |
| 879 |
self.context_counter += field.get_context_size() |
| 880 |
self.fields.append(field) |
| 881 |
|
| 882 |
def __unicode__(self): |
| 883 |
qs = ['DELETE'] |
| 884 |
if self.fields: |
| 885 |
qs += [', '.join(['{0}'.format(f) for f in self.fields])] |
| 886 |
qs += ['FROM', self.table] |
| 887 |
|
| 888 |
delete_option = [] |
| 889 |
|
| 890 |
if self.timestamp: |
| 891 |
delete_option += ["TIMESTAMP {0}".format(self.timestamp_normalized)] |
| 892 |
|
| 893 |
if delete_option: |
| 894 |
qs += [" USING {0} ".format(" AND ".join(delete_option))] |
| 895 |
|
| 896 |
if self.where_clauses: |
| 897 |
qs += [self._where] |
| 898 |
|
| 899 |
if self.conditionals: |
| 900 |
qs += [self._get_conditionals()] |
| 901 |
|
| 902 |
if self.if_exists: |
| 903 |
qs += ["IF EXISTS"] |
| 904 |
|
| 905 |
return ' '.join(qs) |