Пример #1
0
    def test_statement(self):
        ist = InsertStatement('table', None)
        ist.add_assignment_clause(AssignmentClause('a', 'b'))
        ist.add_assignment_clause(AssignmentClause('c', 'd'))

        self.assertEqual(six.text_type(ist),
                         'INSERT INTO table ("a", "c") VALUES (%(0)s, %(1)s)')
    def test_statement(self):
        ist = InsertStatement('table', None)
        ist.add_assignment(Column(db_field='a'), 'b')
        ist.add_assignment(Column(db_field='c'), 'd')

        self.assertEqual(six.text_type(ist),
                         'INSERT INTO table ("a", "c") VALUES (%(0)s, %(1)s)')
Пример #3
0
def insert_query(table: str, data: dict, mode: str = 'INSERT'):
    assignment_clauses = assignment_clauses_from_data(data)
    if mode == 'REPLACE':
        statement = InsertStatement(table, assignment_clauses)
    else:
        statement = InsertStatement(table,
                                    assignment_clauses,
                                    if_not_exists=True)
    return str(statement), statement.get_context()
Пример #4
0
    def test_statement(self):
        ist = InsertStatement('table', None)
        ist.add_assignment(Column(db_field='a'), 'b')
        ist.add_assignment(Column(db_field='c'), 'd')

        self.assertEqual(
            six.text_type(ist),
            'INSERT INTO table ("a", "c") VALUES (%(0)s, %(1)s)'
        )
Пример #5
0
    def test_statement(self):
        ist = InsertStatement('table', None)
        ist.add_assignment_clause(AssignmentClause('a', 'b'))
        ist.add_assignment_clause(AssignmentClause('c', 'd'))

        self.assertEqual(
            six.text_type(ist),
            'INSERT INTO table ("a", "c") VALUES (%(0)s, %(1)s)'
        )
Пример #6
0
def query_parameters_from_create(collection, data, mode='INSERT'):
    assignment_clauses = assignment_clauses_from_data(data)
    if mode == 'REPLACE':
        statement = InsertStatement(
            table=collection, assignments=assignment_clauses,
        )
    else:
        statement = InsertStatement(
            table=collection, assignments=assignment_clauses,
            if_not_exists=True
        )
    return str(statement), statement.get_context()
Пример #7
0
    async def async_save(self):
        """
        Creates / updates a row.
        This is a blind insert 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

        nulled_fields = set()
        if self.instance._has_counter or self.instance._can_update():
            if self.instance._has_counter:
                warn("'create' and 'save' actions on Counters are deprecated. "
                     "A future version will disallow this. Use the 'update' "
                     "mechanism instead.")
            return await self.async_update()
        else:
            insert = InsertStatement(
                self.column_family_name,
                ttl=self._ttl,
                timestamp=self._timestamp,
                if_not_exists=self._if_not_exists,
            )
            static_save_only = (False if len(self.instance._clustering_keys)
                                == 0 else True)
            for name, col in self.instance._clustering_keys.items():
                static_save_only = static_save_only and col._val_is_null(
                    getattr(self.instance, name, None))
            for name, col in self.instance._columns.items():
                if (static_save_only and not col.static
                        and not col.partition_key):
                    continue
                val = getattr(self.instance, name, None)
                if col._val_is_null(val):
                    if self.instance._values[name].changed:
                        nulled_fields.add(col.db_field_name)
                    continue
                if col.has_default and not self.instance._values[name].changed:
                    # Ensure default columns included in a save()
                    # are marked as explicit, to get them *persisted* properly
                    self.instance._values[name].explicit = True
                insert.add_assignment(col, getattr(self.instance, name, None))

        # skip query execution if it's empty
        # caused by pointless update queries
        if not insert.is_empty:
            await self._async_execute(insert)
        # delete any nulled columns
        if not static_save_only:
            self._delete_null_columns()
Пример #8
0
    def save(self):
        """
        Creates / updates a row.
        This is a blind insert 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

        nulled_fields = set()
        if self.instance._has_counter or self.instance._can_update():
            return self.update()
        else:
            insert = InsertStatement(self.column_family_name,
                                     ttl=self._ttl,
                                     timestamp=self._timestamp,
                                     if_not_exists=self._if_not_exists)
            static_save_only = False if len(
                self.instance._clustering_keys) == 0 else True
            for name, col in self.instance._clustering_keys.items():
                static_save_only = static_save_only and col._val_is_null(
                    getattr(self.instance, name, None))
            for name, col in self.instance._columns.items():
                if static_save_only and not col.static and not col.partition_key:
                    continue
                val = getattr(self.instance, name, None)
                if col._val_is_null(val):
                    if self.instance._values[name].changed:
                        nulled_fields.add(col.db_field_name)
                    continue
                insert.add_assignment_clause(
                    AssignmentClause(
                        col.db_field_name,
                        col.to_database(getattr(self.instance, name, None))))

        # skip query execution if it's empty
        # caused by pointless update queries
        if not insert.is_empty:
            self._execute(insert)
        # delete any nulled columns
        if not static_save_only:
            self._delete_null_columns()
