def test_insert_statement_execute(self):
        """
        Test to verify the execution of BaseCQLStatements using connection.execute

        @since 3.10
        @jira_ticket PYTHON-505
        @expected_result inserts a row in C*, updates the rows and then deletes
        all the rows using BaseCQLStatements

        @test_category data_types:object_mapper
        """
        partition = uuid4()
        cluster = 1
        self._insert_statement(partition, cluster)

        # Verifying update statement
        where = [WhereClause('partition', EqualsOperator(), partition),
                 WhereClause('cluster', EqualsOperator(), cluster)]

        st = UpdateStatement(self.table_name, where=where)
        st.add_assignment(Column(db_field='count'), 2)
        st.add_assignment(Column(db_field='text'), "text_for_db_update")
        st.add_assignment(Column(db_field='text_set'), set(("foo_update", "bar_update")))
        st.add_assignment(Column(db_field='text_list'), ["foo_update", "bar_update"])
        st.add_assignment(Column(db_field='text_map'), {"foo": '3', "bar": '4'})

        execute(st)
        self._verify_statement(st)

        # Verifying delete statement
        execute(DeleteStatement(self.table_name, where=where))
        self.assertEqual(TestQueryUpdateModel.objects.count(), 0)
    def test_where_clause_rendering(self):
        """ tests that where clauses are rendered properly """
        wc = WhereClause('a', EqualsOperator(), 'c')
        wc.set_context_id(5)

        self.assertEqual('"a" = %(5)s', six.text_type(wc), six.text_type(wc))
        self.assertEqual('"a" = %(5)s', str(wc), type(wc))
示例#3
0
    def _check_partition_value_generation(self, model, state, reverse=False):
        """
        This generates a some statements based on the partition_key_index of the model.
        It then validates that order of the partition key values in the statement matches the index
        specified in the models partition_key_index
        """
        # Setup some unique values for statement generation
        uuid = uuid4()
        values = {
            'k': 5,
            'v': 3,
            'partition': uuid,
            'cluster': 6,
            'count': 42,
            'text': 'text',
            'float': 3.1415,
            'text_2': 'text_2'
        }
        res = dict((v, k) for k, v in values.items())
        items = list(model._partition_key_index.items())
        if (reverse):
            items.reverse()
        # Add where clauses for each partition key
        for partition_key, position in items:
            wc = WhereClause(partition_key, EqualsOperator(),
                             values.get(partition_key))
            state._add_where_clause(wc)

        # Iterate over the partition key values check to see that their index matches
        # Those specified in the models partition field
        for indx, value in enumerate(
                state.partition_key_values(model._partition_key_index)):
            name = res.get(value)
            self.assertEqual(indx, model._partition_key_index.get(name))
示例#4
0
    def _delete_null_columns(self):
        """
        executes a delete query to remove columns that have changed to null
        """
        ds = DeleteStatement(self.column_family_name)
        deleted_fields = False
        for _, v in self.instance._values.items():
            col = v.column
            if v.deleted:
                ds.add_field(col.db_field_name)
                deleted_fields = True
            elif isinstance(col, columns.Map):
                uc = MapDeleteClause(col.db_field_name, v.value, v.previous_value)
                if uc.get_context_size() > 0:
                    ds.add_field(uc)
                    deleted_fields = True

        if deleted_fields:
            for name, col in self.model._primary_keys.items():
                ds.add_where_clause(WhereClause(
                    col.db_field_name,
                    EqualsOperator(),
                    col.to_database(getattr(self.instance, name))
                ))
            self._execute(ds)
示例#5
0
    def test_mintimeuuid_function(self):
        """
        Tests that queries with helper functions are generated properly
        """
        now = datetime.now()
        where = WhereClause('time', EqualsOperator(), functions.MinTimeUUID(now))
        where.set_context_id(5)

        self.assertEqual(str(where), '"time" = MinTimeUUID(%(5)s)')
        ctx = {}
        where.update_context(ctx)
        self.assertEqual(ctx, {'5': columns.DateTime().to_database(now)})
示例#6
0
    def delete(self):
        """ Deletes one instance """
        if self.instance is None:
            raise CQLEngineException("DML Query instance attribute is None")

        ds = DeleteStatement(self.column_family_name, timestamp=self._timestamp, conditionals=self._conditional, if_exists=self._if_exists)
        for name, col in self.model._primary_keys.items():
            val = getattr(self.instance, name)
            if val is None and not col.partition_key:
                continue
            ds.add_where(col, EqualsOperator(), val)
        self._execute(ds)
