def connect(self):
     with self._connect_lock:
         if not self.connected or self.connection is None:
             settings = self.settings_dict
             self.connection = CassandraConnection(self.alias, **settings)
             connection_created.send(sender=self.__class__, connection=self)
             self.connected = True
示例#2
0
class DatabaseWrapper(NonrelDatabaseWrapper):

    vendor = 'cassandra'

    def __init__(self, *args, **kwargs):
        super(DatabaseWrapper, self).__init__(*args, **kwargs)

        # Set up the associated backend objects
        self.features = DatabaseFeatures(self)
        self.ops = DatabaseOperations(self)
        self.client = DatabaseClient(self)
        self.creation = DatabaseCreation(self)
        self.validation = DatabaseValidation(self)
        self.introspection = DatabaseIntrospection(self)

        self.commit_on_exit = False
        self.connected = False
        self.autocommit = True

        del self.connection

    def connect(self):
        if not self.connected or self.connection is None:
            settings = self.settings_dict
            self.connection = CassandraConnection(**settings)
            connection_created.send(sender=self.__class__, connection=self)
            self.connected = True

    def __getattr__(self, attr):
        if attr == "connection":
            assert not self.connected
            self.connect()
            return getattr(self, attr)
        raise AttributeError(attr)

    def reconnect(self):

        if self.connected:
            self.connection.close_all()
            del self.connection
            self.connected = False
        self.connect()

    def close(self):
        pass

    def _commit(self):
        pass

    def _rollback(self):
        pass

    def _cursor(self):
        return CursorWrapper(self.connection.cursor(), self)

    def schema_editor(self, *args, **kwargs):
        """
        Returns a new instance of this backend's SchemaEditor (Django>=1.7)
        """
        return DatabaseSchemaEditor(self, *args, **kwargs)
class DatabaseWrapper(NonrelDatabaseWrapper):

    vendor = 'cassandra'

    def __init__(self, *args, **kwargs):
        super(DatabaseWrapper, self).__init__(*args, **kwargs)

        # Set up the associated backend objects
        self.features = DatabaseFeatures(self)
        self.ops = DatabaseOperations(self)
        self.client = DatabaseClient(self)
        self.creation = DatabaseCreation(self)
        self.validation = DatabaseValidation(self)
        self.introspection = DatabaseIntrospection(self)

        self.commit_on_exit = False
        self.connected = False
        self.autocommit = True

        del self.connection

    def connect(self):
        if not self.connected or self.connection is None:
            settings = self.settings_dict
            self.connection = CassandraConnection(**settings)
            connection_created.send(sender=self.__class__, connection=self)
            self.connected = True

    def __getattr__(self, attr):
        if attr == "connection":
            assert not self.connected
            self.connect()
            return getattr(self, attr)
        raise AttributeError(attr)

    def reconnect(self):

        if self.connected:
            self.connection.close_all()
            del self.connection
            self.connected = False
        self.connect()

    def close(self):
        pass

    def _commit(self):
        pass

    def _rollback(self):
        pass

    def _cursor(self):
        return CursorWrapper(self.connection.cursor(), self)

    def schema_editor(self, *args, **kwargs):
        """
        Returns a new instance of this backend's SchemaEditor (Django>=1.7)
        """
        return DatabaseSchemaEditor(self, *args, **kwargs)
    def test_register_connection_called_first_time_with_proper_options(
            self, connection_mock):

        settings = self.cassandra_connection.settings_dict
        connection = CassandraConnection('default', **settings)
        connection_mock.get_connection.side_effect = CQLEngineException()
        connection.register()
        connection_mock.register_connection.assert_called_once_with(
            'default',
            hosts=connection.hosts,
            default=mock.ANY,
            cluster_options=connection.cluster_options,
            **connection.connection_options)
class CassandraConnectionTestCase(TestCase):

    def setUp(self):

        self.connection = CassandraConnection(**connection.settings_dict)

    def test_cursor(self):

        self.assertIsInstance(self.connection.cursor(), FakeCursor)

    def test_connected_to_db(self):

        from cqlengine import connection as cql_connection

        self.assertIsInstance(cql_connection.cluster, Cluster)
        self.assertIsNotNone(cql_connection.session)

    def test_session_property(self):

        from cqlengine import connection as cql_connection

        self.assertEqual(self.connection.session, cql_connection.session)

    def test_cluster_property(self):

        from cqlengine import connection as cql_connection

        self.assertEqual(self.connection.cluster, cql_connection.cluster)
