Ejemplo n.º 1
0
    def validate(self):
        super(FamilyMembers, self).validate()
        if self.sex and self.sex not in 'mf':
            raise ValidationError("FamilyMember.sex must be one of ['m', 'f']")

        if self.birth_year and self.sex == 'f':
            raise ValidationError("FamilyMember.birth_year is set, and 'a lady never tells'")
Ejemplo n.º 2
0
    def __init__(self, key_type, value_type, default=dict, **kwargs):
        """
        :param key_type: a column class indicating the types of the key
        :param value_type: a column class indicating the types of the value
        """

        self.db_type = 'map<{0}, {1}>'.format(key_type.db_type,
                                              value_type.db_type)

        inheritance_comparator = issubclass if isinstance(key_type,
                                                          type) else isinstance
        if not inheritance_comparator(key_type, Column):
            raise ValidationError('key_type must be a column class')
        if inheritance_comparator(key_type, BaseContainerColumn):
            raise ValidationError('container types cannot be nested')
        if key_type.db_type is None:
            raise ValidationError('key_type cannot be an abstract column type')

        if isinstance(key_type, type):
            self.key_type = key_type
            self.key_col = self.key_type()
        else:
            self.key_col = key_type
            self.key_type = self.key_col.__class__
        super(Map, self).__init__(value_type, default=default, **kwargs)
Ejemplo n.º 3
0
 def validate(self, value):
     val = super(List, self).validate(value)
     if val is None:
         return
     if not isinstance(val, (set, list, tuple)):
         raise ValidationError('{0} {1} is not a list object'.format(self.column_name, val))
     if None in val:
         raise ValidationError("{0} None is not allowed in a list".format(self.column_name))
     return [self.value_col.validate(v) for v in val]
Ejemplo n.º 4
0
 def validate(self, value):
     val = super(Map, self).validate(value)
     if val is None:
         return
     if not isinstance(val, dict):
         raise ValidationError('{0} {1} is not a dict object'.format(self.column_name, val))
     if None in val:
         raise ValidationError("{0} None is not allowed in a map".format(self.column_name))
     return dict((self.key_col.validate(k), self.value_col.validate(v)) for k, v in val.items())
Ejemplo n.º 5
0
    def update(self, **values):
        """
        Performs an update on the model instance. You can pass in values to set on the model
        for updating, or you can call without values to execute an update against any modified
        fields. If no fields on the model have been modified since loading, no query will be
        performed. Model validation is performed normally. Setting a value to `None` is
        equivalent to running a CQL `DELETE` on that column.

        It is possible to do a blind update, that is, to update a field without having first selected the object out of the database.
        See :ref:`Blind Updates <blind_updates>`
        """
        for column_id, v in values.items():
            col = self._columns.get(column_id)

            # check for nonexistant columns
            if col is None:
                raise ValidationError(
                    "{0}.{1} has no column named: {2}".format(
                        self.__module__, self.__class__.__name__, column_id))

            # check for primary key update attempts
            if col.is_primary_key:
                current_value = getattr(self, column_id)
                if v != current_value:
                    raise ValidationError(
                        "Cannot apply update to primary key '{0}' for {1}.{2}".
                        format(column_id, self.__module__,
                               self.__class__.__name__))

            setattr(self, column_id, v)

        # handle polymorphic models
        if self._is_polymorphic:
            if self._is_polymorphic_base:
                raise PolymorphicModelException(
                    'cannot update polymorphic base model')
            else:
                setattr(self, self._discriminator_column_name,
                        self.__discriminator_value__)

        self.validate()
        self.__dmlquery__(self.__class__,
                          self,
                          batch=self._batch,
                          ttl=self._ttl,
                          timestamp=self._timestamp,
                          consistency=self.__consistency__,
                          conditional=self._conditional,
                          timeout=self._timeout,
                          if_exists=self._if_exists).update()

        self._set_persisted()

        self._timestamp = None

        return self
