def test_named_table_pk_token_function(self):
        """
        Test to ensure that token function work with named tables.

        @since 3.2
        @jira_ticket PYTHON-272
        @expected_result partition key token functions should all for pagination. Prior to Python-272
        this would fail with an AttributeError

        @test_category object_mapper
        """

        for i in range(5):
            TokenTestModel.create(key=i, val=i)
        named = NamedTable(DEFAULT_KEYSPACE, TokenTestModel.__table_name__)

        query = named.all().limit(1)
        first_page = list(query)
        last = first_page[-1]
        self.assertTrue(len(first_page) is 1)
        next_page = list(query.filter(pk__token__gt=functions.Token(last.key)))
        self.assertTrue(len(next_page) is 1)
예제 #2
0
    def test_named_table_pk_token_function(self):
        """
        Test to ensure that token function work with named tables.

        @since 3.2
        @jira_ticket PYTHON-272
        @expected_result partition key token functions should all for pagination. Prior to Python-272
        this would fail with an AttributeError

        @test_category object_mapper
        """

        for i in range(5):
            TokenTestModel.create(key=i, val=i)
        named = NamedTable(DEFAULT_KEYSPACE, TokenTestModel.__table_name__)

        query = named.all().limit(1)
        first_page = list(query)
        last = first_page[-1]
        self.assertTrue(len(first_page) is 1)
        next_page = list(query.filter(pk__token__gt=functions.Token(last.key)))
        self.assertTrue(len(next_page) is 1)
예제 #3
0
from cassandra import metadata
from cassandra.cqlengine import CQLEngineException
from cassandra.cqlengine import columns, query
from cassandra.cqlengine.connection import execute, get_cluster, format_log_context
from cassandra.cqlengine.models import Model
from cassandra.cqlengine.named import NamedTable
from cassandra.cqlengine.usertype import UserType

CQLENG_ALLOW_SCHEMA_MANAGEMENT = 'CQLENG_ALLOW_SCHEMA_MANAGEMENT'

Field = namedtuple('Field', ['name', 'type'])

log = logging.getLogger(__name__)

# system keyspaces
schema_columnfamilies = NamedTable('system', 'schema_columnfamilies')


def _get_context(keyspaces, connections):
    """Return all the execution contexts"""

    if keyspaces:
        if not isinstance(keyspaces, (list, tuple)):
            raise ValueError('keyspaces must be a list or a tuple.')

    if connections:
        if not isinstance(connections, (list, tuple)):
            raise ValueError('connections must be a list or a tuple.')

    keyspaces = keyspaces if keyspaces else [None]
    connections = connections if connections else [None]
예제 #4
0
class CassandraDAO:
    try:
        db_name = 'Cassandra'
        cassandra = CassandraModel()
        setup(["127.0.0.1"], "test_keyspace")
        inscritos = NamedTable("test_keyspace", "inscritos")
    except Exception as e:
        pass

    def insertObject(self, objeto):
        id_ = uuid.uuid4().hex
        self.cassandra.session.execute(
            """
				INSERT INTO inscritos (id, ANO_NASCIMENTO, PESO, ALTURA, CABECA, CALCADO, CINTURA, RELIGIAO, MUN_NASCIMENTO, UF_NASCIMENTO, PAIS_NASCIMENTO, ESTADO_CIVIL, SEXO, ESCOLARIDADE, VINCULACAO_ANO, DISPENSA, ZONA_RESIDENCIAL, MUN_RESIDENCIA, UF_RESIDENCIA, PAIS_RESIDENCIA, JSM, MUN_JSM, UF_JSM)
				VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
			""", (id_, objeto['ANO_NASCIMENTO'], objeto['PESO'], objeto['ALTURA'],
         objeto['CABECA'], objeto['CALCADO'], objeto['CINTURA'],
         objeto['RELIGIAO'], objeto['MUN_NASCIMENTO'], objeto['UF_NASCIMENTO'],
         objeto['PAIS_NASCIMENTO'], objeto['ESTADO_CIVIL'], objeto['SEXO'],
         objeto['ESCOLARIDADE'], objeto['VINCULACAO_ANO'], objeto['DISPENSA'],
         objeto['ZONA_RESIDENCIAL'], objeto['MUN_RESIDENCIA'],
         objeto['UF_RESIDENCIA'], objeto['PAIS_RESIDENCIA'], objeto['JSM'],
         objeto['MUN_JSM'], objeto['UF_JSM']))

    def insertGroupOfObjects(self, objetos):
        insert_user = self.cassandra.session.prepare(
            "INSERT INTO inscritos (id, ANO_NASCIMENTO, PESO, ALTURA, CABECA, CALCADO, CINTURA, RELIGIAO, MUN_NASCIMENTO, UF_NASCIMENTO, PAIS_NASCIMENTO, ESTADO_CIVIL, SEXO, ESCOLARIDADE, VINCULACAO_ANO, DISPENSA, ZONA_RESIDENCIAL, MUN_RESIDENCIA, UF_RESIDENCIA, PAIS_RESIDENCIA, JSM, MUN_JSM, UF_JSM)VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
        )
        objetos_parts = [objetos[i:i + 50] for i in range(0, len(objetos), 50)]
        for parts_objects in objetos_parts:
            batch = BatchStatement()
            for objeto in parts_objects:
                id_ = uuid.uuid4().hex
                batch.add(
                    insert_user,
                    (id_, objeto['ANO_NASCIMENTO'], objeto['PESO'],
                     objeto['ALTURA'], objeto['CABECA'], objeto['CALCADO'],
                     objeto['CINTURA'], objeto['RELIGIAO'],
                     objeto['MUN_NASCIMENTO'], objeto['UF_NASCIMENTO'],
                     objeto['PAIS_NASCIMENTO'], objeto['ESTADO_CIVIL'],
                     objeto['SEXO'], objeto['ESCOLARIDADE'],
                     objeto['VINCULACAO_ANO'], objeto['DISPENSA'],
                     objeto['ZONA_RESIDENCIAL'], objeto['MUN_RESIDENCIA'],
                     objeto['UF_RESIDENCIA'], objeto['PAIS_RESIDENCIA'],
                     objeto['JSM'], objeto['MUN_JSM'], objeto['UF_JSM']))
            self.cassandra.session.execute(batch)

    def getAllObjects(self):
        all_objects = self.inscritos.objects.all()
        return all_objects, all_objects.count()

    def getQuantityOfValuesOnDB(self):
        quantity = self.inscritos.objects.count()
        return quantity

    def getByCivilStatus(self, civil_status):
        query = self.inscritos.objects.filter(estado_civil=civil_status)
        result = query.allow_filtering()
        return result, result.count()

    def updateCivilStatus(self, old_status, new_status):
        list_to_update, quantity = self.getByCivilStatus(old_status)
        enrolled = {}
        for insc in list_to_update:
            enrolled[insc['id']] = insc
            self.cassandra.session.execute(
                "UPDATE inscritos SET estado_civil = %s WHERE id = %s;",
                (new_status, insc['id']))
        return enrolled, len(enrolled)

    def deleteByCivilStatus(self, civil_status_to_delete):
        list_to_delete, quantity = self.getByCivilStatus(
            civil_status_to_delete)
        deleted = {}
        query = "DELETE FROM inscritos WHERE id=%s;"
        for insc in list_to_delete:
            deleted[insc['id']] = insc
            self.cassandra.session.execute(query, [insc['id']])
        return deleted, len(deleted)

    def deleteAllObjects(self):
        query = "TRUNCATE inscritos;"
        self.cassandra.session.execute(query)