| 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 |
import copy |
| 16 |
from datetime import datetime, timedelta |
| 17 |
from functools import partial |
| 18 |
import time |
| 19 |
from warnings import warn |
| 20 |
|
| 21 |
from cassandra.query import SimpleStatement, BatchType as CBatchType, BatchStatement |
| 22 |
from cassandra.cqlengine import columns, CQLEngineException, ValidationError, UnicodeMixin |
| 23 |
from cassandra.cqlengine import connection as conn |
| 24 |
from cassandra.cqlengine.functions import Token, BaseQueryFunction, QueryValue |
| 25 |
from cassandra.cqlengine.operators import (InOperator, EqualsOperator, GreaterThanOperator, |
| 26 |
GreaterThanOrEqualOperator, LessThanOperator, |
| 27 |
LessThanOrEqualOperator, ContainsOperator, BaseWhereOperator) |
| 28 |
from cassandra.cqlengine.statements import (WhereClause, SelectStatement, DeleteStatement, |
| 29 |
UpdateStatement, InsertStatement, |
| 30 |
BaseCQLStatement, MapDeleteClause, ConditionalClause) |
| 31 |
|
| 32 |
|
| 33 |
class QueryException(CQLEngineException): |
| 34 |
pass |
| 35 |
|
| 36 |
|
| 37 |
class IfNotExistsWithCounterColumn(CQLEngineException): |
| 38 |
pass |
| 39 |
|
| 40 |
|
| 41 |
class IfExistsWithCounterColumn(CQLEngineException): |
| 42 |
pass |
| 43 |
|
| 44 |
|
| 45 |
class LWTException(CQLEngineException): |
| 46 |
"""Lightweight conditional exception. |
| 47 |
|
| 48 |
This exception will be raised when a write using an `IF` clause could not be |
| 49 |
applied due to existing data violating the condition. The existing data is |
| 50 |
available through the ``existing`` attribute. |
| 51 |
|
| 52 |
:param existing: The current state of the data which prevented the write. |
| 53 |
""" |
| 54 |
def __init__(self, existing): |
| 55 |
super(LWTException, self).__init__("LWT Query was not applied") |
| 56 |
self.existing = existing |
| 57 |
|
| 58 |
|
| 59 |
class DoesNotExist(QueryException): |
| 60 |
pass |
| 61 |
|
| 62 |
|
| 63 |
class MultipleObjectsReturned(QueryException): |
| 64 |
pass |
| 65 |
|
| 66 |
|
| 67 |
def check_applied(result): |
| 68 |
""" |
| 69 |
Raises LWTException if it looks like a failed LWT request. A LWTException |
| 70 |
won't be raised in the special case in which there are several failed LWT |
| 71 |
in a :class:`~cqlengine.query.BatchQuery`. |
| 72 |
""" |
| 73 |
try: |
| 74 |
applied = result.was_applied |
| 75 |
except Exception: |
| 76 |
applied = True # result was not LWT form |
| 77 |
if not applied: |
| 78 |
raise LWTException(result.one()) |
| 79 |
|
| 80 |
|
| 81 |
class AbstractQueryableColumn(UnicodeMixin): |
| 82 |
""" |
| 83 |
exposes cql query operators through pythons |
| 84 |
builtin comparator symbols |
| 85 |
""" |
| 86 |
|
| 87 |
def _get_column(self): |
| 88 |
raise NotImplementedError |
| 89 |
|
| 90 |
def __unicode__(self): |
| 91 |
raise NotImplementedError |
| 92 |
|
| 93 |
def _to_database(self, val): |
| 94 |
if isinstance(val, QueryValue): |
| 95 |
return val |
| 96 |
else: |
| 97 |
return self._get_column().to_database(val) |
| 98 |
|
| 99 |
def in_(self, item): |
| 100 |
""" |
| 101 |
Returns an in operator |
| 102 |
|
| 103 |
used where you'd typically want to use python's `in` operator |
| 104 |
""" |
| 105 |
return WhereClause(str(self), InOperator(), item) |
| 106 |
|
| 107 |
def contains_(self, item): |
| 108 |
""" |
| 109 |
Returns a CONTAINS operator |
| 110 |
""" |
| 111 |
return WhereClause(str(self), ContainsOperator(), item) |
| 112 |
|
| 113 |
|
| 114 |
def __eq__(self, other): |
| 115 |
return WhereClause(str(self), EqualsOperator(), self._to_database(other)) |
| 116 |
|
| 117 |
def __gt__(self, other): |
| 118 |
return WhereClause(str(self), GreaterThanOperator(), self._to_database(other)) |
| 119 |
|
| 120 |
def __ge__(self, other): |
| 121 |
return WhereClause(str(self), GreaterThanOrEqualOperator(), self._to_database(other)) |
| 122 |
|
| 123 |
def __lt__(self, other): |
| 124 |
return WhereClause(str(self), LessThanOperator(), self._to_database(other)) |
| 125 |
|
| 126 |
def __le__(self, other): |
| 127 |
return WhereClause(str(self), LessThanOrEqualOperator(), self._to_database(other)) |
| 128 |
|
| 129 |
|
| 130 |
class BatchType(object): |
| 131 |
Unlogged = 'UNLOGGED' |
| 132 |
Counter = 'COUNTER' |
| 133 |
|
| 134 |
|
| 135 |
class BatchQuery(object): |
| 136 |
""" |
| 137 |
Handles the batching of queries |
| 138 |
|
| 139 |
http://docs.datastax.com/en/cql/3.0/cql/cql_reference/batch_r.html |
| 140 |
|
| 141 |
See :doc:`/cqlengine/batches` for more details. |
| 142 |
""" |
| 143 |
warn_multiple_exec = True |
| 144 |
|
| 145 |
_consistency = None |
| 146 |
|
| 147 |
_connection = None |
| 148 |
_connection_explicit = False |
| 149 |
|
| 150 |
|
| 151 |
def __init__(self, batch_type=None, timestamp=None, consistency=None, execute_on_exception=False, |
| 152 |
timeout=conn.NOT_SET, connection=None): |
| 153 |
""" |
| 154 |
:param batch_type: (optional) One of batch type values available through BatchType enum |
| 155 |
:type batch_type: BatchType, str or None |
| 156 |
:param timestamp: (optional) A datetime or timedelta object with desired timestamp to be applied |
| 157 |
to the batch conditional. |
| 158 |
:type timestamp: datetime or timedelta or None |
| 159 |
:param consistency: (optional) One of consistency values ("ANY", "ONE", "QUORUM" etc) |
| 160 |
:type consistency: The :class:`.ConsistencyLevel` to be used for the batch query, or None. |
| 161 |
:param execute_on_exception: (Defaults to False) Indicates that when the BatchQuery instance is used |
| 162 |
as a context manager the queries accumulated within the context must be executed despite |
| 163 |
encountering an error within the context. By default, any exception raised from within |
| 164 |
the context scope will cause the batched queries not to be executed. |
| 165 |
:type execute_on_exception: bool |
| 166 |
:param timeout: (optional) Timeout for the entire batch (in seconds), if not specified fallback |
| 167 |
to default session timeout |
| 168 |
:type timeout: float or None |
| 169 |
:param str connection: Connection name to use for the batch execution |
| 170 |
""" |
| 171 |
self.queries = [] |
| 172 |
self.batch_type = batch_type |
| 173 |
if timestamp is not None and not isinstance(timestamp, (datetime, timedelta)): |
| 174 |
raise CQLEngineException('timestamp object must be an instance of datetime') |
| 175 |
self.timestamp = timestamp |
| 176 |
self._consistency = consistency |
| 177 |
self._execute_on_exception = execute_on_exception |
| 178 |
self._timeout = timeout |
| 179 |
self._callbacks = [] |
| 180 |
self._executed = False |
| 181 |
self._context_entered = False |
| 182 |
self._connection = connection |
| 183 |
if connection: |
| 184 |
self._connection_explicit = True |
| 185 |
|
| 186 |
def add_query(self, query): |
| 187 |
if not isinstance(query, BaseCQLStatement): |
| 188 |
raise CQLEngineException('only BaseCQLStatements can be added to a batch query') |
| 189 |
self.queries.append(query) |
| 190 |
|
| 191 |
def consistency(self, consistency): |
| 192 |
self._consistency = consistency |
| 193 |
|
| 194 |
def _execute_callbacks(self): |
| 195 |
for callback, args, kwargs in self._callbacks: |
| 196 |
callback(*args, **kwargs) |
| 197 |
|
| 198 |
def add_callback(self, fn, *args, **kwargs): |
| 199 |
"""Add a function and arguments to be passed to it to be executed after the batch executes. |
| 200 |
|
| 201 |
A batch can support multiple callbacks. |
| 202 |
|
| 203 |
Note, that if the batch does not execute, the callbacks are not executed. |
| 204 |
A callback, thus, is an "on batch success" handler. |
| 205 |
|
| 206 |
:param fn: Callable object |
| 207 |
:type fn: callable |
| 208 |
:param args: Positional arguments to be passed to the callback at the time of execution |
| 209 |
:param kwargs: Named arguments to be passed to the callback at the time of execution |
| 210 |
""" |
| 211 |
if not callable(fn): |
| 212 |
raise ValueError("Value for argument 'fn' is {0} and is not a callable object.".format(type(fn))) |
| 213 |
self._callbacks.append((fn, args, kwargs)) |
| 214 |
|
| 215 |
def execute(self): |
| 216 |
if self._executed and self.warn_multiple_exec: |
| 217 |
msg = "Batch executed multiple times." |
| 218 |
if self._context_entered: |
| 219 |
msg += " If using the batch as a context manager, there is no need to call execute directly." |
| 220 |
warn(msg) |
| 221 |
self._executed = True |
| 222 |
|
| 223 |
if len(self.queries) == 0: |
| 224 |
# Empty batch is a no-op |
| 225 |
# except for callbacks |
| 226 |
self._execute_callbacks() |
| 227 |
return |
| 228 |
|
| 229 |
batch_type = None if self.batch_type is CBatchType.LOGGED else self.batch_type |
| 230 |
opener = 'BEGIN ' + (str(batch_type) + ' ' if batch_type else '') + ' BATCH' |
| 231 |
if self.timestamp: |
| 232 |
|
| 233 |
if isinstance(self.timestamp, int): |
| 234 |
ts = self.timestamp |
| 235 |
elif isinstance(self.timestamp, (datetime, timedelta)): |
| 236 |
ts = self.timestamp |
| 237 |
if isinstance(self.timestamp, timedelta): |
| 238 |
ts += datetime.now() # Apply timedelta |
| 239 |
ts = int(time.mktime(ts.timetuple()) * 1e+6 + ts.microsecond) |
| 240 |
else: |
| 241 |
raise ValueError("Batch expects a long, a timedelta, or a datetime") |
| 242 |
|
| 243 |
opener += ' USING TIMESTAMP {0}'.format(ts) |
| 244 |
|
| 245 |
query_list = [opener] |
| 246 |
parameters = {} |
| 247 |
ctx_counter = 0 |
| 248 |
for query in self.queries: |
| 249 |
query.update_context_id(ctx_counter) |
| 250 |
ctx = query.get_context() |
| 251 |
ctx_counter += len(ctx) |
| 252 |
query_list.append(' ' + str(query)) |
| 253 |
parameters.update(ctx) |
| 254 |
|
| 255 |
query_list.append('APPLY BATCH;') |
| 256 |
|
| 257 |
tmp = conn.execute('\n'.join(query_list), parameters, self._consistency, self._timeout, connection=self._connection) |
| 258 |
check_applied(tmp) |
| 259 |
|
| 260 |
self.queries = [] |
| 261 |
self._execute_callbacks() |
| 262 |
|
| 263 |
def __enter__(self): |
| 264 |
self._context_entered = True |
| 265 |
return self |
| 266 |
|
| 267 |
def __exit__(self, exc_type, exc_val, exc_tb): |
| 268 |
# don't execute if there was an exception by default |
| 269 |
if exc_type is not None and not self._execute_on_exception: |
| 270 |
return |
| 271 |
self.execute() |
| 272 |
|
| 273 |
|
| 274 |
class ContextQuery(object): |
| 275 |
""" |
| 276 |
A Context manager to allow a Model to switch context easily. Presently, the context only |
| 277 |
specifies a keyspace for model IO. |
| 278 |
|
| 279 |
:param args: One or more models. A model should be a class type, not an instance. |
| 280 |
:param kwargs: (optional) Context parameters: can be *keyspace* or *connection* |
| 281 |
|
| 282 |
For example: |
| 283 |
|
| 284 |
.. code-block:: python |
| 285 |
|
| 286 |
with ContextQuery(Automobile, keyspace='test2') as A: |
| 287 |
A.objects.create(manufacturer='honda', year=2008, model='civic') |
| 288 |
print(len(A.objects.all())) # 1 result |
| 289 |
|
| 290 |
with ContextQuery(Automobile, keyspace='test4') as A: |
| 291 |
print(len(A.objects.all())) # 0 result |
| 292 |
|
| 293 |
# Multiple models |
| 294 |
with ContextQuery(Automobile, Automobile2, connection='cluster2') as (A, A2): |
| 295 |
print(len(A.objects.all())) |
| 296 |
print(len(A2.objects.all())) |
| 297 |
|
| 298 |
""" |
| 299 |
|
| 300 |
def __init__(self, *args, **kwargs): |
| 301 |
from cassandra.cqlengine import models |
| 302 |
|
| 303 |
self.models = [] |
| 304 |
|
| 305 |
if len(args) < 1: |
| 306 |
raise ValueError("No model provided.") |
| 307 |
|
| 308 |
keyspace = kwargs.pop('keyspace', None) |
| 309 |
connection = kwargs.pop('connection', None) |
| 310 |
|
| 311 |
if kwargs: |
| 312 |
raise ValueError("Unknown keyword argument(s): {0}".format( |
| 313 |
','.join(kwargs.keys()))) |
| 314 |
|
| 315 |
for model in args: |
| 316 |
try: |
| 317 |
issubclass(model, models.Model) |
| 318 |
except TypeError: |
| 319 |
raise ValueError("Models must be derived from base Model.") |
| 320 |
|
| 321 |
m = models._clone_model_class(model, {}) |
| 322 |
|
| 323 |
if keyspace: |
| 324 |
m.__keyspace__ = keyspace |
| 325 |
if connection: |
| 326 |
m.__connection__ = connection |
| 327 |
|
| 328 |
self.models.append(m) |
| 329 |
|
| 330 |
def __enter__(self): |
| 331 |
if len(self.models) > 1: |
| 332 |
return tuple(self.models) |
| 333 |
return self.models[0] |
| 334 |
|
| 335 |
def __exit__(self, exc_type, exc_val, exc_tb): |
| 336 |
return |
| 337 |
|
| 338 |
|
| 339 |
class AbstractQuerySet(object): |
| 340 |
|
| 341 |
def __init__(self, model): |
| 342 |
super(AbstractQuerySet, self).__init__() |
| 343 |
self.model = model |
| 344 |
|
| 345 |
# Where clause filters |
| 346 |
self._where = [] |
| 347 |
|
| 348 |
# Conditional clause filters |
| 349 |
self._conditional = [] |
| 350 |
|
| 351 |
# ordering arguments |
| 352 |
self._order = [] |
| 353 |
|
| 354 |
self._allow_filtering = False |
| 355 |
|
| 356 |
# CQL has a default limit of 10000, it's defined here |
| 357 |
# because explicit is better than implicit |
| 358 |
self._limit = 10000 |
| 359 |
|
| 360 |
# We store the fields for which we use the Equal operator |
| 361 |
# in a query, so we don't select it from the DB. _defer_fields |
| 362 |
# will contain the names of the fields in the DB, not the names |
| 363 |
# of the variables used by the mapper |
| 364 |
self._defer_fields = set() |
| 365 |
self._deferred_values = {} |
| 366 |
|
| 367 |
# This variable will hold the names in the database of the fields |
| 368 |
# for which we want to query |
| 369 |
self._only_fields = [] |
| 370 |
|
| 371 |
self._values_list = False |
| 372 |
self._flat_values_list = False |
| 373 |
|
| 374 |
# results cache |
| 375 |
self._result_cache = None |
| 376 |
self._result_idx = None |
| 377 |
self._result_generator = None |
| 378 |
self._materialize_results = True |
| 379 |
|
| 380 |
self._distinct_fields = None |
| 381 |
|
| 382 |
self._count = None |
| 383 |
|
| 384 |
self._batch = None |
| 385 |
self._ttl = None |
| 386 |
self._consistency = None |
| 387 |
self._timestamp = None |
| 388 |
self._if_not_exists = False |
| 389 |
self._timeout = conn.NOT_SET |
| 390 |
self._if_exists = False |
| 391 |
self._fetch_size = None |
| 392 |
self._connection = None |
| 393 |
|
| 394 |
@property |
| 395 |
def column_family_name(self): |
| 396 |
return self.model.column_family_name() |
| 397 |
|
| 398 |
def _execute(self, statement): |
| 399 |
if self._batch: |
| 400 |
return self._batch.add_query(statement) |
| 401 |
else: |
| 402 |
connection = self._connection or self.model._get_connection() |
| 403 |
result = _execute_statement(self.model, statement, self._consistency, self._timeout, connection=connection) |
| 404 |
if self._if_not_exists or self._if_exists or self._conditional: |
| 405 |
check_applied(result) |
| 406 |
return result |
| 407 |
|
| 408 |
def __unicode__(self): |
| 409 |
return str(self._select_query()) |
| 410 |
|
| 411 |
def __str__(self): |
| 412 |
return str(self.__unicode__()) |
| 413 |
|
| 414 |
def __call__(self, *args, **kwargs): |
| 415 |
return self.filter(*args, **kwargs) |
| 416 |
|
| 417 |
def __deepcopy__(self, memo): |
| 418 |
clone = self.__class__(self.model) |
| 419 |
for k, v in self.__dict__.items(): |
| 420 |
if k in ['_con', '_cur', '_result_cache', '_result_idx', '_result_generator', '_construct_result']: # don't clone these, which are per-request-execution |
| 421 |
clone.__dict__[k] = None |
| 422 |
elif k == '_batch': |
| 423 |
# we need to keep the same batch instance across |
| 424 |
# all queryset clones, otherwise the batched queries |
| 425 |
# fly off into other batch instances which are never |
| 426 |
# executed, thx @dokai |
| 427 |
clone.__dict__[k] = self._batch |
| 428 |
elif k == '_timeout': |
| 429 |
clone.__dict__[k] = self._timeout |
| 430 |
else: |
| 431 |
clone.__dict__[k] = copy.deepcopy(v, memo) |
| 432 |
|
| 433 |
return clone |
| 434 |
|
| 435 |
def __len__(self): |
| 436 |
self._execute_query() |
| 437 |
return self.count() |
| 438 |
|
| 439 |
# ----query generation / execution---- |
| 440 |
|
| 441 |
def _select_fields(self): |
| 442 |
""" returns the fields to select """ |
| 443 |
return [] |
| 444 |
|
| 445 |
def _validate_select_where(self): |
| 446 |
""" put select query validation here """ |
| 447 |
|
| 448 |
def _select_query(self): |
| 449 |
""" |
| 450 |
Returns a select clause based on the given filter args |
| 451 |
""" |
| 452 |
if self._where: |
| 453 |
self._validate_select_where() |
| 454 |
return SelectStatement( |
| 455 |
self.column_family_name, |
| 456 |
fields=self._select_fields(), |
| 457 |
where=self._where, |
| 458 |
order_by=self._order, |
| 459 |
limit=self._limit, |
| 460 |
allow_filtering=self._allow_filtering, |
| 461 |
distinct_fields=self._distinct_fields, |
| 462 |
fetch_size=self._fetch_size |
| 463 |
) |
| 464 |
|
| 465 |
# ----Reads------ |
| 466 |
|
| 467 |
def _execute_query(self): |
| 468 |
if self._batch: |
| 469 |
raise CQLEngineException("Only inserts, updates, and deletes are available in batch mode") |
| 470 |
if self._result_cache is None: |
| 471 |
self._result_generator = (i for i in self._execute(self._select_query())) |
| 472 |
self._result_cache = [] |
| 473 |
self._construct_result = self._maybe_inject_deferred(self._get_result_constructor()) |
| 474 |
|
| 475 |
# "DISTINCT COUNT()" is not supported in C* < 2.2, so we need to materialize all results to get |
| 476 |
# len() and count() working with DISTINCT queries |
| 477 |
if self._materialize_results or self._distinct_fields: |
| 478 |
self._fill_result_cache() |
| 479 |
|
| 480 |
def _fill_result_cache(self): |
| 481 |
""" |
| 482 |
Fill the result cache with all results. |
| 483 |
""" |
| 484 |
|
| 485 |
idx = 0 |
| 486 |
try: |
| 487 |
while True: |
| 488 |
idx += 1000 |
| 489 |
self._fill_result_cache_to_idx(idx) |
| 490 |
except StopIteration: |
| 491 |
pass |
| 492 |
|
| 493 |
self._count = len(self._result_cache) |
| 494 |
|
| 495 |
def _fill_result_cache_to_idx(self, idx): |
| 496 |
self._execute_query() |
| 497 |
if self._result_idx is None: |
| 498 |
self._result_idx = -1 |
| 499 |
|
| 500 |
qty = idx - self._result_idx |
| 501 |
if qty < 1: |
| 502 |
return |
| 503 |
else: |
| 504 |
for idx in range(qty): |
| 505 |
self._result_idx += 1 |
| 506 |
while True: |
| 507 |
try: |
| 508 |
self._result_cache[self._result_idx] = self._construct_result(self._result_cache[self._result_idx]) |
| 509 |
break |
| 510 |
except IndexError: |
| 511 |
self._result_cache.append(next(self._result_generator)) |
| 512 |
|
| 513 |
def __iter__(self): |
| 514 |
self._execute_query() |
| 515 |
|
| 516 |
idx = 0 |
| 517 |
while True: |
| 518 |
if len(self._result_cache) <= idx: |
| 519 |
try: |
| 520 |
self._result_cache.append(next(self._result_generator)) |
| 521 |
except StopIteration: |
| 522 |
break |
| 523 |
|
| 524 |
instance = self._result_cache[idx] |
| 525 |
if isinstance(instance, dict): |
| 526 |
self._fill_result_cache_to_idx(idx) |
| 527 |
yield self._result_cache[idx] |
| 528 |
|
| 529 |
idx += 1 |
| 530 |
|
| 531 |
def __getitem__(self, s): |
| 532 |
self._execute_query() |
| 533 |
|
| 534 |
if isinstance(s, slice): |
| 535 |
start = s.start if s.start else 0 |
| 536 |
|
| 537 |
if start < 0 or (s.stop is not None and s.stop < 0): |
| 538 |
warn("ModelQuerySet slicing with negative indices support will be removed in 4.0.", |
| 539 |
DeprecationWarning) |
| 540 |
|
| 541 |
# calculate the amount of results that need to be loaded |
| 542 |
end = s.stop |
| 543 |
if start < 0 or s.stop is None or s.stop < 0: |
| 544 |
end = self.count() |
| 545 |
|
| 546 |
try: |
| 547 |
self._fill_result_cache_to_idx(end) |
| 548 |
except StopIteration: |
| 549 |
pass |
| 550 |
|
| 551 |
return self._result_cache[start:s.stop:s.step] |
| 552 |
else: |
| 553 |
try: |
| 554 |
s = int(s) |
| 555 |
except (ValueError, TypeError): |
| 556 |
raise TypeError('QuerySet indices must be integers') |
| 557 |
|
| 558 |
if s < 0: |
| 559 |
warn("ModelQuerySet indexing with negative indices support will be removed in 4.0.", |
| 560 |
DeprecationWarning) |
| 561 |
|
| 562 |
# Using negative indexing is costly since we have to execute a count() |
| 563 |
if s < 0: |
| 564 |
num_results = self.count() |
| 565 |
s += num_results |
| 566 |
|
| 567 |
try: |
| 568 |
self._fill_result_cache_to_idx(s) |
| 569 |
except StopIteration: |
| 570 |
raise IndexError |
| 571 |
|
| 572 |
return self._result_cache[s] |
| 573 |
|
| 574 |
def _get_result_constructor(self): |
| 575 |
""" |
| 576 |
Returns a function that will be used to instantiate query results |
| 577 |
""" |
| 578 |
raise NotImplementedError |
| 579 |
|
| 580 |
@staticmethod |
| 581 |
def _construct_with_deferred(f, deferred, row): |
| 582 |
row.update(deferred) |
| 583 |
return f(row) |
| 584 |
|
| 585 |
def _maybe_inject_deferred(self, constructor): |
| 586 |
return partial(self._construct_with_deferred, constructor, self._deferred_values)\ |
| 587 |
if self._deferred_values else constructor |
| 588 |
|
| 589 |
def batch(self, batch_obj): |
| 590 |
""" |
| 591 |
Set a batch object to run the query on. |
| 592 |
|
| 593 |
Note: running a select query with a batch object will raise an exception |
| 594 |
""" |
| 595 |
if self._connection: |
| 596 |
raise CQLEngineException("Cannot specify the connection on model in batch mode.") |
| 597 |
|
| 598 |
if batch_obj is not None and not isinstance(batch_obj, BatchQuery): |
| 599 |
raise CQLEngineException('batch_obj must be a BatchQuery instance or None') |
| 600 |
clone = copy.deepcopy(self) |
| 601 |
clone._batch = batch_obj |
| 602 |
return clone |
| 603 |
|
| 604 |
def first(self): |
| 605 |
try: |
| 606 |
return next(iter(self)) |
| 607 |
except StopIteration: |
| 608 |
return None |
| 609 |
|
| 610 |
def all(self): |
| 611 |
""" |
| 612 |
Returns a queryset matching all rows |
| 613 |
|
| 614 |
.. code-block:: python |
| 615 |
|
| 616 |
for user in User.objects().all(): |
| 617 |
print(user) |
| 618 |
""" |
| 619 |
return copy.deepcopy(self) |
| 620 |
|
| 621 |
def consistency(self, consistency): |
| 622 |
""" |
| 623 |
Sets the consistency level for the operation. See :class:`.ConsistencyLevel`. |
| 624 |
|
| 625 |
.. code-block:: python |
| 626 |
|
| 627 |
for user in User.objects(id=3).consistency(CL.ONE): |
| 628 |
print(user) |
| 629 |
""" |
| 630 |
clone = copy.deepcopy(self) |
| 631 |
clone._consistency = consistency |
| 632 |
return clone |
| 633 |
|
| 634 |
def _parse_filter_arg(self, arg): |
| 635 |
""" |
| 636 |
Parses a filter arg in the format: |
| 637 |
<colname>__<op> |
| 638 |
:returns: colname, op tuple |
| 639 |
""" |
| 640 |
statement = arg.rsplit('__', 1) |
| 641 |
if len(statement) == 1: |
| 642 |
return arg, None |
| 643 |
elif len(statement) == 2: |
| 644 |
return (statement[0], statement[1]) if arg != 'pk__token' else (arg, None) |
| 645 |
else: |
| 646 |
raise QueryException("Can't parse '{0}'".format(arg)) |
| 647 |
|
| 648 |
def iff(self, *args, **kwargs): |
| 649 |
"""Adds IF statements to queryset""" |
| 650 |
if len([x for x in kwargs.values() if x is None]): |
| 651 |
raise CQLEngineException("None values on iff are not allowed") |
| 652 |
|
| 653 |
clone = copy.deepcopy(self) |
| 654 |
for operator in args: |
| 655 |
if not isinstance(operator, ConditionalClause): |
| 656 |
raise QueryException('{0} is not a valid query operator'.format(operator)) |
| 657 |
clone._conditional.append(operator) |
| 658 |
|
| 659 |
for arg, val in kwargs.items(): |
| 660 |
if isinstance(val, Token): |
| 661 |
raise QueryException("Token() values are not valid in conditionals") |
| 662 |
|
| 663 |
col_name, col_op = self._parse_filter_arg(arg) |
| 664 |
try: |
| 665 |
column = self.model._get_column(col_name) |
| 666 |
except KeyError: |
| 667 |
raise QueryException("Can't resolve column name: '{0}'".format(col_name)) |
| 668 |
|
| 669 |
if isinstance(val, BaseQueryFunction): |
| 670 |
query_val = val |
| 671 |
else: |
| 672 |
query_val = column.to_database(val) |
| 673 |
|
| 674 |
operator_class = BaseWhereOperator.get_operator(col_op or 'EQ') |
| 675 |
operator = operator_class() |
| 676 |
clone._conditional.append(WhereClause(column.db_field_name, operator, query_val)) |
| 677 |
|
| 678 |
return clone |
| 679 |
|
| 680 |
def filter(self, *args, **kwargs): |
| 681 |
""" |
| 682 |
Adds WHERE arguments to the queryset, returning a new queryset |
| 683 |
|
| 684 |
See :ref:`retrieving-objects-with-filters` |
| 685 |
|
| 686 |
Returns a QuerySet filtered on the keyword arguments |
| 687 |
""" |
| 688 |
# add arguments to the where clause filters |
| 689 |
if len([x for x in kwargs.values() if x is None]): |
| 690 |
raise CQLEngineException("None values on filter are not allowed") |
| 691 |
|
| 692 |
clone = copy.deepcopy(self) |
| 693 |
for operator in args: |
| 694 |
if not isinstance(operator, WhereClause): |
| 695 |
raise QueryException('{0} is not a valid query operator'.format(operator)) |
| 696 |
clone._where.append(operator) |
| 697 |
|
| 698 |
for arg, val in kwargs.items(): |
| 699 |
col_name, col_op = self._parse_filter_arg(arg) |
| 700 |
quote_field = True |
| 701 |
|
| 702 |
if not isinstance(val, Token): |
| 703 |
try: |
| 704 |
column = self.model._get_column(col_name) |
| 705 |
except KeyError: |
| 706 |
raise QueryException("Can't resolve column name: '{0}'".format(col_name)) |
| 707 |
else: |
| 708 |
if col_name != 'pk__token': |
| 709 |
raise QueryException("Token() values may only be compared to the 'pk__token' virtual column") |
| 710 |
|
| 711 |
column = columns._PartitionKeysToken(self.model) |
| 712 |
quote_field = False |
| 713 |
|
| 714 |
partition_columns = column.partition_columns |
| 715 |
if len(partition_columns) != len(val.value): |
| 716 |
raise QueryException( |
| 717 |
'Token() received {0} arguments but model has {1} partition keys'.format( |
| 718 |
len(val.value), len(partition_columns))) |
| 719 |
val.set_columns(partition_columns) |
| 720 |
|
| 721 |
# get query operator, or use equals if not supplied |
| 722 |
operator_class = BaseWhereOperator.get_operator(col_op or 'EQ') |
| 723 |
operator = operator_class() |
| 724 |
|
| 725 |
if isinstance(operator, InOperator): |
| 726 |
if not isinstance(val, (list, tuple)): |
| 727 |
raise QueryException('IN queries must use a list/tuple value') |
| 728 |
query_val = [column.to_database(v) for v in val] |
| 729 |
elif isinstance(val, BaseQueryFunction): |
| 730 |
query_val = val |
| 731 |
elif (isinstance(operator, ContainsOperator) and |
| 732 |
isinstance(column, (columns.List, columns.Set, columns.Map))): |
| 733 |
# For ContainsOperator and collections, we query using the value, not the container |
| 734 |
query_val = val |
| 735 |
else: |
| 736 |
query_val = column.to_database(val) |
| 737 |
if not col_op: # only equal values should be deferred |
| 738 |
clone._defer_fields.add(column.db_field_name) |
| 739 |
clone._deferred_values[column.db_field_name] = val # map by db field name for substitution in results |
| 740 |
|
| 741 |
clone._where.append(WhereClause(column.db_field_name, operator, query_val, quote_field=quote_field)) |
| 742 |
|
| 743 |
return clone |
| 744 |
|
| 745 |
def get(self, *args, **kwargs): |
| 746 |
""" |
| 747 |
Returns a single instance matching this query, optionally with additional filter kwargs. |
| 748 |
|
| 749 |
See :ref:`retrieving-objects-with-filters` |
| 750 |
|
| 751 |
Returns a single object matching the QuerySet. |
| 752 |
|
| 753 |
.. code-block:: python |
| 754 |
|
| 755 |
user = User.get(id=1) |
| 756 |
|
| 757 |
If no objects are matched, a :class:`~.DoesNotExist` exception is raised. |
| 758 |
|
| 759 |
If more than one object is found, a :class:`~.MultipleObjectsReturned` exception is raised. |
| 760 |
""" |
| 761 |
if args or kwargs: |
| 762 |
return self.filter(*args, **kwargs).get() |
| 763 |
|
| 764 |
self._execute_query() |
| 765 |
|
| 766 |
# Check that the resultset only contains one element, avoiding sending a COUNT query |
| 767 |
try: |
| 768 |
self[1] |
| 769 |
raise self.model.MultipleObjectsReturned('Multiple objects found') |
| 770 |
except IndexError: |
| 771 |
pass |
| 772 |
|
| 773 |
try: |
| 774 |
obj = self[0] |
| 775 |
except IndexError: |
| 776 |
raise self.model.DoesNotExist |
| 777 |
|
| 778 |
return obj |
| 779 |
|
| 780 |
def _get_ordering_condition(self, colname): |
| 781 |
order_type = 'DESC' if colname.startswith('-') else 'ASC' |
| 782 |
colname = colname.replace('-', '') |
| 783 |
|
| 784 |
return colname, order_type |
| 785 |
|
| 786 |
def order_by(self, *colnames): |
| 787 |
""" |
| 788 |
Sets the column(s) to be used for ordering |
| 789 |
|
| 790 |
Default order is ascending, prepend a '-' to any column name for descending |
| 791 |
|
| 792 |
*Note: column names must be a clustering key* |
| 793 |
|
| 794 |
.. code-block:: python |
| 795 |
|
| 796 |
from uuid import uuid1,uuid4 |
| 797 |
|
| 798 |
class Comment(Model): |
| 799 |
photo_id = UUID(primary_key=True) |
| 800 |
comment_id = TimeUUID(primary_key=True, default=uuid1) # second primary key component is a clustering key |
| 801 |
comment = Text() |
| 802 |
|
| 803 |
sync_table(Comment) |
| 804 |
|
| 805 |
u = uuid4() |
| 806 |
for x in range(5): |
| 807 |
Comment.create(photo_id=u, comment="test %d" % x) |
| 808 |
|
| 809 |
print("Normal") |
| 810 |
for comment in Comment.objects(photo_id=u): |
| 811 |
print(comment.comment_id) |
| 812 |
|
| 813 |
print("Reversed") |
| 814 |
for comment in Comment.objects(photo_id=u).order_by("-comment_id"): |
| 815 |
print(comment.comment_id) |
| 816 |
""" |
| 817 |
if len(colnames) == 0: |
| 818 |
clone = copy.deepcopy(self) |
| 819 |
clone._order = [] |
| 820 |
return clone |
| 821 |
|
| 822 |
conditions = [] |
| 823 |
for colname in colnames: |
| 824 |
conditions.append('"{0}" {1}'.format(*self._get_ordering_condition(colname))) |
| 825 |
|
| 826 |
clone = copy.deepcopy(self) |
| 827 |
clone._order.extend(conditions) |
| 828 |
return clone |
| 829 |
|
| 830 |
def count(self): |
| 831 |
""" |
| 832 |
Returns the number of rows matched by this query. |
| 833 |
|
| 834 |
*Note: This function executes a SELECT COUNT() and has a performance cost on large datasets* |
| 835 |
""" |
| 836 |
if self._batch: |
| 837 |
raise CQLEngineException("Only inserts, updates, and deletes are available in batch mode") |
| 838 |
|
| 839 |
if self._count is None: |
| 840 |
query = self._select_query() |
| 841 |
query.count = True |
| 842 |
result = self._execute(query) |
| 843 |
count_row = result.one().popitem() |
| 844 |
self._count = count_row[1] |
| 845 |
return self._count |
| 846 |
|
| 847 |
def distinct(self, distinct_fields=None): |
| 848 |
""" |
| 849 |
Returns the DISTINCT rows matched by this query. |
| 850 |
|
| 851 |
distinct_fields default to the partition key fields if not specified. |
| 852 |
|
| 853 |
*Note: distinct_fields must be a partition key or a static column* |
| 854 |
|
| 855 |
.. code-block:: python |
| 856 |
|
| 857 |
class Automobile(Model): |
| 858 |
manufacturer = columns.Text(partition_key=True) |
| 859 |
year = columns.Integer(primary_key=True) |
| 860 |
model = columns.Text(primary_key=True) |
| 861 |
price = columns.Decimal() |
| 862 |
|
| 863 |
sync_table(Automobile) |
| 864 |
|
| 865 |
# create rows |
| 866 |
|
| 867 |
Automobile.objects.distinct() |
| 868 |
|
| 869 |
# or |
| 870 |
|
| 871 |
Automobile.objects.distinct(['manufacturer']) |
| 872 |
|
| 873 |
""" |
| 874 |
|
| 875 |
clone = copy.deepcopy(self) |
| 876 |
if distinct_fields: |
| 877 |
clone._distinct_fields = distinct_fields |
| 878 |
else: |
| 879 |
clone._distinct_fields = [x.column_name for x in self.model._partition_keys.values()] |
| 880 |
|
| 881 |
return clone |
| 882 |
|
| 883 |
def limit(self, v): |
| 884 |
""" |
| 885 |
Limits the number of results returned by Cassandra. Use *0* or *None* to disable. |
| 886 |
|
| 887 |
*Note that CQL's default limit is 10,000, so all queries without a limit set explicitly will have an implicit limit of 10,000* |
| 888 |
|
| 889 |
.. code-block:: python |
| 890 |
|
| 891 |
# Fetch 100 users |
| 892 |
for user in User.objects().limit(100): |
| 893 |
print(user) |
| 894 |
|
| 895 |
# Fetch all users |
| 896 |
for user in User.objects().limit(None): |
| 897 |
print(user) |
| 898 |
""" |
| 899 |
|
| 900 |
if v is None: |
| 901 |
v = 0 |
| 902 |
|
| 903 |
if not isinstance(v, int): |
| 904 |
raise TypeError |
| 905 |
if v == self._limit: |
| 906 |
return self |
| 907 |
|
| 908 |
if v < 0: |
| 909 |
raise QueryException("Negative limit is not allowed") |
| 910 |
|
| 911 |
clone = copy.deepcopy(self) |
| 912 |
clone._limit = v |
| 913 |
return clone |
| 914 |
|
| 915 |
def fetch_size(self, v): |
| 916 |
""" |
| 917 |
Sets the number of rows that are fetched at a time. |
| 918 |
|
| 919 |
*Note that driver's default fetch size is 5000.* |
| 920 |
|
| 921 |
.. code-block:: python |
| 922 |
|
| 923 |
for user in User.objects().fetch_size(500): |
| 924 |
print(user) |
| 925 |
""" |
| 926 |
|
| 927 |
if not isinstance(v, int): |
| 928 |
raise TypeError |
| 929 |
if v == self._fetch_size: |
| 930 |
return self |
| 931 |
|
| 932 |
if v < 1: |
| 933 |
raise QueryException("fetch size less than 1 is not allowed") |
| 934 |
|
| 935 |
clone = copy.deepcopy(self) |
| 936 |
clone._fetch_size = v |
| 937 |
return clone |
| 938 |
|
| 939 |
def allow_filtering(self): |
| 940 |
""" |
| 941 |
Enables the (usually) unwise practive of querying on a clustering key without also defining a partition key |
| 942 |
""" |
| 943 |
clone = copy.deepcopy(self) |
| 944 |
clone._allow_filtering = True |
| 945 |
return clone |
| 946 |
|
| 947 |
def _only_or_defer(self, action, fields): |
| 948 |
if action == 'only' and self._only_fields: |
| 949 |
raise QueryException("QuerySet already has 'only' fields defined") |
| 950 |
|
| 951 |
clone = copy.deepcopy(self) |
| 952 |
|
| 953 |
# check for strange fields |
| 954 |
missing_fields = [f for f in fields if f not in self.model._columns.keys()] |
| 955 |
if missing_fields: |
| 956 |
raise QueryException( |
| 957 |
"Can't resolve fields {0} in {1}".format( |
| 958 |
', '.join(missing_fields), self.model.__name__)) |
| 959 |
|
| 960 |
fields = [self.model._columns[field].db_field_name for field in fields] |
| 961 |
|
| 962 |
if action == 'defer': |
| 963 |
clone._defer_fields.update(fields) |
| 964 |
elif action == 'only': |
| 965 |
clone._only_fields = fields |
| 966 |
else: |
| 967 |
raise ValueError |
| 968 |
|
| 969 |
return clone |
| 970 |
|
| 971 |
def only(self, fields): |
| 972 |
""" Load only these fields for the returned query """ |
| 973 |
return self._only_or_defer('only', fields) |
| 974 |
|
| 975 |
def defer(self, fields): |
| 976 |
""" Don't load these fields for the returned query """ |
| 977 |
return self._only_or_defer('defer', fields) |
| 978 |
|
| 979 |
def create(self, **kwargs): |
| 980 |
return self.model(**kwargs) \ |
| 981 |
.batch(self._batch) \ |
| 982 |
.ttl(self._ttl) \ |
| 983 |
.consistency(self._consistency) \ |
| 984 |
.if_not_exists(self._if_not_exists) \ |
| 985 |
.timestamp(self._timestamp) \ |
| 986 |
.if_exists(self._if_exists) \ |
| 987 |
.using(connection=self._connection) \ |
| 988 |
.save() |
| 989 |
|
| 990 |
def delete(self): |
| 991 |
""" |
| 992 |
Deletes the contents of a query |
| 993 |
""" |
| 994 |
# validate where clause |
| 995 |
partition_keys = set(x.db_field_name for x in self.model._partition_keys.values()) |
| 996 |
if partition_keys - set(c.field for c in self._where): |
| 997 |
raise QueryException("The partition key must be defined on delete queries") |
| 998 |
|
| 999 |
dq = DeleteStatement( |
| 1000 |
self.column_family_name, |
| 1001 |
where=self._where, |
| 1002 |
timestamp=self._timestamp, |
| 1003 |
conditionals=self._conditional, |
| 1004 |
if_exists=self._if_exists |
| 1005 |
) |
| 1006 |
self._execute(dq) |
| 1007 |
|
| 1008 |
def __eq__(self, q): |
| 1009 |
if len(self._where) == len(q._where): |
| 1010 |
return all([w in q._where for w in self._where]) |
| 1011 |
return False |
| 1012 |
|
| 1013 |
def __ne__(self, q): |
| 1014 |
return not (self != q) |
| 1015 |
|
| 1016 |
def timeout(self, timeout): |
| 1017 |
""" |
| 1018 |
:param timeout: Timeout for the query (in seconds) |
| 1019 |
:type timeout: float or None |
| 1020 |
""" |
| 1021 |
clone = copy.deepcopy(self) |
| 1022 |
clone._timeout = timeout |
| 1023 |
return clone |
| 1024 |
|
| 1025 |
def using(self, keyspace=None, connection=None): |
| 1026 |
""" |
| 1027 |
Change the context on-the-fly of the Model class (keyspace, connection) |
| 1028 |
""" |
| 1029 |
|
| 1030 |
if connection and self._batch: |
| 1031 |
raise CQLEngineException("Cannot specify a connection on model in batch mode.") |
| 1032 |
|
| 1033 |
clone = copy.deepcopy(self) |
| 1034 |
if keyspace: |
| 1035 |
from cassandra.cqlengine.models import _clone_model_class |
| 1036 |
clone.model = _clone_model_class(self.model, {'__keyspace__': keyspace}) |
| 1037 |
|
| 1038 |
if connection: |
| 1039 |
clone._connection = connection |
| 1040 |
|
| 1041 |
return clone |
| 1042 |
|
| 1043 |
|
| 1044 |
class ResultObject(dict): |
| 1045 |
""" |
| 1046 |
adds attribute access to a dictionary |
| 1047 |
""" |
| 1048 |
|
| 1049 |
def __getattr__(self, item): |
| 1050 |
try: |
| 1051 |
return self[item] |
| 1052 |
except KeyError: |
| 1053 |
raise AttributeError |
| 1054 |
|
| 1055 |
|
| 1056 |
class SimpleQuerySet(AbstractQuerySet): |
| 1057 |
""" |
| 1058 |
Overrides _get_result_constructor for querysets that do not define a model (e.g. NamedTable queries) |
| 1059 |
""" |
| 1060 |
|
| 1061 |
def _get_result_constructor(self): |
| 1062 |
""" |
| 1063 |
Returns a function that will be used to instantiate query results |
| 1064 |
""" |
| 1065 |
return ResultObject |
| 1066 |
|
| 1067 |
|
| 1068 |
class ModelQuerySet(AbstractQuerySet): |
| 1069 |
""" |
| 1070 |
""" |
| 1071 |
def _validate_select_where(self): |
| 1072 |
""" Checks that a filterset will not create invalid select statement """ |
| 1073 |
# check that there's either a =, a IN or a CONTAINS (collection) |
| 1074 |
# relationship with a primary key or indexed field. We also allow |
| 1075 |
# custom indexes to be queried with any operator (a difference |
| 1076 |
# between a secondary index) |
| 1077 |
equal_ops = [self.model._get_column_by_db_name(w.field) \ |
| 1078 |
for w in self._where if not isinstance(w.value, Token) |
| 1079 |
and (isinstance(w.operator, EqualsOperator) |
| 1080 |
or self.model._get_column_by_db_name(w.field).custom_index)] |
| 1081 |
token_comparison = any([w for w in self._where if isinstance(w.value, Token)]) |
| 1082 |
if not any(w.primary_key or w.has_index for w in equal_ops) and not token_comparison and not self._allow_filtering: |
| 1083 |
raise QueryException( |
| 1084 |
('Where clauses require either =, a IN or a CONTAINS ' |
| 1085 |
'(collection) comparison with either a primary key or ' |
| 1086 |
'indexed field. You might want to consider setting ' |
| 1087 |
'custom_index on fields that you manage index outside ' |
| 1088 |
'cqlengine.')) |
| 1089 |
|
| 1090 |
if not self._allow_filtering: |
| 1091 |
# if the query is not on an indexed field |
| 1092 |
if not any(w.has_index for w in equal_ops): |
| 1093 |
if not any([w.partition_key for w in equal_ops]) and not token_comparison: |
| 1094 |
raise QueryException( |
| 1095 |
('Filtering on a clustering key without a partition ' |
| 1096 |
'key is not allowed unless allow_filtering() is ' |
| 1097 |
'called on the queryset. You might want to consider ' |
| 1098 |
'setting custom_index on fields that you manage ' |
| 1099 |
'index outside cqlengine.')) |
| 1100 |
|
| 1101 |
def _select_fields(self): |
| 1102 |
if self._defer_fields or self._only_fields: |
| 1103 |
fields = [columns.db_field_name for columns in self.model._columns.values()] |
| 1104 |
if self._defer_fields: |
| 1105 |
fields = [f for f in fields if f not in self._defer_fields] |
| 1106 |
# select the partition keys if all model fields are set defer |
| 1107 |
if not fields: |
| 1108 |
fields = [columns.db_field_name for columns in self.model._partition_keys.values()] |
| 1109 |
if self._only_fields: |
| 1110 |
fields = [f for f in fields if f in self._only_fields] |
| 1111 |
if not fields: |
| 1112 |
raise QueryException('No fields in select query. Only fields: "{0}", defer fields: "{1}"'.format( |
| 1113 |
','.join(self._only_fields), ','.join(self._defer_fields))) |
| 1114 |
return fields |
| 1115 |
return super(ModelQuerySet, self)._select_fields() |
| 1116 |
|
| 1117 |
def _get_result_constructor(self): |
| 1118 |
""" Returns a function that will be used to instantiate query results """ |
| 1119 |
if not self._values_list: # we want models |
| 1120 |
return self.model._construct_instance |
| 1121 |
elif self._flat_values_list: # the user has requested flattened list (1 value per row) |
| 1122 |
key = self._only_fields[0] |
| 1123 |
return lambda row: row[key] |
| 1124 |
else: |
| 1125 |
return lambda row: [row[f] for f in self._only_fields] |
| 1126 |
|
| 1127 |
def _get_ordering_condition(self, colname): |
| 1128 |
colname, order_type = super(ModelQuerySet, self)._get_ordering_condition(colname) |
| 1129 |
|
| 1130 |
column = self.model._columns.get(colname) |
| 1131 |
if column is None: |
| 1132 |
raise QueryException("Can't resolve the column name: '{0}'".format(colname)) |
| 1133 |
|
| 1134 |
# validate the column selection |
| 1135 |
if not column.primary_key: |
| 1136 |
raise QueryException( |
| 1137 |
"Can't order on '{0}', can only order on (clustered) primary keys".format(colname)) |
| 1138 |
|
| 1139 |
pks = [v for k, v in self.model._columns.items() if v.primary_key] |
| 1140 |
if column == pks[0]: |
| 1141 |
raise QueryException( |
| 1142 |
"Can't order by the first primary key (partition key), clustering (secondary) keys only") |
| 1143 |
|
| 1144 |
return column.db_field_name, order_type |
| 1145 |
|
| 1146 |
def values_list(self, *fields, **kwargs): |
| 1147 |
""" Instructs the query set to return tuples, not model instance """ |
| 1148 |
flat = kwargs.pop('flat', False) |
| 1149 |
if kwargs: |
| 1150 |
raise TypeError('Unexpected keyword arguments to values_list: %s' |
| 1151 |
% (kwargs.keys(),)) |
| 1152 |
if flat and len(fields) > 1: |
| 1153 |
raise TypeError("'flat' is not valid when values_list is called with more than one field.") |
| 1154 |
clone = self.only(fields) |
| 1155 |
clone._values_list = True |
| 1156 |
clone._flat_values_list = flat |
| 1157 |
return clone |
| 1158 |
|
| 1159 |
def ttl(self, ttl): |
| 1160 |
""" |
| 1161 |
Sets the ttl (in seconds) for modified data. |
| 1162 |
|
| 1163 |
*Note that running a select query with a ttl value will raise an exception* |
| 1164 |
""" |
| 1165 |
clone = copy.deepcopy(self) |
| 1166 |
clone._ttl = ttl |
| 1167 |
return clone |
| 1168 |
|
| 1169 |
def timestamp(self, timestamp): |
| 1170 |
""" |
| 1171 |
Allows for custom timestamps to be saved with the record. |
| 1172 |
""" |
| 1173 |
clone = copy.deepcopy(self) |
| 1174 |
clone._timestamp = timestamp |
| 1175 |
return clone |
| 1176 |
|
| 1177 |
def if_not_exists(self): |
| 1178 |
""" |
| 1179 |
Check the existence of an object before insertion. |
| 1180 |
|
| 1181 |
If the insertion isn't applied, a LWTException is raised. |
| 1182 |
""" |
| 1183 |
if self.model._has_counter: |
| 1184 |
raise IfNotExistsWithCounterColumn('if_not_exists cannot be used with tables containing counter columns') |
| 1185 |
clone = copy.deepcopy(self) |
| 1186 |
clone._if_not_exists = True |
| 1187 |
return clone |
| 1188 |
|
| 1189 |
def if_exists(self): |
| 1190 |
""" |
| 1191 |
Check the existence of an object before an update or delete. |
| 1192 |
|
| 1193 |
If the update or delete isn't applied, a LWTException is raised. |
| 1194 |
""" |
| 1195 |
if self.model._has_counter: |
| 1196 |
raise IfExistsWithCounterColumn('if_exists cannot be used with tables containing counter columns') |
| 1197 |
clone = copy.deepcopy(self) |
| 1198 |
clone._if_exists = True |
| 1199 |
return clone |
| 1200 |
|
| 1201 |
def update(self, **values): |
| 1202 |
""" |
| 1203 |
Performs an update on the row selected by the queryset. Include values to update in the |
| 1204 |
update like so: |
| 1205 |
|
| 1206 |
.. code-block:: python |
| 1207 |
|
| 1208 |
Model.objects(key=n).update(value='x') |
| 1209 |
|
| 1210 |
Passing in updates for columns which are not part of the model will raise a ValidationError. |
| 1211 |
|
| 1212 |
Per column validation will be performed, but instance level validation will not |
| 1213 |
(i.e., `Model.validate` is not called). This is sometimes referred to as a blind update. |
| 1214 |
|
| 1215 |
For example: |
| 1216 |
|
| 1217 |
.. code-block:: python |
| 1218 |
|
| 1219 |
class User(Model): |
| 1220 |
id = Integer(primary_key=True) |
| 1221 |
name = Text() |
| 1222 |
|
| 1223 |
setup(["localhost"], "test") |
| 1224 |
sync_table(User) |
| 1225 |
|
| 1226 |
u = User.create(id=1, name="jon") |
| 1227 |
|
| 1228 |
User.objects(id=1).update(name="Steve") |
| 1229 |
|
| 1230 |
# sets name to null |
| 1231 |
User.objects(id=1).update(name=None) |
| 1232 |
|
| 1233 |
|
| 1234 |
Also supported is blindly adding and removing elements from container columns, |
| 1235 |
without loading a model instance from Cassandra. |
| 1236 |
|
| 1237 |
Using the syntax `.update(column_name={x, y, z})` will overwrite the contents of the container, like updating a |
| 1238 |
non container column. However, adding `__<operation>` to the end of the keyword arg, makes the update call add |
| 1239 |
or remove items from the collection, without overwriting then entire column. |
| 1240 |
|
| 1241 |
Given the model below, here are the operations that can be performed on the different container columns: |
| 1242 |
|
| 1243 |
.. code-block:: python |
| 1244 |
|
| 1245 |
class Row(Model): |
| 1246 |
row_id = columns.Integer(primary_key=True) |
| 1247 |
set_column = columns.Set(Integer) |
| 1248 |
list_column = columns.List(Integer) |
| 1249 |
map_column = columns.Map(Integer, Integer) |
| 1250 |
|
| 1251 |
:class:`~cqlengine.columns.Set` |
| 1252 |
|
| 1253 |
- `add`: adds the elements of the given set to the column |
| 1254 |
- `remove`: removes the elements of the given set to the column |
| 1255 |
|
| 1256 |
|
| 1257 |
.. code-block:: python |
| 1258 |
|
| 1259 |
# add elements to a set |
| 1260 |
Row.objects(row_id=5).update(set_column__add={6}) |
| 1261 |
|
| 1262 |
# remove elements to a set |
| 1263 |
Row.objects(row_id=5).update(set_column__remove={4}) |
| 1264 |
|
| 1265 |
:class:`~cqlengine.columns.List` |
| 1266 |
|
| 1267 |
- `append`: appends the elements of the given list to the end of the column |
| 1268 |
- `prepend`: prepends the elements of the given list to the beginning of the column |
| 1269 |
|
| 1270 |
.. code-block:: python |
| 1271 |
|
| 1272 |
# append items to a list |
| 1273 |
Row.objects(row_id=5).update(list_column__append=[6, 7]) |
| 1274 |
|
| 1275 |
# prepend items to a list |
| 1276 |
Row.objects(row_id=5).update(list_column__prepend=[1, 2]) |
| 1277 |
|
| 1278 |
|
| 1279 |
:class:`~cqlengine.columns.Map` |
| 1280 |
|
| 1281 |
- `update`: adds the given keys/values to the columns, creating new entries if they didn't exist, and overwriting old ones if they did |
| 1282 |
|
| 1283 |
.. code-block:: python |
| 1284 |
|
| 1285 |
# add items to a map |
| 1286 |
Row.objects(row_id=5).update(map_column__update={1: 2, 3: 4}) |
| 1287 |
|
| 1288 |
# remove items from a map |
| 1289 |
Row.objects(row_id=5).update(map_column__remove={1, 2}) |
| 1290 |
""" |
| 1291 |
if not values: |
| 1292 |
return |
| 1293 |
|
| 1294 |
nulled_columns = set() |
| 1295 |
updated_columns = set() |
| 1296 |
us = UpdateStatement(self.column_family_name, where=self._where, ttl=self._ttl, |
| 1297 |
timestamp=self._timestamp, conditionals=self._conditional, if_exists=self._if_exists) |
| 1298 |
for name, val in values.items(): |
| 1299 |
col_name, col_op = self._parse_filter_arg(name) |
| 1300 |
col = self.model._columns.get(col_name) |
| 1301 |
# check for nonexistant columns |
| 1302 |
if col is None: |
| 1303 |
raise ValidationError("{0}.{1} has no column named: {2}".format(self.__module__, self.model.__name__, col_name)) |
| 1304 |
# check for primary key update attempts |
| 1305 |
if col.is_primary_key: |
| 1306 |
raise ValidationError("Cannot apply update to primary key '{0}' for {1}.{2}".format(col_name, self.__module__, self.model.__name__)) |
| 1307 |
|
| 1308 |
if col_op == 'remove' and isinstance(col, columns.Map): |
| 1309 |
if not isinstance(val, set): |
| 1310 |
raise ValidationError( |
| 1311 |
"Cannot apply update operation '{0}' on column '{1}' with value '{2}'. A set is required.".format(col_op, col_name, val)) |
| 1312 |
val = {v: None for v in val} |
| 1313 |
else: |
| 1314 |
# we should not provide default values in this use case. |
| 1315 |
val = col.validate(val) |
| 1316 |
|
| 1317 |
if val is None: |
| 1318 |
nulled_columns.add(col_name) |
| 1319 |
continue |
| 1320 |
|
| 1321 |
us.add_update(col, val, operation=col_op) |
| 1322 |
updated_columns.add(col_name) |
| 1323 |
|
| 1324 |
if us.assignments: |
| 1325 |
self._execute(us) |
| 1326 |
|
| 1327 |
if nulled_columns: |
| 1328 |
delete_conditional = [condition for condition in self._conditional |
| 1329 |
if condition.field not in updated_columns] if self._conditional else None |
| 1330 |
ds = DeleteStatement(self.column_family_name, fields=nulled_columns, |
| 1331 |
where=self._where, conditionals=delete_conditional, if_exists=self._if_exists) |
| 1332 |
self._execute(ds) |
| 1333 |
|
| 1334 |
|
| 1335 |
class DMLQuery(object): |
| 1336 |
""" |
| 1337 |
A query object used for queries performing inserts, updates, or deletes |
| 1338 |
|
| 1339 |
this is usually instantiated by the model instance to be modified |
| 1340 |
|
| 1341 |
unlike the read query object, this is mutable |
| 1342 |
""" |
| 1343 |
_ttl = None |
| 1344 |
_consistency = None |
| 1345 |
_timestamp = None |
| 1346 |
_if_not_exists = False |
| 1347 |
_if_exists = False |
| 1348 |
|
| 1349 |
def __init__(self, model, instance=None, batch=None, ttl=None, consistency=None, timestamp=None, |
| 1350 |
if_not_exists=False, conditional=None, timeout=conn.NOT_SET, if_exists=False): |
| 1351 |
self.model = model |
| 1352 |
self.column_family_name = self.model.column_family_name() |
| 1353 |
self.instance = instance |
| 1354 |
self._batch = batch |
| 1355 |
self._ttl = ttl |
| 1356 |
self._consistency = consistency |
| 1357 |
self._timestamp = timestamp |
| 1358 |
self._if_not_exists = if_not_exists |
| 1359 |
self._if_exists = if_exists |
| 1360 |
self._conditional = conditional |
| 1361 |
self._timeout = timeout |
| 1362 |
|
| 1363 |
def _execute(self, statement): |
| 1364 |
connection = self.instance._get_connection() if self.instance else self.model._get_connection() |
| 1365 |
if self._batch: |
| 1366 |
if self._batch._connection: |
| 1367 |
if not self._batch._connection_explicit and connection and \ |
| 1368 |
connection != self._batch._connection: |
| 1369 |
raise CQLEngineException('BatchQuery queries must be executed on the same connection') |
| 1370 |
else: |
| 1371 |
# set the BatchQuery connection from the model |
| 1372 |
self._batch._connection = connection |
| 1373 |
return self._batch.add_query(statement) |
| 1374 |
else: |
| 1375 |
results = _execute_statement(self.model, statement, self._consistency, self._timeout, connection=connection) |
| 1376 |
if self._if_not_exists or self._if_exists or self._conditional: |
| 1377 |
check_applied(results) |
| 1378 |
return results |
| 1379 |
|
| 1380 |
def batch(self, batch_obj): |
| 1381 |
if batch_obj is not None and not isinstance(batch_obj, BatchQuery): |
| 1382 |
raise CQLEngineException('batch_obj must be a BatchQuery instance or None') |
| 1383 |
self._batch = batch_obj |
| 1384 |
return self |
| 1385 |
|
| 1386 |
def _delete_null_columns(self, conditionals=None): |
| 1387 |
""" |
| 1388 |
executes a delete query to remove columns that have changed to null |
| 1389 |
""" |
| 1390 |
ds = DeleteStatement(self.column_family_name, conditionals=conditionals, if_exists=self._if_exists) |
| 1391 |
deleted_fields = False |
| 1392 |
static_only = True |
| 1393 |
for _, v in self.instance._values.items(): |
| 1394 |
col = v.column |
| 1395 |
if v.deleted: |
| 1396 |
ds.add_field(col.db_field_name) |
| 1397 |
deleted_fields = True |
| 1398 |
static_only &= col.static |
| 1399 |
elif isinstance(col, columns.Map): |
| 1400 |
uc = MapDeleteClause(col.db_field_name, v.value, v.previous_value) |
| 1401 |
if uc.get_context_size() > 0: |
| 1402 |
ds.add_field(uc) |
| 1403 |
deleted_fields = True |
| 1404 |
static_only |= col.static |
| 1405 |
|
| 1406 |
if deleted_fields: |
| 1407 |
keys = self.model._partition_keys if static_only else self.model._primary_keys |
| 1408 |
for name, col in keys.items(): |
| 1409 |
ds.add_where(col, EqualsOperator(), getattr(self.instance, name)) |
| 1410 |
self._execute(ds) |
| 1411 |
|
| 1412 |
def update(self): |
| 1413 |
""" |
| 1414 |
updates a row. |
| 1415 |
This is a blind update call. |
| 1416 |
All validation and cleaning needs to happen |
| 1417 |
prior to calling this. |
| 1418 |
""" |
| 1419 |
if self.instance is None: |
| 1420 |
raise CQLEngineException("DML Query intance attribute is None") |
| 1421 |
assert type(self.instance) == self.model |
| 1422 |
null_clustering_key = False if len(self.instance._clustering_keys) == 0 else True |
| 1423 |
static_changed_only = True |
| 1424 |
statement = UpdateStatement(self.column_family_name, ttl=self._ttl, timestamp=self._timestamp, |
| 1425 |
conditionals=self._conditional, if_exists=self._if_exists) |
| 1426 |
for name, col in self.instance._clustering_keys.items(): |
| 1427 |
null_clustering_key = null_clustering_key and col._val_is_null(getattr(self.instance, name, None)) |
| 1428 |
|
| 1429 |
updated_columns = set() |
| 1430 |
# get defined fields and their column names |
| 1431 |
for name, col in self.model._columns.items(): |
| 1432 |
# if clustering key is null, don't include non static columns |
| 1433 |
if null_clustering_key and not col.static and not col.partition_key: |
| 1434 |
continue |
| 1435 |
if not col.is_primary_key: |
| 1436 |
val = getattr(self.instance, name, None) |
| 1437 |
val_mgr = self.instance._values[name] |
| 1438 |
|
| 1439 |
if val is None: |
| 1440 |
continue |
| 1441 |
|
| 1442 |
if not val_mgr.changed and not isinstance(col, columns.Counter): |
| 1443 |
continue |
| 1444 |
|
| 1445 |
static_changed_only = static_changed_only and col.static |
| 1446 |
statement.add_update(col, val, previous=val_mgr.previous_value) |
| 1447 |
updated_columns.add(col.db_field_name) |
| 1448 |
|
| 1449 |
if statement.assignments: |
| 1450 |
for name, col in self.model._primary_keys.items(): |
| 1451 |
# only include clustering key if clustering key is not null, and non static columns are changed to avoid cql error |
| 1452 |
if (null_clustering_key or static_changed_only) and (not col.partition_key): |
| 1453 |
continue |
| 1454 |
statement.add_where(col, EqualsOperator(), getattr(self.instance, name)) |
| 1455 |
self._execute(statement) |
| 1456 |
|
| 1457 |
if not null_clustering_key: |
| 1458 |
# remove conditions on fields that have been updated |
| 1459 |
delete_conditionals = [condition for condition in self._conditional |
| 1460 |
if condition.field not in updated_columns] if self._conditional else None |
| 1461 |
self._delete_null_columns(delete_conditionals) |
| 1462 |
|
| 1463 |
def save(self): |
| 1464 |
""" |
| 1465 |
Creates / updates a row. |
| 1466 |
This is a blind insert call. |
| 1467 |
All validation and cleaning needs to happen |
| 1468 |
prior to calling this. |
| 1469 |
""" |
| 1470 |
if self.instance is None: |
| 1471 |
raise CQLEngineException("DML Query intance attribute is None") |
| 1472 |
assert type(self.instance) == self.model |
| 1473 |
|
| 1474 |
nulled_fields = set() |
| 1475 |
if self.instance._has_counter or self.instance._can_update(): |
| 1476 |
if self.instance._has_counter: |
| 1477 |
warn("'create' and 'save' actions on Counters are deprecated. It will be disallowed in 4.0. " |
| 1478 |
"Use the 'update' mechanism instead.", DeprecationWarning) |
| 1479 |
return self.update() |
| 1480 |
else: |
| 1481 |
insert = InsertStatement(self.column_family_name, ttl=self._ttl, timestamp=self._timestamp, if_not_exists=self._if_not_exists) |
| 1482 |
static_save_only = False if len(self.instance._clustering_keys) == 0 else True |
| 1483 |
for name, col in self.instance._clustering_keys.items(): |
| 1484 |
static_save_only = static_save_only and col._val_is_null(getattr(self.instance, name, None)) |
| 1485 |
for name, col in self.instance._columns.items(): |
| 1486 |
if static_save_only and not col.static and not col.partition_key: |
| 1487 |
continue |
| 1488 |
val = getattr(self.instance, name, None) |
| 1489 |
if col._val_is_null(val): |
| 1490 |
if self.instance._values[name].changed: |
| 1491 |
nulled_fields.add(col.db_field_name) |
| 1492 |
continue |
| 1493 |
if col.has_default and not self.instance._values[name].changed: |
| 1494 |
# Ensure default columns included in a save() are marked as explicit, to get them *persisted* properly |
| 1495 |
self.instance._values[name].explicit = True |
| 1496 |
insert.add_assignment(col, getattr(self.instance, name, None)) |
| 1497 |
|
| 1498 |
# skip query execution if it's empty |
| 1499 |
# caused by pointless update queries |
| 1500 |
if not insert.is_empty: |
| 1501 |
self._execute(insert) |
| 1502 |
# delete any nulled columns |
| 1503 |
if not static_save_only: |
| 1504 |
self._delete_null_columns() |
| 1505 |
|
| 1506 |
def delete(self): |
| 1507 |
""" Deletes one instance """ |
| 1508 |
if self.instance is None: |
| 1509 |
raise CQLEngineException("DML Query instance attribute is None") |
| 1510 |
|
| 1511 |
ds = DeleteStatement(self.column_family_name, timestamp=self._timestamp, conditionals=self._conditional, if_exists=self._if_exists) |
| 1512 |
for name, col in self.model._primary_keys.items(): |
| 1513 |
val = getattr(self.instance, name) |
| 1514 |
if val is None and not col.partition_key: |
| 1515 |
continue |
| 1516 |
ds.add_where(col, EqualsOperator(), val) |
| 1517 |
self._execute(ds) |
| 1518 |
|
| 1519 |
|
| 1520 |
def _execute_statement(model, statement, consistency_level, timeout, connection=None): |
| 1521 |
params = statement.get_context() |
| 1522 |
s = SimpleStatement(str(statement), consistency_level=consistency_level, fetch_size=statement.fetch_size) |
| 1523 |
if model._partition_key_index: |
| 1524 |
key_values = statement.partition_key_values(model._partition_key_index) |
| 1525 |
if not any(v is None for v in key_values): |
| 1526 |
parts = model._routing_key_from_values(key_values, conn.get_cluster(connection).protocol_version) |
| 1527 |
s.routing_key = parts |
| 1528 |
s.keyspace = model._get_keyspace() |
| 1529 |
connection = connection or model._get_connection() |
| 1530 |
return conn.execute(s, params, timeout=timeout, connection=connection) |