Пример #9
0
    def save(self):
        """
        Creates / updates a row.
        This is a blind insert 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

        nulled_fields = set()
        if self.instance._has_counter or self.instance._can_update():
            if self.instance._has_counter:
                warn("'create' and 'save' actions on Counters are deprecated. A future version will disallow this. Use the 'update' mechanism instead.")
            return self.update()
        else:
            insert = InsertStatement(self.column_family_name, ttl=self._ttl, timestamp=self._timestamp, if_not_exists=self._if_not_exists)
            static_save_only = False if len(self.instance._clustering_keys) == 0 else True
            for name, col in self.instance._clustering_keys.items():
                static_save_only = static_save_only and col._val_is_null(getattr(self.instance, name, None))
            for name, col in self.instance._columns.items():
                if static_save_only and not col.static and not col.partition_key:
                    continue
                val = getattr(self.instance, name, None)
                if col._val_is_null(val):
                    if self.instance._values[name].changed:
                        nulled_fields.add(col.db_field_name)
                    continue
                insert.add_assignment_clause(AssignmentClause(
                    col.db_field_name,
                    col.to_database(getattr(self.instance, name, None))
                ))

        # skip query execution if it's empty
        # caused by pointless update queries
        if not insert.is_empty:
            self._execute(insert)
        # delete any nulled columns
        if not static_save_only:
            self._delete_null_columns()
    def test_context_update(self):
        ist = InsertStatement('table', None)
        ist.add_assignment(Column(db_field='a'), 'b')
        ist.add_assignment(Column(db_field='c'), 'd')

        ist.update_context_id(4)
        self.assertEqual(six.text_type(ist),
                         'INSERT INTO table ("a", "c") VALUES (%(4)s, %(5)s)')
        ctx = ist.get_context()
        self.assertEqual(ctx, {'4': 'b', '5': 'd'})
Пример #11
0
    def test_context_update(self):
        ist = InsertStatement('table', None)
        ist.add_assignment_clause(AssignmentClause('a', 'b'))
        ist.add_assignment_clause(AssignmentClause('c', 'd'))

        ist.update_context_id(4)
        self.assertEqual(
            six.text_type(ist),
            'INSERT INTO table ("a", "c") VALUES (%(4)s, %(5)s)'
        )
        ctx = ist.get_context()
        self.assertEqual(ctx, {'4': 'b', '5': 'd'})
Пример #12
0
 def test_additional_rendering(self):
     ist = InsertStatement('table', ttl=60)
     ist.add_assignment(Column(db_field='a'), 'b')
     ist.add_assignment(Column(db_field='c'), 'd')
     self.assertIn('USING TTL 60', six.text_type(ist))
Пример #13
0
    def _insert_statement(self, partition, cluster):
        # Verifying insert statement
        st = InsertStatement(self.table_name)
        st.add_assignment(Column(db_field='partition'), partition)
        st.add_assignment(Column(db_field='cluster'), cluster)

        st.add_assignment(Column(db_field='count'), 1)
        st.add_assignment(Column(db_field='text'), self.text)
        st.add_assignment(Column(db_field='text_set'), set(("foo", "bar")))
        st.add_assignment(Column(db_field='text_list'), ["foo", "bar"])
        st.add_assignment(Column(db_field='text_map'), {
            "foo": '1',
            "bar": '2'
        })

        execute(st)
        self._verify_statement(st)
Пример #14
0
 def test_additional_rendering(self):
     ist = InsertStatement('table', ttl=60)
     ist.add_assignment_clause(AssignmentClause('a', 'b'))
     ist.add_assignment_clause(AssignmentClause('c', 'd'))
     self.assertIn('USING TTL 60', six.text_type(ist))
Пример #15
0
 def test_where_clause_failure(self):
     """ tests that where clauses cannot be added to Insert statements """
     ist = InsertStatement('table', None)
     with self.assertRaises(StatementException):
         ist.add_where_clause('s')
Пример #16
0
    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

        #Verifying insert statement
        st = InsertStatement(self.table_name)
        st.add_assignment(Column(db_field='partition'), partition)
        st.add_assignment(Column(db_field='cluster'), cluster)

        st.add_assignment(Column(db_field='count'), 1)
        st.add_assignment(Column(db_field='text'), "text_for_db")
        st.add_assignment(Column(db_field='text_set'), set(("foo", "bar")))
        st.add_assignment(Column(db_field='text_list'), ["foo", "bar"])
        st.add_assignment(Column(db_field='text_map'), {"foo": '1', "bar": '2'})

        execute(st)
        self._verify_statement(st)

        # 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)
Пример #17
0
    def _insert_statement(self, partition, cluster):
        # Verifying insert statement
        st = InsertStatement(self.table_name)
        st.add_assignment(Column(db_field='partition'), partition)
        st.add_assignment(Column(db_field='cluster'), cluster)

        st.add_assignment(Column(db_field='count'), 1)
        st.add_assignment(Column(db_field='text'), self.text)
        st.add_assignment(Column(db_field='text_set'), set(("foo", "bar")))
        st.add_assignment(Column(db_field='text_list'), ["foo", "bar"])
        st.add_assignment(Column(db_field='text_map'), {"foo": '1', "bar": '2'})

        execute(st)
        self._verify_statement(st)
Пример #18
0
 def test_additional_rendering(self):
     ist = InsertStatement('table', ttl=60)
     ist.add_assignment_clause(AssignmentClause('a', 'b'))
     ist.add_assignment_clause(AssignmentClause('c', 'd'))
     self.assertIn('USING TTL 60', six.text_type(ist))
Пример #19
0
 def test_where_clause_failure(self):
     """ tests that where clauses cannot be added to Insert statements """
     ist = InsertStatement('table', None)
     with self.assertRaises(StatementException):
         ist.add_where_clause('s')
 def test_additional_rendering(self):
     ist = InsertStatement('table', ttl=60)
     ist.add_assignment(Column(db_field='a'), 'b')
     ist.add_assignment(Column(db_field='c'), 'd')
     self.assertIn('USING TTL 60', six.text_type(ist))
Пример #21
0
    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

        #Verifying insert statement
        st = InsertStatement(self.table_name)
        st.add_assignment(Column(db_field='partition'), partition)
        st.add_assignment(Column(db_field='cluster'), cluster)

        st.add_assignment(Column(db_field='count'), 1)
        st.add_assignment(Column(db_field='text'), "text_for_db")
        st.add_assignment(Column(db_field='text_set'), set(("foo", "bar")))
        st.add_assignment(Column(db_field='text_list'), ["foo", "bar"])
        st.add_assignment(Column(db_field='text_map'), {
            "foo": '1',
            "bar": '2'
        })

        execute(st)
        self._verify_statement(st)

        # 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)