示例#6
0
    def test_connection_register_called_second_time(
            self, connection_mock):
        settings = self.cassandra_connection.settings_dict
        CassandraConnection('default', **settings)
        connection_mock.get_connection.side_effect = CQLEngineException()

        self.assertFalse(connection_mock.register_connection.called)
    def test_connection_setup_called_second_time(self, connection_mock):

        settings = self.cassandra_connection.settings_dict
        connection_mock.cluster = Cluster()
        CassandraConnection(**settings)

        self.assertFalse(connection_mock.setup.called)
示例#8
0
 def connect(self):
     with self._connect_lock:
         if not self.connected or self.connection is None:
             settings = self.settings_dict
             self.connection = CassandraConnection(self.alias, **settings)
             connection_created.send(sender=self.__class__, connection=self)
             self.connected = True
示例#9
0
def setup_cassandra_object_mapper(alias="cassandra"):
    try:
        from dse.cqlengine import connection
    except ImportError:
        from cassandra.cqlengine import connection

    db = get_database(None, alias=alias)
    CassandraConnection("default", **db.settings_dict).register()
    def test_connection_setup_called_first_time_with_proper_options(
            self, connection_mock):

        settings = self.cassandra_connection.settings_dict
        connection_mock.cluster = None
        connection = CassandraConnection(**settings)

        connection_mock.setup.assert_called_once_with(
            connection.hosts, connection.keyspace,
            **settings['OPTIONS']['connection'])
示例#11
0
    def test_connection_setup_called_second_time_session_is_shutdown(
            self, connection_mock):

        settings = self.cassandra_connection.settings_dict
        session_mock = Mock()
        session_mock.is_shutdown = True
        connection_mock.get_session.return_value = session_mock
        CassandraConnection(**settings)

        self.assertTrue(connection_mock.setup.called)
示例#12
0
    def test_connection_auth_provider_not_changed(self, register_mock):

        settings = copy(self.cassandra_connection.settings_dict)
        settings['USER'] = '******'
        settings['PASSWORD'] = '******'
        settings['OPTIONS']['connection'] = {}
        settings['OPTIONS']['connection']['auth_provider'] = 'sth'
        connection = CassandraConnection('default', **settings)

        self.assertEqual(connection.cluster_options['auth_provider'],
                         settings['OPTIONS']['connection']['auth_provider'])
        register_mock.assert_called_once()
示例#13
0
class DatabaseWrapper(BaseDatabaseWrapper):

    Database = Database
    vendor = 'cassandra'

    operators = {
        'exact': '= %s',
        'contains': 'CONTAINS %s',
        'gt': '> %s',
        'gte': '>= %s',
        'lt': '< %s',
        'lte': '<= %s'
    }

    client = None
    # Classes instantiated in __init__().
    client_class = CassandraDatabaseClient
    creation_class = CassandraDatabaseCreation
    features_class = CassandraDatabaseFeatures
    introspection_class = CassandraDatabaseIntrospection
    ops_class = CassandraDatabaseOperations
    validation_class = CassandraDatabaseValidation

    def __init__(self, *args, **kwargs):
        super(DatabaseWrapper, self).__init__(*args, **kwargs)

        self.commit_on_exit = False
        self.connected = False
        self.autocommit = True
        self._connect_lock = threading.RLock()

        if self.client is None:
            # Set up the associated backend objects
            self.features = CassandraDatabaseFeatures(self)
            self.ops = CassandraDatabaseOperations(self)
            self.client = CassandraDatabaseClient(self)
            self.creation = CassandraDatabaseCreation(self)
            self.validation = CassandraDatabaseValidation(self)
            self.introspection = CassandraDatabaseIntrospection(self)

        del self.connection

    def get_connection_params(self):
        return {}

    def get_new_connection(self, conn_params):
        return FakeConnection()

    def init_connection_state(self):
        pass

    def _set_autocommit(self, autocommit):
        pass

    def connect(self):
        with self._connect_lock:
            if not self.connected or self.connection is None:
                settings = self.settings_dict
                self.connection = CassandraConnection(self.alias, **settings)
                connection_created.send(sender=self.__class__, connection=self)
                self.connected = True

    def __getattr__(self, attr):
        if attr == "connection":
            assert not self.connected
            self.connect()
            return getattr(self, attr)
        raise AttributeError(attr)

    def reconnect(self):
        with self._connect_lock:
            if self.connected:
                self.connection.unregister()
                del self.connection
                self.connected = False
            self.connect()

    def close_if_unusable_or_obsolete(self):
        self.connect()

    def close(self):
        pass

    def _commit(self):
        pass

    def _rollback(self):
        pass

    def _cursor(self, *args, **kwargs):
        keyspace = self.settings_dict['NAME']
        if not self.connection.cluster.schema_metadata_enabled and \
                keyspace not in self.connection.cluster.metadata.keyspaces:
            self.connection.cluster.refresh_schema_metadata()

        self.connection.cluster.metadata.keyspaces[keyspace]
        return CursorWrapper(self.connection.cursor(), self)

    def schema_editor(self, *args, **kwargs):
        """
        Returns a new instance of this backends' SchemaEditor (Django>=1.7)
        """
        return CassandraDatabaseSchemaEditor(self, *args, **kwargs)