Ejemplo n.º 6
0
    def update(self, **values):
        """
        Performs an update on the model instance. You can pass in values to set on the model
        for updating, or you can call without values to execute an update against any modified
        fields. If no fields on the model have been modified since loading, no query will be
        performed. Model validation is performed normally.

        It is possible to do a blind update, that is, to update a field without having first selected the object out of the database.
        See :ref:`Blind Updates <blind_updates>`
        """
        for k, v in values.items():
            col = self._columns.get(k)

            # check for nonexistant columns
            if col is None:
                raise ValidationError(
                    "{0}.{1} has no column named: {2}".format(
                        self.__module__, self.__class__.__name__, k))

            # check for primary key update attempts
            if col.is_primary_key:
                raise ValidationError(
                    "Cannot apply update to primary key '{0}' for {1}.{2}".
                    format(k, self.__module__, self.__class__.__name__))

            setattr(self, k, v)

        # handle polymorphic models
        if self._is_polymorphic:
            if self._is_polymorphic_base:
                raise PolymorphicModelException(
                    'cannot update polymorphic base model')
            else:
                setattr(self, self._discriminator_column_name,
                        self.__discriminator_value__)

        self.validate()
        self.__dmlquery__(self.__class__,
                          self,
                          batch=self._batch,
                          ttl=self._ttl,
                          timestamp=self._timestamp,
                          consistency=self.__consistency__,
                          transaction=self._transaction,
                          timeout=self._timeout).update()

        # reset the value managers
        for v in self._values.values():
            v.reset_previous_value()
        self._is_persisted = True

        self._ttl = self.__default_ttl__
        self._timestamp = None

        return self
Ejemplo n.º 7
0
 def validate(self, value):
     value = super(Text, self).validate(value)
     if not isinstance(value, (six.string_types, bytearray)) and value is not None:
         raise ValidationError('{0} {1} is not a string'.format(self.column_name, type(value)))
     if self.max_length is not None:
         if value and len(value) > self.max_length:
             raise ValidationError('{0} is longer than {1} characters'.format(self.column_name, self.max_length))
     if self.min_length:
         if (self.min_length and not value) or len(value) < self.min_length:
             raise ValidationError('{0} is shorter than {1} characters'.format(self.column_name, self.min_length))
     return value
Ejemplo n.º 8
0
 def validate(self, value):
     val = super(Map, self).validate(value)
     if val is None:
         return
     if not isinstance(val, (dict, util.OrderedMap)):
         raise ValidationError('{0} {1} is not a dict object'.format(self.column_name, val))
     if None in val:
         raise ValidationError("{0} None is not allowed in a map".format(self.column_name))
     # TODO: stop doing this conversion because it doesn't support non-hashable collections as keys (cassandra does)
     # will need to start using the cassandra.util types in the next major rev (PYTHON-494)
     return dict((self.key_col.validate(k), self.value_col.validate(v)) for k, v in val.items())
Ejemplo n.º 9
0
    def validate_elements_quantities(elements_quantities):
        elements_quantity_sum = 0

        for element in elements_quantities:
            if element < 0:
                raise ValidationError('invalid element quantity')
            elements_quantity_sum += element

        if abs(elements_quantity_sum - 100) > 0.1:
            raise ValidationError('invalid elements quantity')

        return elements_quantities
Ejemplo n.º 10
0
    def validate(self, value):
        val = super(Set, self).validate(value)
        if val is None:
            return
        types = (set,) if self.strict else (set, list, tuple)
        if not isinstance(val, types):
            if self.strict:
                raise ValidationError('{0} {1} is not a set object'.format(self.column_name, val))
            else:
                raise ValidationError('{0} {1} cannot be coerced to a set object'.format(self.column_name, val))

        if None in val:
            raise ValidationError("{0} None not allowed in a set".format(self.column_name))

        return set(self.value_col.validate(v) for v in val)
Ejemplo n.º 11
0
 def validate(self, value):
     value = super(BaseCollectionColumn, self).validate(value)
     # It is dangerous to let collections have more than 65535.
     # See: https://issues.apache.org/jira/browse/CASSANDRA-5428
     if value is not None and len(value) > 65535:
         raise ValidationError("{0} Collection can't have more than 65535 elements.".format(self.column_name))
     return value
