Ejemplo n.º 1
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('{} is not a list object'.format(val))
     if None in val:
         raise ValidationError("None is not allowed in a list")
     return [self.value_col.validate(v) for v in val]
Ejemplo n.º 2
0
    def update(self, **values):
        """ Updates the rows in this queryset """
        if not values:
            return

        nulled_columns = set()
        us = UpdateStatement(self.column_family_name,
                             where=self._where,
                             ttl=self._ttl,
                             timestamp=self._timestamp)
        for name, val in values.items():
            col_name, col_op = self._parse_filter_arg(name)
            col = self.model._columns.get(col_name)
            # check for nonexistant columns
            if col is None:
                raise ValidationError("{}.{} has no column named: {}".format(
                    self.__module__, self.model.__name__, col_name))
            # check for primary key update attempts
            if col.is_primary_key:
                raise ValidationError(
                    "Cannot apply update to primary key '{}' for {}.{}".format(
                        col_name, self.__module__, self.model.__name__))

            val = col.validate(val)
            if val is None:
                nulled_columns.add(col_name)
                continue

            # add the update statements
            if isinstance(col, Counter):
                # TODO: implement counter updates
                raise NotImplementedError
            elif isinstance(col, (List, Set, Map)):
                if isinstance(col, List):
                    klass = ListUpdateClause
                elif isinstance(col, Set):
                    klass = SetUpdateClause
                elif isinstance(col, Map):
                    klass = MapUpdateClause
                else:
                    raise RuntimeError
                us.add_assignment_clause(
                    klass(col_name, col.to_database(val), operation=col_op))
            else:
                us.add_assignment_clause(
                    AssignmentClause(col_name, col.to_database(val)))

        if us.assignments:
            self._execute(us)

        if nulled_columns:
            ds = DeleteStatement(self.column_family_name,
                                 fields=nulled_columns,
                                 where=self._where)
            self._execute(ds)
Ejemplo n.º 3
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('{} is not a set object'.format(val))
            else:
                raise ValidationError(
                    '{} cannot be coerced to a set object'.format(val))

        return {self.value_col.validate(v) for v in val}
Ejemplo n.º 4
0
 def validate(self, value):
     value = super(Text, self).validate(value)
     if value is None: return
     if not isinstance(value,
                       (six.string_types, bytearray)) and value is not None:
         raise ValidationError('{} is not a string'.format(type(value)))
     if self.max_length:
         if len(value) > self.max_length:
             raise ValidationError('{} is longer than {} characters'.format(
                 self.column_name, self.max_length))
     if self.min_length:
         if len(value) < self.min_length:
             raise ValidationError(
                 '{} is shorter than {} characters'.format(
                     self.column_name, self.min_length))
     return value
Ejemplo n.º 5
0
 def validate(self, value):
     value = super(Float, self).validate(value)
     if value is None: return
     try:
         return float(value)
     except (TypeError, ValueError):
         raise ValidationError("{} is not a valid float".format(value))
Ejemplo n.º 6
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(
             "{} can't be converted to integral value".format(value))
Ejemplo n.º 7
0
 def validate(self, value):
     value = super(BaseContainerColumn, 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(
             "Collection can't have more than 65535 elements.")
     return value
Ejemplo n.º 8
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(value))
Ejemplo n.º 9
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.º 10
0
    def update(self, **values):
        for k, v in values.items():
            col = self._columns.get(k)

            # check for nonexistant columns
            if col is None:
                raise ValidationError("{}.{} has no column named: {}".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 '{}' for {}.{}".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._polymorphic_column_name,
                        self.__polymorphic_key__)

        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.º 11
0
    def to_database(self, value):
        value = super(Date, self).to_database(value)
        if isinstance(value, datetime):
            value = value.date()
        if not isinstance(value, date):
            raise ValidationError("'{}' is not a date object".format(
                repr(value)))

        return long((value - date(1970, 1, 1)).total_seconds() * 1000)
Ejemplo n.º 12
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(val))
     return {
         self.key_col.validate(k): self.value_col.validate(v)
         for k, v in val.items()
     }
Ejemplo n.º 13
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(val)
     except InvalidOperation:
         raise ValidationError(
             "'{}' can't be coerced to decimal".format(val))
Ejemplo n.º 14
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.º 15
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(
                 '{} - None values are not allowed'.format(
                     self.column_name or self.db_field))
     return value
Ejemplo n.º 16
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
        """
        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.º 17
0
    def to_database(self, value):
        value = super(DateTime, self).to_database(value)
        if value is None: return
        if not isinstance(value, datetime):
            if isinstance(value, date):
                value = datetime(value.year, value.month, value.day)
            else:
                raise ValidationError(
                    "'{}' is not a datetime object".format(value))
        epoch = datetime(1970, 1, 1, tzinfo=value.tzinfo)
        offset = epoch.tzinfo.utcoffset(
            epoch).total_seconds() if epoch.tzinfo else 0

        return int(((value - epoch).total_seconds() - offset) * 1000)
Ejemplo n.º 18
0
    def __init__(self, **values):
        self._values = {}

        extra_columns = set(values.keys()) - set(self._columns.keys())
        if extra_columns:
            raise ValidationError(
                "Incorrect columns passed: {}".format(extra_columns))

        for name, column in self._columns.items():
            value = values.get(name, None)
            if value is not None or isinstance(column,
                                               columns.BaseContainerColumn):
                value = column.to_python(value)
            value_mngr = column.value_manager(self, column, value)
            self._values[name] = value_mngr

        # a flag set by the deserializer to indicate
        # that update should be used when persisting changes
        self._is_persisted = False
        self._batch = None
Ejemplo n.º 19
0
 def create(cls, **kwargs):
     extra_columns = set(kwargs.keys()) - set(cls._columns.keys())
     if extra_columns:
         raise ValidationError(
             "Incorrect columns passed: {}".format(extra_columns))
     return cls.objects.create(**kwargs)