class CassandraConnectionTestCase(TestCase):

    def setUp(self):
        self.cassandra_connection = get_cassandra_connection()
        self.connection = CassandraConnection(
            **self.cassandra_connection.settings_dict)

    def test_cursor(self):

        self.assertIsInstance(self.connection.cursor(), Cursor)
        self.assertEqual(self.connection.cursor().connection, self.connection)

    def test_connected_to_db(self):

        from cassandra.cqlengine import connection as cql_connection

        self.assertIsInstance(cql_connection.cluster, Cluster)
        self.assertIsNotNone(cql_connection.session)

    def test_session_property(self):

        from cassandra.cqlengine import connection as cql_connection

        self.assertEqual(self.connection.session, cql_connection.session)

    def test_cluster_property(self):

        from cassandra.cqlengine import connection as cql_connection

        self.assertEqual(self.connection.cluster, cql_connection.cluster)

    def test_connection_options(self):
        connection_options = \
            self.cassandra_connection.settings_dict['OPTIONS']['connection']
        self.assertEqual(
            self.connection.connection_options, connection_options)

    @patch("cassandra.cqlengine.connection")
    def test_connection_setup_called_first_time_with_proper_options(
            self, connection_mock):

        settings = self.cassandra_connection.settings_dict
        connection_mock.cluster = None
        connection = CassandraConnection(**settings)

        connection_mock.setup.assert_called_once_with(
            connection.hosts, connection.keyspace,
            **settings['OPTIONS']['connection'])

    @patch("django_cassandra_engine.connection.connection")
    def test_connection_setup_called_second_time(
            self, connection_mock):

        settings = self.cassandra_connection.settings_dict
        connection_mock.cluster = Cluster()
        CassandraConnection(**settings)

        self.assertFalse(connection_mock.setup.called)

    def test_connection_auth_provider_added_to_connection_options(self):

        settings = self.cassandra_connection.settings_dict
        settings['USER'] = '******'
        settings['PASSWORD'] = '******'
        connection = CassandraConnection(**settings)

        self.assertIsInstance(connection.connection_options['auth_provider'],
                              PlainTextAuthProvider)

    def test_connection_auth_provider_not_changed(self):

        settings = self.cassandra_connection.settings_dict
        settings['USER'] = '******'
        settings['PASSWORD'] = '******'
        settings['OPTIONS']['connection'] = {}
        settings['OPTIONS']['connection']['auth_provider'] = 'sth'
        connection = CassandraConnection(**settings)

        self.assertEqual(connection.connection_options['auth_provider'],
                         settings['OPTIONS']['connection']['auth_provider'])

    def test_connection_session_options_default_timeout(self):

        session_opts = \
            self.cassandra_connection.settings_dict['OPTIONS']['session']
        self.assertEqual(self.connection.session_options, session_opts)
        self.assertEqual(self.connection.session.default_timeout,
                         session_opts.get('default_timeout'))

    def test_raw_cql_cursor_queries(self):
        cursor = self.connection.cursor()
        self.assertEqual(
            cursor.execute("SELECT count(*) from example_model")[0]['count'], 0
        )

        cursor.execute("INSERT INTO example_model (id) VALUES (1)")

        self.assertEqual(
            cursor.execute("SELECT count(*) from example_model")[0]['count'], 1
        )