示例#7
0
    def update(self):
        """
        updates a row.
        This is a blind update call.
        All validation and cleaning needs to happen
        prior to calling this.
        """
        if self.instance is None:
            raise CQLEngineException("DML Query intance attribute is None")
        assert type(self.instance) == self.model
        null_clustering_key = False if len(self.instance._clustering_keys) == 0 else True
        static_changed_only = True
        statement = UpdateStatement(self.column_family_name, ttl=self._ttl, timestamp=self._timestamp,
                                    conditionals=self._conditional, if_exists=self._if_exists)
        for name, col in self.instance._clustering_keys.items():
            null_clustering_key = null_clustering_key and col._val_is_null(getattr(self.instance, name, None))

        updated_columns = set()
        # get defined fields and their column names
        for name, col in self.model._columns.items():
            # if clustering key is null, don't include non static columns
            if null_clustering_key and not col.static and not col.partition_key:
                continue
            if not col.is_primary_key:
                val = getattr(self.instance, name, None)
                val_mgr = self.instance._values[name]

                if val is None:
                    continue

                if not val_mgr.changed and not isinstance(col, columns.Counter):
                    continue

                static_changed_only = static_changed_only and col.static
                statement.add_update(col, val, previous=val_mgr.previous_value)
                updated_columns.add(col.db_field_name)

        if statement.assignments:
            for name, col in self.model._primary_keys.items():
                # only include clustering key if clustering key is not null, and non static columns are changed to avoid cql error
                if (null_clustering_key or static_changed_only) and (not col.partition_key):
                    continue
                statement.add_where(col, EqualsOperator(), getattr(self.instance, name))
            self._execute(statement)

        if not null_clustering_key:
            # remove conditions on fields that have been updated
            delete_conditionals = [condition for condition in self._conditional
                                   if condition.field not in updated_columns] if self._conditional else None
            self._delete_null_columns(delete_conditionals)
示例#8
0
    def delete(self):
        """ Deletes one instance """
        if self.instance is None:
            raise CQLEngineException("DML Query instance attribute is None")

        ds = DeleteStatement(self.column_family_name,
                             timestamp=self._timestamp)
        for name, col in self.model._primary_keys.items():
            if (not col.partition_key) and (getattr(self.instance, name) is
                                            None):
                continue

            ds.add_where_clause(
                WhereClause(col.db_field_name, EqualsOperator(),
                            col.to_database(getattr(self.instance, name))))
        self._execute(ds)
 def test_equality_method(self):
     """ tests that 2 identical where clauses evaluate as == """
     wc1 = WhereClause('a', EqualsOperator(), 'c')
     wc2 = WhereClause('a', EqualsOperator(), 'c')
     assert wc1 == wc2
示例#10
0
 def __eq__(self, other):
     return WhereClause(six.text_type(self), EqualsOperator(),
                        self._to_database(other))
示例#11
0
    def update(self):
        """
        updates a row.
        This is a blind update call.
        All validation and cleaning needs to happen
        prior to calling this.
        """
        if self.instance is None:
            raise CQLEngineException("DML Query intance attribute is None")
        assert type(self.instance) == self.model
        null_clustering_key = False if len(
            self.instance._clustering_keys) == 0 else True
        static_changed_only = True
        statement = UpdateStatement(self.column_family_name,
                                    ttl=self._ttl,
                                    timestamp=self._timestamp,
                                    transactions=self._transaction)
        for name, col in self.instance._clustering_keys.items():
            null_clustering_key = null_clustering_key and col._val_is_null(
                getattr(self.instance, name, None))
        # get defined fields and their column names
        for name, col in self.model._columns.items():
            # if clustering key is null, don't include non static columns
            if null_clustering_key and not col.static and not col.partition_key:
                continue
            if not col.is_primary_key:
                val = getattr(self.instance, name, None)
                val_mgr = self.instance._values[name]

                # don't update something that is null
                if val is None:
                    continue

                # don't update something if it hasn't changed
                if not val_mgr.changed and not isinstance(
                        col, columns.Counter):
                    continue

                static_changed_only = static_changed_only and col.static
                if isinstance(col,
                              (columns.BaseContainerColumn, columns.Counter)):
                    # get appropriate clause
                    if isinstance(col, columns.List):
                        klass = ListUpdateClause
                    elif isinstance(col, columns.Map):
                        klass = MapUpdateClause
                    elif isinstance(col, columns.Set):
                        klass = SetUpdateClause
                    elif isinstance(col, columns.Counter):
                        klass = CounterUpdateClause
                    else:
                        raise RuntimeError

                    # do the stuff
                    clause = klass(col.db_field_name,
                                   val,
                                   previous=val_mgr.previous_value,
                                   column=col)
                    if clause.get_context_size() > 0:
                        statement.add_assignment_clause(clause)
                else:
                    statement.add_assignment_clause(
                        AssignmentClause(col.db_field_name,
                                         col.to_database(val)))

        if statement.get_context_size() > 0 or self.instance._has_counter:
            for name, col in self.model._primary_keys.items():
                # only include clustering key if clustering key is not null, and non static columns are changed to avoid cql error
                if (null_clustering_key
                        or static_changed_only) and (not col.partition_key):
                    continue
                statement.add_where_clause(
                    WhereClause(col.db_field_name, EqualsOperator(),
                                col.to_database(getattr(self.instance, name))))
            self._execute(statement)

        if not null_clustering_key:
            self._delete_null_columns()