Debian Codegraph @

cassandra/cqlengine/models.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 import logging
16 import re
17 from warnings import warn
18
19 from cassandra.cqlengine import CQLEngineException, ValidationError
20 from cassandra.cqlengine import columns
21 from cassandra.cqlengine import connection
22 from cassandra.cqlengine import query
23 from cassandra.cqlengine.query import DoesNotExist as _DoesNotExist
24 from cassandra.cqlengine.query import MultipleObjectsReturned as _MultipleObjectsReturned
25 from cassandra.metadata import protect_name
26 from cassandra.util import OrderedDict
27
28 log = logging.getLogger(__name__)
29
30
31 def _clone_model_class(model, attrs):
32 new_type = type(model.__name__, (model,), attrs)
33 try:
34 new_type.__abstract__ = model.__abstract__
35 new_type.__discriminator_value__ = model.__discriminator_value__
36 new_type.__default_ttl__ = model.__default_ttl__
37 except AttributeError:
38 pass
39 return new_type
40
41
42 class ModelException(CQLEngineException):
43 pass
44
45
46 class ModelDefinitionException(ModelException):
47 pass
48
49
50 class PolymorphicModelException(ModelException):
51 pass
52
53
54 class UndefinedKeyspaceWarning(Warning):
55 pass
56
57 DEFAULT_KEYSPACE = None
58
59
60 class hybrid_classmethod(object):
61 """
62 Allows a method to behave as both a class method and
63 normal instance method depending on how it's called
64 """
65 def __init__(self, clsmethod, instmethod):
66 self.clsmethod = clsmethod
67 self.instmethod = instmethod
68
69 def __get__(self, instance, owner):
70 if instance is None:
71 return self.clsmethod.__get__(owner, owner)
72 else:
73 return self.instmethod.__get__(instance, owner)
74
75 def __call__(self, *args, **kwargs):
76 """
77 Just a hint to IDEs that it's ok to call this
78 """
79 raise NotImplementedError
80
81
82 class QuerySetDescriptor(object):
83 """
84 returns a fresh queryset for the given model
85 it's declared on everytime it's accessed
86 """
87
88 def __get__(self, obj, model):
89 """ :rtype: ModelQuerySet """
90 if model.__abstract__:
91 raise CQLEngineException('cannot execute queries against abstract models')
92 queryset = model.__queryset__(model)
93
94 # if this is a concrete polymorphic model, and the discriminator
95 # key is an indexed column, add a filter clause to only return
96 # logical rows of the proper type
97 if model._is_polymorphic and not model._is_polymorphic_base:
98 name, column = model._discriminator_column_name, model._discriminator_column
99 if column.partition_key or column.index:
100 # look for existing poly types
101 return queryset.filter(**{name: model.__discriminator_value__})
102
103 return queryset
104
105 def __call__(self, *args, **kwargs):
106 """
107 Just a hint to IDEs that it's ok to call this
108
109 :rtype: ModelQuerySet
110 """
111 raise NotImplementedError
112
113
114 class ConditionalDescriptor(object):
115 """
116 returns a query set descriptor
117 """
118 def __get__(self, instance, model):
119 if instance:
120 def conditional_setter(*prepared_conditional, **unprepared_conditionals):
121 if len(prepared_conditional) > 0:
122 conditionals = prepared_conditional[0]
123 else:
124 conditionals = instance.objects.iff(**unprepared_conditionals)._conditional
125 instance._conditional = conditionals
126 return instance
127
128 return conditional_setter
129 qs = model.__queryset__(model)
130
131 def conditional_setter(**unprepared_conditionals):
132 conditionals = model.objects.iff(**unprepared_conditionals)._conditional
133 qs._conditional = conditionals
134 return qs
135 return conditional_setter
136
137 def __call__(self, *args, **kwargs):
138 raise NotImplementedError
139
140
141 class TTLDescriptor(object):
142 """
143 returns a query set descriptor
144 """
145 def __get__(self, instance, model):
146 if instance:
147 # instance = copy.deepcopy(instance)
148 # instance method
149 def ttl_setter(ts):
150 instance._ttl = ts
151 return instance
152 return ttl_setter
153
154 qs = model.__queryset__(model)
155
156 def ttl_setter(ts):
157 qs._ttl = ts
158 return qs
159
160 return ttl_setter
161
162 def __call__(self, *args, **kwargs):
163 raise NotImplementedError
164
165
166 class TimestampDescriptor(object):
167 """
168 returns a query set descriptor with a timestamp specified
169 """
170 def __get__(self, instance, model):
171 if instance:
172 # instance method
173 def timestamp_setter(ts):
174 instance._timestamp = ts
175 return instance
176 return timestamp_setter
177
178 return model.objects.timestamp
179
180 def __call__(self, *args, **kwargs):
181 raise NotImplementedError
182
183
184 class IfNotExistsDescriptor(object):
185 """
186 return a query set descriptor with a if_not_exists flag specified
187 """
188 def __get__(self, instance, model):
189 if instance:
190 # instance method
191 def ifnotexists_setter(ife=True):
192 instance._if_not_exists = ife
193 return instance
194 return ifnotexists_setter
195
196 return model.objects.if_not_exists
197
198 def __call__(self, *args, **kwargs):
199 raise NotImplementedError
200
201
202 class IfExistsDescriptor(object):
203 """
204 return a query set descriptor with a if_exists flag specified
205 """
206 def __get__(self, instance, model):
207 if instance:
208 # instance method
209 def ifexists_setter(ife=True):
210 instance._if_exists = ife
211 return instance
212 return ifexists_setter
213
214 return model.objects.if_exists
215
216 def __call__(self, *args, **kwargs):
217 raise NotImplementedError
218
219
220 class ConsistencyDescriptor(object):
221 """
222 returns a query set descriptor if called on Class, instance if it was an instance call
223 """
224 def __get__(self, instance, model):
225 if instance:
226 # instance = copy.deepcopy(instance)
227 def consistency_setter(consistency):
228 instance.__consistency__ = consistency
229 return instance
230 return consistency_setter
231
232 qs = model.__queryset__(model)
233
234 def consistency_setter(consistency):
235 qs._consistency = consistency
236 return qs
237
238 return consistency_setter
239
240 def __call__(self, *args, **kwargs):
241 raise NotImplementedError
242
243
244 class UsingDescriptor(object):
245 """
246 return a query set descriptor with a connection context specified
247 """
248 def __get__(self, instance, model):
249 if instance:
250 # instance method
251 def using_setter(connection=None):
252 if connection:
253 instance._connection = connection
254 return instance
255 return using_setter
256
257 return model.objects.using
258
259 def __call__(self, *args, **kwargs):
260 raise NotImplementedError
261
262
263 class ColumnQueryEvaluator(query.AbstractQueryableColumn):
264 """
265 Wraps a column and allows it to be used in comparator
266 expressions, returning query operators
267
268 ie:
269 Model.column == 5
270 """
271
272 def __init__(self, column):
273 self.column = column
274
275 def __unicode__(self):
276 return self.column.db_field_name
277
278 def _get_column(self):
279 return self.column
280
281
282 class ColumnDescriptor(object):
283 """
284 Handles the reading and writing of column values to and from
285 a model instance's value manager, as well as creating
286 comparator queries
287 """
288
289 def __init__(self, column):
290 """
291 :param column:
292 :type column: columns.Column
293 :return:
294 """
295 self.column = column
296 self.query_evaluator = ColumnQueryEvaluator(self.column)
297
298 def __get__(self, instance, owner):
299 """
300 Returns either the value or column, depending
301 on if an instance is provided or not
302
303 :param instance: the model instance
304 :type instance: Model
305 """
306 try:
307 return instance._values[self.column.column_name].getval()
308 except AttributeError:
309 return self.query_evaluator
310
311 def __set__(self, instance, value):
312 """
313 Sets the value on an instance, raises an exception with classes
314 TODO: use None instance to create update statements
315 """
316 if instance:
317 return instance._values[self.column.column_name].setval(value)
318 else:
319 raise AttributeError('cannot reassign column values')
320
321 def __delete__(self, instance):
322 """
323 Sets the column value to None, if possible
324 """
325 if instance:
326 if self.column.can_delete:
327 instance._values[self.column.column_name].delval()
328 else:
329 raise AttributeError('cannot delete {0} columns'.format(self.column.column_name))
330
331
332 class BaseModel(object):
333 """
334 The base model class, don't inherit from this, inherit from Model, defined below
335 """
336
337 class DoesNotExist(_DoesNotExist):
338 pass
339
340 class MultipleObjectsReturned(_MultipleObjectsReturned):
341 pass
342
343 objects = QuerySetDescriptor()
344 ttl = TTLDescriptor()
345 consistency = ConsistencyDescriptor()
346 iff = ConditionalDescriptor()
347
348 # custom timestamps, see USING TIMESTAMP X
349 timestamp = TimestampDescriptor()
350
351 if_not_exists = IfNotExistsDescriptor()
352
353 if_exists = IfExistsDescriptor()
354
355 using = UsingDescriptor()
356
357 # _len is lazily created by __len__
358
359 __table_name__ = None
360
361 __table_name_case_sensitive__ = False
362
363 __keyspace__ = None
364
365 __connection__ = None
366
367 __discriminator_value__ = None
368
369 __options__ = None
370
371 __compute_routing_key__ = True
372
373 # the queryset class used for this class
374 __queryset__ = query.ModelQuerySet
375 __dmlquery__ = query.DMLQuery
376
377 __consistency__ = None # can be set per query
378
379 _timestamp = None # optional timestamp to include with the operation (USING TIMESTAMP)
380
381 _if_not_exists = False # optional if_not_exists flag to check existence before insertion
382
383 _if_exists = False # optional if_exists flag to check existence before update
384
385 _table_name = None # used internally to cache a derived table name
386
387 _connection = None
388
389 def __init__(self, **values):
390 self._ttl = None
391 self._timestamp = None
392 self._conditional = None
393 self._batch = None
394 self._timeout = connection.NOT_SET
395 self._is_persisted = False
396 self._connection = None
397
398 self._values = {}
399 for name, column in self._columns.items():
400 # Set default values on instantiation. Thanks to this, we don't have
401 # to wait anylonger for a call to validate() to have CQLengine set
402 # default columns values.
403 column_default = column.get_default() if column.has_default else None
404 value = values.get(name, column_default)
405 if value is not None or isinstance(column, columns.BaseContainerColumn):
406 value = column.to_python(value)
407 value_mngr = column.value_manager(self, column, value)
408 value_mngr.explicit = name in values
409 self._values[name] = value_mngr
410
411 def __repr__(self):
412 return '{0}({1})'.format(self.__class__.__name__,
413 ', '.join('{0}={1!r}'.format(k, getattr(self, k))
414 for k in self._defined_columns.keys()
415 if k != self._discriminator_column_name))
416
417 def __str__(self):
418 """
419 Pretty printing of models by their primary key
420 """
421 return '{0} <{1}>'.format(self.__class__.__name__,
422 ', '.join('{0}={1}'.format(k, getattr(self, k)) for k in self._primary_keys.keys()))
423
424 @classmethod
425 def _routing_key_from_values(cls, pk_values, protocol_version):
426 return cls._key_serializer(pk_values, protocol_version)
427
428 @classmethod
429 def _discover_polymorphic_submodels(cls):
430 if not cls._is_polymorphic_base:
431 raise ModelException('_discover_polymorphic_submodels can only be called on polymorphic base classes')
432
433 def _discover(klass):
434 if not klass._is_polymorphic_base and klass.__discriminator_value__ is not None:
435 cls._discriminator_map[klass.__discriminator_value__] = klass
436 for subklass in klass.__subclasses__():
437 _discover(subklass)
438 _discover(cls)
439
440 @classmethod
441 def _get_model_by_discriminator_value(cls, key):
442 if not cls._is_polymorphic_base:
443 raise ModelException('_get_model_by_discriminator_value can only be called on polymorphic base classes')
444 return cls._discriminator_map.get(key)
445
446 @classmethod
447 def _construct_instance(cls, values):
448 """
449 method used to construct instances from query results
450 this is where polymorphic deserialization occurs
451 """
452 # we're going to take the values, which is from the DB as a dict
453 # and translate that into our local fields
454 # the db_map is a db_field -> model field map
455 if cls._db_map:
456 values = dict((cls._db_map.get(k, k), v) for k, v in values.items())
457
458 if cls._is_polymorphic:
459 disc_key = values.get(cls._discriminator_column_name)
460
461 if disc_key is None:
462 raise PolymorphicModelException('discriminator value was not found in values')
463
464 poly_base = cls if cls._is_polymorphic_base else cls._polymorphic_base
465
466 klass = poly_base._get_model_by_discriminator_value(disc_key)
467 if klass is None:
468 poly_base._discover_polymorphic_submodels()
469 klass = poly_base._get_model_by_discriminator_value(disc_key)
470 if klass is None:
471 raise PolymorphicModelException(
472 'unrecognized discriminator column {0} for class {1}'.format(disc_key, poly_base.__name__)
473 )
474
475 if not issubclass(klass, cls):
476 raise PolymorphicModelException(
477 '{0} is not a subclass of {1}'.format(klass.__name__, cls.__name__)
478 )
479
480 values = dict((k, v) for k, v in values.items() if k in klass._columns.keys())
481
482 else:
483 klass = cls
484
485 instance = klass(**values)
486 instance._set_persisted(force=True)
487 return instance
488
489 def _set_persisted(self, force=False):
490 # ensure we don't modify to any values not affected by the last save/update
491 for v in [v for v in self._values.values() if v.changed or force]:
492 v.reset_previous_value()
493 v.explicit = False
494 self._is_persisted = True
495
496 def _can_update(self):
497 """
498 Called by the save function to check if this should be
499 persisted with update or insert
500
501 :return:
502 """
503 if not self._is_persisted:
504 return False
505
506 return all([not self._values[k].changed for k in self._primary_keys])
507
508 @classmethod
509 def _get_keyspace(cls):
510 """
511 Returns the manual keyspace, if set, otherwise the default keyspace
512 """
513 return cls.__keyspace__ or DEFAULT_KEYSPACE
514
515 @classmethod
516 def _get_column(cls, name):
517 """
518 Returns the column matching the given name, raising a key error if
519 it doesn't exist
520
521 :param name: the name of the column to return
522 :rtype: Column
523 """
524 return cls._columns[name]
525
526 @classmethod
527 def _get_column_by_db_name(cls, name):
528 """
529 Returns the column, mapped by db_field name
530 """
531 return cls._columns.get(cls._db_map.get(name, name))
532
533 def __eq__(self, other):
534 if self.__class__ != other.__class__:
535 return False
536
537 # check attribute keys
538 keys = set(self._columns.keys())
539 other_keys = set(other._columns.keys())
540 if keys != other_keys:
541 return False
542
543 return all(getattr(self, key, None) == getattr(other, key, None) for key in other_keys)
544
545 def __ne__(self, other):
546 return not self.__eq__(other)
547
548 @classmethod
549 def column_family_name(cls, include_keyspace=True):
550 """
551 Returns the column family name if it's been defined
552 otherwise, it creates it from the module and class name
553 """
554 cf_name = protect_name(cls._raw_column_family_name())
555 if include_keyspace:
556 keyspace = cls._get_keyspace()
557 if not keyspace:
558 raise CQLEngineException("Model keyspace is not set and no default is available. Set model keyspace or setup connection before attempting to generate a query.")
559 return '{0}.{1}'.format(protect_name(keyspace), cf_name)
560
561 return cf_name
562
563
564 @classmethod
565 def _raw_column_family_name(cls):
566 if not cls._table_name:
567 if cls.__table_name__:
568 if cls.__table_name_case_sensitive__:
569 warn("Model __table_name_case_sensitive__ will be removed in 4.0.", PendingDeprecationWarning)
570 cls._table_name = cls.__table_name__
571 else:
572 table_name = cls.__table_name__.lower()
573 if cls.__table_name__ != table_name:
574 warn(("Model __table_name__ will be case sensitive by default in 4.0. "
575 "You should fix the __table_name__ value of the '{0}' model.").format(cls.__name__))
576 cls._table_name = table_name
577 else:
578 if cls._is_polymorphic and not cls._is_polymorphic_base:
579 cls._table_name = cls._polymorphic_base._raw_column_family_name()
580 else:
581 camelcase = re.compile(r'([a-z])([A-Z])')
582 ccase = lambda s: camelcase.sub(lambda v: '{0}_{1}'.format(v.group(1), v.group(2).lower()), s)
583
584 cf_name = ccase(cls.__name__)
585 # trim to less than 48 characters or cassandra will complain
586 cf_name = cf_name[-48:]
587 cf_name = cf_name.lower()
588 cf_name = re.sub(r'^_+', '', cf_name)
589 cls._table_name = cf_name
590
591 return cls._table_name
592
593 def _set_column_value(self, name, value):
594 """Function to change a column value without changing the value manager states"""
595 self._values[name].value = value # internal assignement, skip the main setter
596
597 def validate(self):
598 """
599 Cleans and validates the field values
600 """
601 for name, col in self._columns.items():
602 v = getattr(self, name)
603 if v is None and not self._values[name].explicit and col.has_default:
604 v = col.get_default()
605 val = col.validate(v)
606 self._set_column_value(name, val)
607
608 # Let an instance be used like a dict of its columns keys/values
609 def __iter__(self):
610 """ Iterate over column ids. """
611 for column_id in self._columns.keys():
612 yield column_id
613
614 def __getitem__(self, key):
615 """ Returns column's value. """
616 if not isinstance(key, str):
617 raise TypeError
618 if key not in self._columns.keys():
619 raise KeyError
620 return getattr(self, key)
621
622 def __setitem__(self, key, val):
623 """ Sets a column's value. """
624 if not isinstance(key, str):
625 raise TypeError
626 if key not in self._columns.keys():
627 raise KeyError
628 return setattr(self, key, val)
629
630 def __len__(self):
631 """
632 Returns the number of columns defined on that model.
633 """
634 try:
635 return self._len
636 except:
637 self._len = len(self._columns.keys())
638 return self._len
639
640 def keys(self):
641 """ Returns a list of column IDs. """
642 return [k for k in self]
643
644 def values(self):
645 """ Returns list of column values. """
646 return [self[k] for k in self]
647
648 def items(self):
649 """ Returns a list of column ID/value tuples. """
650 return [(k, self[k]) for k in self]
651
652 def _as_dict(self):
653 """ Returns a map of column names to cleaned values """
654 values = self._dynamic_columns or {}
655 for name, col in self._columns.items():
656 values[name] = col.to_database(getattr(self, name, None))
657 return values
658
659 @classmethod
660 def create(cls, **kwargs):
661 """
662 Create an instance of this model in the database.
663
664 Takes the model column values as keyword arguments. Setting a value to
665 `None` is equivalent to running a CQL `DELETE` on that column.
666
667 Returns the instance.
668 """
669 extra_columns = set(kwargs.keys()) - set(cls._columns.keys())
670 if extra_columns:
671 raise ValidationError("Incorrect columns passed: {0}".format(extra_columns))
672 return cls.objects.create(**kwargs)
673
674 @classmethod
675 def all(cls):
676 """
677 Returns a queryset representing all stored objects
678
679 This is a pass-through to the model objects().all()
680 """
681 return cls.objects.all()
682
683 @classmethod
684 def filter(cls, *args, **kwargs):
685 """
686 Returns a queryset based on filter parameters.
687
688 This is a pass-through to the model objects().:method:`~cqlengine.queries.filter`.
689 """
690 return cls.objects.filter(*args, **kwargs)
691
692 @classmethod
693 def get(cls, *args, **kwargs):
694 """
695 Returns a single object based on the passed filter constraints.
696
697 This is a pass-through to the model objects().:method:`~cqlengine.queries.get`.
698 """
699 return cls.objects.get(*args, **kwargs)
700
701 def timeout(self, timeout):
702 """
703 Sets a timeout for use in :meth:`~.save`, :meth:`~.update`, and :meth:`~.delete`
704 operations
705 """
706 assert self._batch is None, 'Setting both timeout and batch is not supported'
707 self._timeout = timeout
708 return self
709
710 def save(self):
711 """
712 Saves an object to the database.
713
714 .. code-block:: python
715
716 #create a person instance
717 person = Person(first_name='Kimberly', last_name='Eggleston')
718 #saves it to Cassandra
719 person.save()
720 """
721
722 # handle polymorphic models
723 if self._is_polymorphic:
724 if self._is_polymorphic_base:
725 raise PolymorphicModelException('cannot save polymorphic base model')
726 else:
727 setattr(self, self._discriminator_column_name, self.__discriminator_value__)
728
729 self.validate()
730 self.__dmlquery__(self.__class__, self,
731 batch=self._batch,
732 ttl=self._ttl,
733 timestamp=self._timestamp,
734 consistency=self.__consistency__,
735 if_not_exists=self._if_not_exists,
736 conditional=self._conditional,
737 timeout=self._timeout,
738 if_exists=self._if_exists).save()
739
740 self._set_persisted()
741
742 self._timestamp = None
743
744 return self
745
746 def update(self, **values):
747 """
748 Performs an update on the model instance. You can pass in values to set on the model
749 for updating, or you can call without values to execute an update against any modified
750 fields. If no fields on the model have been modified since loading, no query will be
751 performed. Model validation is performed normally. Setting a value to `None` is
752 equivalent to running a CQL `DELETE` on that column.
753
754 It is possible to do a blind update, that is, to update a field without having first selected the object out of the database.
755 See :ref:`Blind Updates <blind_updates>`
756 """
757 for column_id, v in values.items():
758 col = self._columns.get(column_id)
759
760 # check for nonexistant columns
761 if col is None:
762 raise ValidationError(
763 "{0}.{1} has no column named: {2}".format(
764 self.__module__, self.__class__.__name__, column_id))
765
766 # check for primary key update attempts
767 if col.is_primary_key:
768 current_value = getattr(self, column_id)
769 if v != current_value:
770 raise ValidationError(
771 "Cannot apply update to primary key '{0}' for {1}.{2}".format(
772 column_id, self.__module__, self.__class__.__name__))
773
774 setattr(self, column_id, v)
775
776 # handle polymorphic models
777 if self._is_polymorphic:
778 if self._is_polymorphic_base:
779 raise PolymorphicModelException('cannot update polymorphic base model')
780 else:
781 setattr(self, self._discriminator_column_name, self.__discriminator_value__)
782
783 self.validate()
784 self.__dmlquery__(self.__class__, self,
785 batch=self._batch,
786 ttl=self._ttl,
787 timestamp=self._timestamp,
788 consistency=self.__consistency__,
789 conditional=self._conditional,
790 timeout=self._timeout,
791 if_exists=self._if_exists).update()
792
793 self._set_persisted()
794
795 self._timestamp = None
796
797 return self
798
799 def delete(self):
800 """
801 Deletes the object from the database
802 """
803 self.__dmlquery__(self.__class__, self,
804 batch=self._batch,
805 timestamp=self._timestamp,
806 consistency=self.__consistency__,
807 timeout=self._timeout,
808 conditional=self._conditional,
809 if_exists=self._if_exists).delete()
810
811 def get_changed_columns(self):
812 """
813 Returns a list of the columns that have been updated since instantiation or save
814 """
815 return [k for k, v in self._values.items() if v.changed]
816
817 @classmethod
818 def _class_batch(cls, batch):
819 return cls.objects.batch(batch)
820
821 def _inst_batch(self, batch):
822 assert self._timeout is connection.NOT_SET, 'Setting both timeout and batch is not supported'
823 if self._connection:
824 raise CQLEngineException("Cannot specify a connection on model in batch mode.")
825 self._batch = batch
826 return self
827
828 batch = hybrid_classmethod(_class_batch, _inst_batch)
829
830 @classmethod
831 def _class_get_connection(cls):
832 return cls.__connection__
833
834 def _inst_get_connection(self):
835 return self._connection or self.__connection__
836
837 _get_connection = hybrid_classmethod(_class_get_connection, _inst_get_connection)
838
839
840 class ModelMetaClass(type):
841
842 def __new__(cls, name, bases, attrs):
843 # move column definitions into columns dict
844 # and set default column names
845 column_dict = OrderedDict()
846 primary_keys = OrderedDict()
847 pk_name = None
848
849 # get inherited properties
850 inherited_columns = OrderedDict()
851 for base in bases:
852 for k, v in getattr(base, '_defined_columns', {}).items():
853 inherited_columns.setdefault(k, v)
854
855 # short circuit __abstract__ inheritance
856 is_abstract = attrs['__abstract__'] = attrs.get('__abstract__', False)
857
858 # short circuit __discriminator_value__ inheritance
859 attrs['__discriminator_value__'] = attrs.get('__discriminator_value__')
860
861 # TODO __default__ttl__ should be removed in the next major release
862 options = attrs.get('__options__') or {}
863 attrs['__default_ttl__'] = options.get('default_time_to_live')
864
865 column_definitions = [(k, v) for k, v in attrs.items() if isinstance(v, columns.Column)]
866 column_definitions = sorted(column_definitions, key=lambda x: x[1].position)
867
868 is_polymorphic_base = any([c[1].discriminator_column for c in column_definitions])
869
870 column_definitions = [x for x in inherited_columns.items()] + column_definitions
871 discriminator_columns = [c for c in column_definitions if c[1].discriminator_column]
872 is_polymorphic = len(discriminator_columns) > 0
873 if len(discriminator_columns) > 1:
874 raise ModelDefinitionException('only one discriminator_column can be defined in a model, {0} found'.format(len(discriminator_columns)))
875
876 if attrs['__discriminator_value__'] and not is_polymorphic:
877 raise ModelDefinitionException('__discriminator_value__ specified, but no base columns defined with discriminator_column=True')
878
879 discriminator_column_name, discriminator_column = discriminator_columns[0] if discriminator_columns else (None, None)
880
881 if isinstance(discriminator_column, (columns.BaseContainerColumn, columns.Counter)):
882 raise ModelDefinitionException('counter and container columns cannot be used as discriminator columns')
883
884 # find polymorphic base class
885 polymorphic_base = None
886 if is_polymorphic and not is_polymorphic_base:
887 def _get_polymorphic_base(bases):
888 for base in bases:
889 if getattr(base, '_is_polymorphic_base', False):
890 return base
891 klass = _get_polymorphic_base(base.__bases__)
892 if klass:
893 return klass
894 polymorphic_base = _get_polymorphic_base(bases)
895
896 defined_columns = OrderedDict(column_definitions)
897
898 # check for primary key
899 if not is_abstract and not any([v.primary_key for k, v in column_definitions]):
900 raise ModelDefinitionException("At least 1 primary key is required.")
901
902 counter_columns = [c for c in defined_columns.values() if isinstance(c, columns.Counter)]
903 data_columns = [c for c in defined_columns.values() if not c.primary_key and not isinstance(c, columns.Counter)]
904 if counter_columns and data_columns:
905 raise ModelDefinitionException('counter models may not have data columns')
906
907 has_partition_keys = any(v.partition_key for (k, v) in column_definitions)
908
909 def _transform_column(col_name, col_obj):
910 column_dict[col_name] = col_obj
911 if col_obj.primary_key:
912 primary_keys[col_name] = col_obj
913 col_obj.set_column_name(col_name)
914 # set properties
915 attrs[col_name] = ColumnDescriptor(col_obj)
916
917 partition_key_index = 0
918 # transform column definitions
919 for k, v in column_definitions:
920 # don't allow a column with the same name as a built-in attribute or method
921 if k in BaseModel.__dict__:
922 raise ModelDefinitionException("column '{0}' conflicts with built-in attribute/method".format(k))
923
924 # counter column primary keys are not allowed
925 if (v.primary_key or v.partition_key) and isinstance(v, columns.Counter):
926 raise ModelDefinitionException('counter columns cannot be used as primary keys')
927
928 # this will mark the first primary key column as a partition
929 # key, if one hasn't been set already
930 if not has_partition_keys and v.primary_key:
931 v.partition_key = True
932 has_partition_keys = True
933 if v.partition_key:
934 v._partition_key_index = partition_key_index
935 partition_key_index += 1
936
937 overriding = column_dict.get(k)
938 if overriding:
939 v.position = overriding.position
940 v.partition_key = overriding.partition_key
941 v._partition_key_index = overriding._partition_key_index
942 _transform_column(k, v)
943
944 partition_keys = OrderedDict(k for k in primary_keys.items() if k[1].partition_key)
945 clustering_keys = OrderedDict(k for k in primary_keys.items() if not k[1].partition_key)
946
947 if attrs.get('__compute_routing_key__', True):
948 key_cols = [c for c in partition_keys.values()]
949 partition_key_index = dict((col.db_field_name, col._partition_key_index) for col in key_cols)
950 key_cql_types = [c.cql_type for c in key_cols]
951 key_serializer = staticmethod(lambda parts, proto_version: [t.to_binary(p, proto_version) for t, p in zip(key_cql_types, parts)])
952 else:
953 partition_key_index = {}
954 key_serializer = staticmethod(lambda parts, proto_version: None)
955
956 # setup partition key shortcut
957 if len(partition_keys) == 0:
958 if not is_abstract:
959 raise ModelException("at least one partition key must be defined")
960 if len(partition_keys) == 1:
961 pk_name = [x for x in partition_keys.keys()][0]
962 attrs['pk'] = attrs[pk_name]
963 else:
964 # composite partition key case, get/set a tuple of values
965 _get = lambda self: tuple(self._values[c].getval() for c in partition_keys.keys())
966 _set = lambda self, val: tuple(self._values[c].setval(v) for (c, v) in zip(partition_keys.keys(), val))
967 attrs['pk'] = property(_get, _set)
968
969 # some validation
970 col_names = set()
971 for v in column_dict.values():
972 # check for duplicate column names
973 if v.db_field_name in col_names:
974 raise ModelException("{0} defines the column '{1}' more than once".format(name, v.db_field_name))
975 if v.clustering_order and not (v.primary_key and not v.partition_key):
976 raise ModelException("clustering_order may be specified only for clustering primary keys")
977 if v.clustering_order and v.clustering_order.lower() not in ('asc', 'desc'):
978 raise ModelException("invalid clustering order '{0}' for column '{1}'".format(repr(v.clustering_order), v.db_field_name))
979 col_names.add(v.db_field_name)
980
981 # create db_name -> model name map for loading
982 db_map = {}
983 for col_name, field in column_dict.items():
984 db_field = field.db_field_name
985 if db_field != col_name:
986 db_map[db_field] = col_name
987
988 # add management members to the class
989 attrs['_columns'] = column_dict
990 attrs['_primary_keys'] = primary_keys
991 attrs['_defined_columns'] = defined_columns
992
993 # maps the database field to the models key
994 attrs['_db_map'] = db_map
995 attrs['_pk_name'] = pk_name
996 attrs['_dynamic_columns'] = {}
997
998 attrs['_partition_keys'] = partition_keys
999 attrs['_partition_key_index'] = partition_key_index
1000 attrs['_key_serializer'] = key_serializer
1001 attrs['_clustering_keys'] = clustering_keys
1002 attrs['_has_counter'] = len(counter_columns) > 0
1003
1004 # add polymorphic management attributes
1005 attrs['_is_polymorphic_base'] = is_polymorphic_base
1006 attrs['_is_polymorphic'] = is_polymorphic
1007 attrs['_polymorphic_base'] = polymorphic_base
1008 attrs['_discriminator_column'] = discriminator_column
1009 attrs['_discriminator_column_name'] = discriminator_column_name
1010 attrs['_discriminator_map'] = {} if is_polymorphic_base else None
1011
1012 # setup class exceptions
1013 DoesNotExistBase = None
1014 for base in bases:
1015 DoesNotExistBase = getattr(base, 'DoesNotExist', None)
1016 if DoesNotExistBase is not None:
1017 break
1018
1019 DoesNotExistBase = DoesNotExistBase or attrs.pop('DoesNotExist', BaseModel.DoesNotExist)
1020 attrs['DoesNotExist'] = type('DoesNotExist', (DoesNotExistBase,), {})
1021
1022 MultipleObjectsReturnedBase = None
1023 for base in bases:
1024 MultipleObjectsReturnedBase = getattr(base, 'MultipleObjectsReturned', None)
1025 if MultipleObjectsReturnedBase is not None:
1026 break
1027
1028 MultipleObjectsReturnedBase = MultipleObjectsReturnedBase or attrs.pop('MultipleObjectsReturned', BaseModel.MultipleObjectsReturned)
1029 attrs['MultipleObjectsReturned'] = type('MultipleObjectsReturned', (MultipleObjectsReturnedBase,), {})
1030
1031 # create the class and add a QuerySet to it
1032 klass = super(ModelMetaClass, cls).__new__(cls, name, bases, attrs)
1033
1034 udts = []
1035 for col in column_dict.values():
1036 columns.resolve_udts(col, udts)
1037
1038 for user_type in set(udts):
1039 user_type.register_for_keyspace(klass._get_keyspace())
1040
1041 return klass
1042
1043
1044 class Model(BaseModel, metaclass=ModelMetaClass):
1045 __abstract__ = True
1046 """
1047 *Optional.* Indicates that this model is only intended to be used as a base class for other models.
1048 You can't create tables for abstract models, but checks around schema validity are skipped during class construction.
1049 """
1050
1051 __table_name__ = None
1052 """
1053 *Optional.* Sets the name of the CQL table for this model. If left blank, the table name will be the name of the model, with it's module name as it's prefix. Manually defined table names are not inherited.
1054 """
1055
1056 __table_name_case_sensitive__ = False
1057 """
1058 *Optional.* By default, __table_name__ is case insensitive. Set this to True if you want to preserve the case sensitivity.
1059 """
1060
1061 __keyspace__ = None
1062 """
1063 Sets the name of the keyspace used by this model.
1064 """
1065
1066 __connection__ = None
1067 """
1068 Sets the name of the default connection used by this model.
1069 """
1070
1071 __options__ = None
1072 """
1073 *Optional* Table options applied with this model
1074
1075 (e.g. compaction, default ttl, cache settings, tec.)
1076 """
1077
1078 __discriminator_value__ = None
1079 """
1080 *Optional* Specifies a value for the discriminator column when using model inheritance.
1081 """
1082
1083 __compute_routing_key__ = True
1084 """
1085 *Optional* Setting False disables computing the routing key for TokenAwareRouting
1086 """