示例#15
0
class DatabaseWrapper(BaseDatabaseWrapper):

    Database = Database
    vendor = 'cassandra'

    operators = {
        'exact': '= %s',
        'contains': 'CONTAINS %s',
        'gt': '> %s',
        'gte': '>= %s',
        'lt': '< %s',
        'lte': '<= %s'
    }

    client = None
    # Classes instantiated in __init__().
    client_class = CassandraDatabaseClient
    creation_class = CassandraDatabaseCreation
    features_class = CassandraDatabaseFeatures
    introspection_class = CassandraDatabaseIntrospection
    ops_class = CassandraDatabaseOperations
    validation_class = CassandraDatabaseValidation

    def __init__(self, *args, **kwargs):
        super(DatabaseWrapper, self).__init__(*args, **kwargs)

        self.commit_on_exit = False
        self.connected = False
        self.autocommit = True
        self._connect_lock = threading.RLock()

        if self.client is None:
            # Set up the associated backend objects
            self.features = CassandraDatabaseFeatures(self)
            self.ops = CassandraDatabaseOperations(self)
            self.client = CassandraDatabaseClient(self)
            self.creation = CassandraDatabaseCreation(self)
            self.validation = CassandraDatabaseValidation(self)
            self.introspection = CassandraDatabaseIntrospection(self)

        del self.connection

    def get_connection_params(self):
        return {}

    def get_new_connection(self, conn_params):
        return FakeConnection()

    def init_connection_state(self):
        pass

    def _set_autocommit(self, autocommit):
        pass

    def connect(self):
        with self._connect_lock:
            if not self.connected or self.connection is None:
                settings = self.settings_dict
                self.connection = CassandraConnection(self.alias, **settings)
                connection_created.send(sender=self.__class__, connection=self)
                self.connected = True

    def __getattr__(self, attr):
        if attr == "connection":
            assert not self.connected
            self.connect()
            return getattr(self, attr)
        raise AttributeError(attr)

    def reconnect(self):
        with self._connect_lock:
            if self.connected:
                self.connection.unregister()
                del self.connection
                self.connected = False
            self.connect()

    def close_if_unusable_or_obsolete(self):
        self.connect()

    def close(self):
        pass

    def _commit(self):
        pass

    def _rollback(self):
        pass

    def _cursor(self, *args, **kwargs):
        keyspace = self.settings_dict['NAME']
        if not self.connection.cluster.schema_metadata_enabled and \
                keyspace not in self.connection.cluster.metadata.keyspaces:
            self.connection.cluster.refresh_schema_metadata()

        self.connection.cluster.metadata.keyspaces[keyspace]
        return CursorWrapper(self.connection.cursor(), self)

    def schema_editor(self, *args, **kwargs):
        """
        Returns a new instance of this backends' SchemaEditor (Django>=1.7)
        """
        return CassandraDatabaseSchemaEditor(self, *args, **kwargs)
示例#16
0
 def setUp(self):
     connection = connections['cassandra']
     self.connection = CassandraConnection(**connection.settings_dict)
 def setUp(self):
     self.cassandra_connection = get_cassandra_connection()
     self.connection = CassandraConnection(
         **self.cassandra_connection.settings_dict)