Ejemplo n.º 12
0
    def validate(self, value):
        val = super(Set, self).validate(value)
        if val is None:
            return
        types = (set, util.SortedSet) if self.strict else (set, util.SortedSet, list, tuple)
        if not isinstance(val, types):
            if self.strict:
                raise ValidationError('{0} {1} is not a set object'.format(self.column_name, val))
            else:
                raise ValidationError('{0} {1} cannot be coerced to a set object'.format(self.column_name, val))

        if None in val:
            raise ValidationError("{0} None not allowed in a set".format(self.column_name))
        # TODO: stop doing this conversion because it doesn't support non-hashable collections as keys (cassandra does)
        # will need to start using the cassandra.util types in the next major rev (PYTHON-494)
        return set(self.value_col.validate(v) for v in val)
Ejemplo n.º 13
0
    def validate(self):
        super(SystemTest, self).validate()

        if self.result < 0 or self.result > 100:
            raise ValidationError('not a valid test result value')

        SystemTest.validate_system_id(self.system_id)
Ejemplo n.º 14
0
 def validate(self, value):
     super().validate(value)
     if not self.EMAIL_REGEX.match(value):
         raise ValidationError(
             '{} is not valid email address'.format(value)
         )
     return value
Ejemplo n.º 15
0
 def __init__(self, value):
     """
     :param value: the time to create a minimum time uuid from
     :type value: datetime
     """
     if not isinstance(value, datetime):
         raise ValidationError('datetime instance is required')
     super(MaxTimeUUID, self).__init__(value)
Ejemplo n.º 16
0
 def validate(self, value):
     value = super(BaseFloat, self).validate(value)
     if value is None:
         return
     try:
         return float(value)
     except (TypeError, ValueError):
         raise ValidationError("{0} {1} is not a valid float".format(self.column_name, value))
Ejemplo n.º 17
0
 def validate(self, value):
     val = super(Integer, self).validate(value)
     if val is None:
         return
     try:
         return int(val)
     except (TypeError, ValueError):
         raise ValidationError("{0} {1} can't be converted to integral value".format(self.column_name, value))
Ejemplo n.º 18
0
 def __init__(self, value):
     """
     :param value: the time to create bounding time uuid from
     :type value: datetime
     """
     if not isinstance(value, datetime):
         raise ValidationError('datetime instance is required')
     super(TimeUUIDQueryFunction, self).__init__(value)
Ejemplo n.º 19
0
 def validate(self, value):
     val = super(Tuple, self).validate(value)
     if val is None:
         return
     if len(val) > len(self.types):
         raise ValidationError("Value %r has more fields than tuple definition (%s)" %
                               (val, ', '.join(t for t in self.types)))
     return tuple(t.validate(v) for t, v in zip(self.types, val))
Ejemplo n.º 20
0
def _state_change_validation(current: EtlStates, new: EtlStates) -> None:
    if new in (EtlStates.Succeeded,
               EtlStates.Failed) and current != EtlStates.Processing:
        raise ValidationError(
            f"Current State '{current}' cannot transition to '{new}'")

    if new == EtlStates.Processing and current != EtlStates.Ready:
        raise ValidationError(
            f"Current State '{current}' cannot transition to '{new}'")

    if new == current:
        raise ValidationError(
            f"Current State '{current}' cannot transition to '{new}', "
            f"you might have duplicate records in your data set")

    if current == EtlStates.Succeeded:
        raise ValidationError(
            f"Current State '{current}' does not allow any transitions")
Ejemplo n.º 21
0
 def validate(self, value):
     """
     Returns a cleaned and validated value. Raises a ValidationError
     if there's a problem
     """
     if value is None:
         if self.required:
             raise ValidationError('{0} - None values are not allowed'.format(self.column_name or self.db_field))
     return value
Ejemplo n.º 22
0
    def __init__(self, types, **kwargs):
        """
        :param types: a sequence of sub types in this collection
        """
        instances = []
        for t in types:
            inheritance_comparator = issubclass if isinstance(t, type) else isinstance
            if not inheritance_comparator(t, Column):
                raise ValidationError("%s is not a column class" % (t,))
            if t.db_type is None:
                raise ValidationError("%s is an abstract type" % (t,))
            inst = t() if isinstance(t, type) else t
            if isinstance(t, BaseCollectionColumn):
                inst._freeze_db_type()
            instances.append(inst)

        self.types = instances
        super(BaseCollectionColumn, self).__init__(**kwargs)