class CassandraConnectionTestCase(TestCase):
    def setUp(self):
        self.cassandra_connection = get_cassandra_connection()
        self.connection = CassandraConnection(
            **self.cassandra_connection.settings_dict)

    def test_cursor(self):

        self.assertIsInstance(self.connection.cursor(), Cursor)
        self.assertEqual(self.connection.cursor().connection, self.connection)

    def test_connected_to_db(self):

        from cassandra.cqlengine import connection as cql_connection

        self.assertIsInstance(cql_connection.cluster, Cluster)
        self.assertIsNotNone(cql_connection.session)

    def test_session_property(self):

        from cassandra.cqlengine import connection as cql_connection

        self.assertEqual(self.connection.session, cql_connection.session)

    def test_cluster_property(self):

        from cassandra.cqlengine import connection as cql_connection

        self.assertEqual(self.connection.cluster, cql_connection.cluster)

    def test_connection_options(self):
        connection_options = \
            self.cassandra_connection.settings_dict['OPTIONS']['connection']
        self.assertEqual(self.connection.connection_options,
                         connection_options)

    @patch("cassandra.cqlengine.connection")
    def test_connection_setup_called_first_time_with_proper_options(
            self, connection_mock):

        settings = self.cassandra_connection.settings_dict
        connection_mock.cluster = None
        connection = CassandraConnection(**settings)

        connection_mock.setup.assert_called_once_with(
            connection.hosts, connection.keyspace,
            **settings['OPTIONS']['connection'])

    @patch("django_cassandra_engine.connection.connection")
    def test_connection_setup_called_second_time(self, connection_mock):

        settings = self.cassandra_connection.settings_dict
        connection_mock.cluster = Cluster()
        CassandraConnection(**settings)

        self.assertFalse(connection_mock.setup.called)

    def test_connection_auth_provider_added_to_connection_options(self):

        settings = self.cassandra_connection.settings_dict
        settings['USER'] = '******'
        settings['PASSWORD'] = '******'
        connection = CassandraConnection(**settings)

        self.assertIsInstance(connection.connection_options['auth_provider'],
                              PlainTextAuthProvider)

    def test_connection_auth_provider_not_changed(self):

        settings = self.cassandra_connection.settings_dict
        settings['USER'] = '******'
        settings['PASSWORD'] = '******'
        settings['OPTIONS']['connection'] = {}
        settings['OPTIONS']['connection']['auth_provider'] = 'sth'
        connection = CassandraConnection(**settings)

        self.assertEqual(connection.connection_options['auth_provider'],
                         settings['OPTIONS']['connection']['auth_provider'])

    def test_connection_session_options_default_timeout(self):

        session_opts = \
            self.cassandra_connection.settings_dict['OPTIONS']['session']
        self.assertEqual(self.connection.session_options, session_opts)
        self.assertEqual(self.connection.session.default_timeout,
                         session_opts.get('default_timeout'))

    def test_connection_session_default_consistency(self):

        settings = self.cassandra_connection.settings_dict
        settings['OPTIONS']['connection'] = {
            'consistency': ConsistencyLevel.ALL
        }
        connection = CassandraConnection(**settings)
        self.assertEqual(connection.session.default_consistency_level,
                         ConsistencyLevel.ALL)

    def test_raw_cql_cursor_queries(self):
        cursor = self.connection.cursor()
        self.assertEqual(
            cursor.execute("SELECT count(*) from example_model")[0]['count'],
            0)

        cursor.execute("INSERT INTO example_model (id) VALUES (1)")

        self.assertEqual(
            cursor.execute("SELECT count(*) from example_model")[0]['count'],
            1)
 def setUp(self):
     self.cassandra_connection = get_cassandra_connection()
     self.connection = CassandraConnection(
         **self.cassandra_connection.settings_dict)
    def setUp(self):

        self.connection = CassandraConnection(**connection.settings_dict)
 def setUp(self):
     connection = connections['cassandra']
     self.connection = CassandraConnection(**connection.settings_dict)
class DatabaseWrapper(BaseDatabaseWrapper):

    Database = Database
    vendor = 'cassandra'

    def __init__(self, *args, **kwargs):
        super(DatabaseWrapper, self).__init__(*args, **kwargs)

        # Set up the associated backend objects
        self.features = CassandraDatabaseFeatures(self)
        self.ops = CassandraDatabaseOperations(self)
        self.client = CassandraDatabaseClient(self)
        self.creation = CassandraDatabaseCreation(self)
        self.validation = CassandraDatabaseValidation(self)
        self.introspection = CassandraDatabaseIntrospection(self)

        self.commit_on_exit = False
        self.connected = False
        self.autocommit = True

        del self.connection

    def get_connection_params(self):
        return {}

    def get_new_connection(self, conn_params):
        return FakeConnection()

    def init_connection_state(self):
        pass

    def _set_autocommit(self, autocommit):
        pass

    def connect(self):
        if not self.connected or self.connection is None:
            settings = self.settings_dict
            self.connection = CassandraConnection(**settings)
            connection_created.send(sender=self.__class__, connection=self)
            self.connected = True

    def __getattr__(self, attr):
        if attr == "connection":
            assert not self.connected
            self.connect()
            return getattr(self, attr)
        raise AttributeError(attr)

    def reconnect(self):

        if self.connected:
            self.connection.close_all()
            del self.connection
            self.connected = False
        self.connect()

    def close_if_unusable_or_obsolete(self):
        self.connect()

    def close(self):
        pass

    def _commit(self):
        pass

    def _rollback(self):
        pass

    def _cursor(self):
        # Error if keyspace for cursor doesn't exist. django-nose uses
        # a cursor to check if it should create a db or not. Any
        # exception will do, and this will raise a KeyError if the
        # keyspace doesn't exist.
        from cassandra.cqlengine import connection
        keyspace = self.settings_dict['NAME']
        connection.cluster.metadata.keyspaces[keyspace]
        return CursorWrapper(self.connection.cursor(), self)

    def schema_editor(self, *args, **kwargs):
        """
        Returns a new instance of this backends' SchemaEditor (Django>=1.7)
        """
        return CassandraDatabaseSchemaEditor(self, *args, **kwargs)
class CassandraConnectionTestCase(TestCase):

    def setUp(self):
        connection = connections['cassandra']
        self.connection = CassandraConnection(**connection.settings_dict)

    def test_cursor(self):

        self.assertIsInstance(self.connection.cursor(), FakeCursor)

    def test_connected_to_db(self):

        from cqlengine import connection as cql_connection

        self.assertIsInstance(cql_connection.cluster, Cluster)
        self.assertIsNotNone(cql_connection.session)

    def test_session_property(self):

        from cqlengine import connection as cql_connection

        self.assertEqual(self.connection.session, cql_connection.session)

    def test_cluster_property(self):

        from cqlengine import connection as cql_connection

        self.assertEqual(self.connection.cluster, cql_connection.cluster)

    def test_connection_options(self):
        connection = connections['cassandra']
        connection_options = connection.settings_dict['OPTIONS']['connection']
        self.assertEqual(
            self.connection.connection_options, connection_options)

    @patch("cqlengine.connection")
    def test_connection_setup_called_first_time_with_proper_options(
            self, connection_mock):

        settings = connections['cassandra'].settings_dict
        connection_mock.cluster = None
        connection = CassandraConnection(**settings)

        connection_mock.setup.assert_called_once_with(
            connection.hosts, connection.keyspace,
            **settings['OPTIONS']['connection'])

    @patch("django_cassandra_engine.connection.connection")
    def test_connection_setup_called_second_time(
            self, connection_mock):

        settings = connections['cassandra'].settings_dict
        connection_mock.cluster = Cluster()
        CassandraConnection(**settings)

        self.assertFalse(connection_mock.setup.called)

    def test_connection_auth_provider_added_to_connection_options(self):

        settings = connections['cassandra'].settings_dict
        settings['USER'] = '******'
        settings['PASSWORD'] = '******'
        connection = CassandraConnection(**settings)

        self.assertIsInstance(connection.connection_options['auth_provider'],
                              PlainTextAuthProvider)

    def test_connection_auth_provider_not_changed(self):

        settings = connections['cassandra'].settings_dict
        settings['USER'] = '******'
        settings['PASSWORD'] = '******'
        settings['OPTIONS']['connection'] = {}
        settings['OPTIONS']['connection']['auth_provider'] = 'sth'
        connection = CassandraConnection(**settings)

        self.assertEqual(connection.connection_options['auth_provider'],
                         settings['OPTIONS']['connection']['auth_provider'])

    def test_connection_session_options_default_timeout(self):

        session_opts = \
            connections['cassandra'].settings_dict['OPTIONS']['session']
        self.assertEqual(self.connection.session_options, session_opts)
        self.assertEqual(self.connection.session.default_timeout,
                         session_opts.get('default_timeout'))