Ejemplo n.º 23
0
 def validate(self, value):
     from decimal import Decimal as _Decimal
     from decimal import InvalidOperation
     val = super(Decimal, self).validate(value)
     if val is None:
         return
     try:
         return _Decimal(repr(val)) if isinstance(val, float) else _Decimal(val)
     except InvalidOperation:
         raise ValidationError("{0} '{1}' can't be coerced to decimal".format(self.column_name, val))
Ejemplo n.º 24
0
    def __init__(self, value_type, **kwargs):
        """
        :param value_type: a column class indicating the types of the value
        """
        inheritance_comparator = issubclass if isinstance(value_type, type) else isinstance
        if not inheritance_comparator(value_type, Column):
            raise ValidationError('value_type must be a column class')
        if inheritance_comparator(value_type, BaseContainerColumn):
            raise ValidationError('container types cannot be nested')
        if value_type.db_type is None:
            raise ValidationError('value_type cannot be an abstract column type')

        if isinstance(value_type, type):
            self.value_type = value_type
            self.value_col = self.value_type()
        else:
            self.value_col = value_type
            self.value_type = self.value_col.__class__

        super(BaseContainerColumn, self).__init__(**kwargs)
Ejemplo n.º 25
0
    def to_database(self, value):
        value = super(Date, self).to_database(value)
        if value is None:
            return
        if isinstance(value, datetime):
            value = value.date()
        if not isinstance(value, date):
            raise ValidationError("{} '{}' is not a date object".format(
                self.column_name, repr(value)))

        return int((value - date(1970, 1, 1)).total_seconds() * 1000)
Ejemplo n.º 26
0
 def validate(self, value):
     val = super(UUID, self).validate(value)
     if val is None:
         return
     from uuid import UUID as _UUID
     if isinstance(val, _UUID):
         return val
     if isinstance(val, six.string_types) and self.re_uuid.match(val):
         return _UUID(val)
     raise ValidationError("{} {} is not a valid uuid".format(
         self.column_name, value))
Ejemplo n.º 27
0
 def validate(self, value):
     val = super(Map, self).validate(value)
     if val is None:
         return
     if not isinstance(val, dict):
         raise ValidationError('{} {} is not a dict object'.format(
             self.column_name, val))
     return {
         self.key_col.validate(k): self.value_col.validate(v)
         for k, v in val.items()
     }
Ejemplo n.º 28
0
    def create(cls, **kwargs):
        """
        Create an instance of this model in the database.

        Takes the model column values as keyword arguments.

        Returns the instance.
        """
        extra_columns = set(kwargs.keys()) - set(cls._columns.keys())
        if extra_columns:
            raise ValidationError("Incorrect columns passed: {0}".format(extra_columns))
        return cls.objects.create(**kwargs)
Ejemplo n.º 29
0
 def __init__(self, value_type, strict=True, default=set, **kwargs):
     """
     :param value_type: a column class indicating the types of the value
     :param strict: sets whether non set values will be coerced to set
         type on validation, or raise a validation error, defaults to True
     """
     self.strict = strict
     super(Set, self).__init__((value_type,), default=default, **kwargs)
     self.value_col = self.types[0]
     if not self.value_col._python_type_hashable:
         raise ValidationError("Cannot create a Set with unhashable value type (see PYTHON-494)")
     self.db_type = 'set<{0}>'.format(self.value_col.db_type)
Ejemplo n.º 30
0
    def create(cls, **kwargs):
        parent = kwargs.get('parent')
        if parent is None:
            raise ValidationError('parent - None values are not allowed.')

        kwargs['parent_id'] = parent.id
        kwargs['data'] = parent.to_json()
        del kwargs['parent']
        event = super(Event, cls).create(**kwargs)
        sender = 'event.{}'.format(event.type)
        signal('on_event').send(sender, instance=event, parent=parent)
        return event